prepare.py 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200
  1. # mypy: allow-untyped-defs
  2. import copy
  3. import warnings
  4. from dataclasses import asdict
  5. from typing import Any, Optional, Union
  6. import torch
  7. from torch._subclasses import FakeTensor
  8. from torch.ao.quantization import (
  9. _DerivedObserverOrFakeQuantize,
  10. FixedQParamsFakeQuantize,
  11. FixedQParamsObserver,
  12. ObserverBase,
  13. ObserverOrFakeQuantize,
  14. PlaceholderObserver,
  15. )
  16. from torch.ao.quantization.backend_config import (
  17. BackendConfig,
  18. DTypeConfig,
  19. get_native_backend_config,
  20. )
  21. from torch.ao.quantization.backend_config.utils import (
  22. get_fusion_pattern_to_root_node_getter,
  23. get_module_to_qat_module,
  24. get_pattern_to_dtype_configs,
  25. )
  26. from torch.ao.quantization.observer import _is_activation_post_process, _PartialWrapper
  27. from torch.ao.quantization.qconfig import _is_reuse_input_qconfig, QConfigAny
  28. from torch.ao.quantization.qconfig_mapping import QConfigMapping
  29. from torch.ao.quantization.quantize import convert, propagate_qconfig_
  30. from torch.ao.quantization.quantizer import (
  31. DerivedQuantizationSpec,
  32. EdgeOrNode,
  33. FixedQParamsQuantizationSpec,
  34. QuantizationSpec,
  35. QuantizationSpecBase,
  36. SharedQuantizationSpec,
  37. )
  38. from torch.ao.quantization.utils import (
  39. _parent_name,
  40. get_qconfig_dtypes,
  41. get_swapped_custom_module_class,
  42. NodePattern,
  43. Pattern,
  44. )
  45. from torch.fx import GraphModule
  46. from torch.fx.graph import Graph, Node
  47. from torch.fx.node import Argument
  48. from ._equalize import is_equalization_observer, node_supports_equalization
  49. from .custom_config import PrepareCustomConfig, StandaloneModuleConfigEntry
  50. from .match_utils import _find_matches, _MatchResultWithQConfig
  51. from .pattern_utils import _sorted_patterns_dict
  52. from .qconfig_mapping_utils import (
  53. _generate_node_name_to_qconfig,
  54. _get_flattened_qconfig_dict,
  55. _update_qconfig_for_fusion,
  56. _update_qconfig_for_qat,
  57. )
  58. from .quantize_handler import (
  59. _default_root_node_getter,
  60. _get_pattern_to_quantize_handlers,
  61. QuantizeHandler,
  62. )
  63. from .utils import (
  64. _insert_dequant_stubs_for_custom_module_lstm_output,
  65. _is_custom_module_lstm,
  66. _maybe_get_custom_module_lstm_from_node_arg,
  67. _qconfig_satisfies_dtype_config_constraints,
  68. all_node_args_have_no_tensors,
  69. assert_and_get_unique_device,
  70. get_custom_module_class_keys,
  71. get_new_attr_name_with_prefix,
  72. get_non_observable_arg_indexes_and_types,
  73. node_arg_is_bias,
  74. node_arg_is_weight,
  75. NON_QUANTIZABLE_WEIGHT_OPS,
  76. ObservedGraphModuleAttrs,
  77. )
  78. __all__ = [
  79. "insert_observers_for_model",
  80. "prepare",
  81. "propagate_dtypes_for_known_nodes",
  82. ]
  83. # list of dtypes to not add observers to
  84. _DO_NOT_OBS_DTYPE_LIST = [int, float, torch.bool, None]
  85. _OBS_DTYPE_LIST = [
  86. torch.quint8,
  87. torch.qint8,
  88. torch.qint32,
  89. torch.float16,
  90. torch.uint8,
  91. torch.int8,
  92. torch.int16,
  93. torch.int32,
  94. torch.float8_e5m2,
  95. torch.float8_e4m3fn,
  96. ]
  97. _DEFAULT_FP32_OBS_OR_FQ_CTR = PlaceholderObserver.with_args(dtype=torch.float)
  98. # note: the following default target dtype info dicts are temporary,
  99. # should be moved to the new programmable API class soon
  100. _DEFAULT_FP32_QCONFIG_FOR_TARGET_DTYPE_INFO = {
  101. "input_act_obs_or_fq_ctr": torch.ao.quantization.qconfig._default_fp32_placeholder_qconfig.activation,
  102. "output_act_obs_or_fq_ctr": torch.ao.quantization.qconfig._default_fp32_placeholder_qconfig.activation,
  103. }
  104. _DEFAULT_QUINT8_QCONFIG_FOR_TARGET_DTYPE_INFO = {
  105. "input_act_obs_or_fq_ctr": torch.ao.quantization.qconfig._default_quint8_placeholder_qconfig.activation,
  106. "output_act_obs_or_fq_ctr": torch.ao.quantization.qconfig._default_quint8_placeholder_qconfig.activation,
  107. }
  108. def _get_observer_kwargs(
  109. quant_spec: Union[QuantizationSpec, FixedQParamsQuantizationSpec],
  110. ):
  111. kwargs_dict = asdict(quant_spec)
  112. return copy.deepcopy(kwargs_dict)
  113. def _get_qspec_for_arg(
  114. arg: Node,
  115. input_qspec_map: dict[Node, QuantizationSpecBase],
  116. named_modules: dict[str, torch.nn.Module],
  117. ) -> Optional[QuantizationSpecBase]:
  118. while _is_activation_post_process_node(arg, named_modules):
  119. arg = arg.args[0] # type: ignore[assignment]
  120. return input_qspec_map.get(arg, None)
  121. def _create_obs_or_fq_from_qspec(
  122. quantization_spec: Optional[QuantizationSpecBase],
  123. obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize],
  124. is_qat: bool,
  125. ):
  126. """Create observer or fake quantize objects based on quantization spec
  127. Args:
  128. quantization_spec: used to store parameters to create the observer or fake quantizer
  129. obs_or_fq_map: this is a map from edge/output to the corresponding observer/fake_quant
  130. instance, it may be reused for different edge/output depending on configuration
  131. """
  132. if quantization_spec is None:
  133. return None
  134. if isinstance(quantization_spec, SharedQuantizationSpec):
  135. edge_or_node = quantization_spec.edge_or_node
  136. assert edge_or_node in obs_or_fq_map, (
  137. "please make sure only refer to edge or node that has "
  138. f"observer/fake_quant inserted: '{edge_or_node}' not in\n{obs_or_fq_map.keys()}"
  139. )
  140. return obs_or_fq_map[edge_or_node]
  141. elif isinstance(quantization_spec, DerivedQuantizationSpec):
  142. # can't use asdict, so not calling get_observer_kwargs here
  143. kwargs = {
  144. "dtype": quantization_spec.dtype,
  145. "derive_qparams_fn": quantization_spec.derive_qparams_fn,
  146. "quant_min": quantization_spec.quant_min,
  147. "quant_max": quantization_spec.quant_max,
  148. "qscheme": quantization_spec.qscheme,
  149. "ch_axis": quantization_spec.ch_axis,
  150. }
  151. edge_or_nodes = quantization_spec.derived_from
  152. obs_or_fqs = [obs_or_fq_map[k] for k in edge_or_nodes]
  153. kwargs["obs_or_fqs"] = obs_or_fqs
  154. return _DerivedObserverOrFakeQuantize.with_args(**kwargs)()
  155. elif isinstance(quantization_spec, FixedQParamsQuantizationSpec):
  156. kwargs = _get_observer_kwargs(quantization_spec)
  157. observer_ctr = FixedQParamsObserver.with_args(**kwargs)
  158. if is_qat:
  159. return FixedQParamsFakeQuantize.with_args(observer=observer_ctr)()
  160. else:
  161. return observer_ctr()
  162. assert isinstance(quantization_spec, QuantizationSpec)
  163. observer_or_fake_quant_ctr = quantization_spec.observer_or_fake_quant_ctr
  164. kwargs = _get_observer_kwargs(quantization_spec)
  165. kwargs.pop("observer_or_fake_quant_ctr")
  166. # we will remove is_dynamic from QuantizationSpec because
  167. # it seems that dynamic range quantization
  168. obs_or_fq_class = observer_or_fake_quant_ctr
  169. if isinstance(observer_or_fake_quant_ctr, _PartialWrapper):
  170. obs_or_fq_class = observer_or_fake_quant_ctr.p.func # type: ignore[union-attr, assignment]
  171. if "PerChannel" not in obs_or_fq_class.__name__: # type: ignore[operator, union-attr]
  172. kwargs.pop("ch_axis")
  173. return observer_or_fake_quant_ctr.with_args(**kwargs)()
  174. def _needs_obs_or_fq(
  175. prev_output_dtype: Any,
  176. prev_output_is_dynamic: bool,
  177. cur_target_dtype: Any,
  178. cur_target_is_dynamic: bool,
  179. reuse_input_obs_or_fq: bool,
  180. is_zeroth_arg: bool = False,
  181. ) -> bool:
  182. """
  183. note: we will treat "not specified" as torch.float for now
  184. utility function that checks if we should insert an observer or fake quant node
  185. base on the requested dtype for the nodes from user
  186. is_zeroth_arg: we only dynamically quantize the first arg of the node right now
  187. this should be removed when we enable configuring dynamic quantization
  188. for a specific argument, this can be removed if we deprecate fx graph mode
  189. quantization
  190. """
  191. # need to insert placeholder observer for dynamic quantization so that it can
  192. # be converted to choose_qparams -> q -> dq in convert step
  193. if cur_target_is_dynamic:
  194. assert cur_target_dtype in _OBS_DTYPE_LIST, (
  195. f"Expected cur_target_dtype to be torch.float, but got: {cur_target_dtype}"
  196. )
  197. assert prev_output_dtype not in _DO_NOT_OBS_DTYPE_LIST
  198. return is_zeroth_arg
  199. if reuse_input_obs_or_fq:
  200. return False
  201. # non dynamic quantization
  202. if cur_target_dtype in _OBS_DTYPE_LIST:
  203. return (
  204. prev_output_dtype in _OBS_DTYPE_LIST + [torch.float]
  205. and cur_target_dtype != prev_output_dtype
  206. )
  207. # lots of error checking are skipped here for now
  208. return False
  209. def _is_activation_post_process_node(
  210. node: Node, named_modules: dict[str, torch.nn.Module]
  211. ) -> bool:
  212. return (
  213. isinstance(node, torch.fx.Node)
  214. and node.op == "call_module"
  215. and _is_activation_post_process(named_modules[str(node.target)])
  216. )
  217. def _get_dtype_and_is_dynamic(
  218. obs_or_fq: Optional[ObserverOrFakeQuantize],
  219. ) -> tuple[Optional[torch.dtype], bool]:
  220. """Given a constructor for observer or fake quant module, returns
  221. a Tuple of dtype and is_dynamic
  222. """
  223. # TODO: instead of instantiating the instance, we can use inspect to get the default args
  224. if obs_or_fq is None:
  225. return None, False
  226. else:
  227. return obs_or_fq.dtype, getattr(obs_or_fq, "is_dynamic", False) # type: ignore[return-value]
  228. def _is_input_arg_dtype_supported_by_backend(
  229. arg: Argument,
  230. node: Node,
  231. qconfig: QConfigAny,
  232. dtype_config: DTypeConfig,
  233. backend_config: BackendConfig,
  234. ) -> bool:
  235. """Check if the configured qconfig for the argument
  236. is supported by the backend or not
  237. """
  238. if isinstance(arg, (list, tuple)):
  239. return all(
  240. _is_input_arg_dtype_supported_by_backend(
  241. a, node, qconfig, dtype_config, backend_config
  242. )
  243. for a in arg
  244. )
  245. if not isinstance(arg, Node):
  246. return True
  247. # TODO: support check for standalone module
  248. is_weight = node_arg_is_weight(node, arg)
  249. is_bias = node_arg_is_bias(node, arg)
  250. is_activation = not is_weight and not is_bias
  251. if is_activation:
  252. input_act_obs_or_fq_ctr = node.meta["target_dtype_info"].get(
  253. "input_act_obs_or_fq_ctr"
  254. )
  255. input_act_obs_or_fq = (
  256. input_act_obs_or_fq_ctr() if input_act_obs_or_fq_ctr else None
  257. )
  258. qconfig_dtype, qconfig_is_dynamic = _get_dtype_and_is_dynamic(
  259. input_act_obs_or_fq
  260. )
  261. # TODO(future PR): remove the cast to bool below after figuring
  262. # out why backend_config has is_dynamic set to None in some cases.
  263. return (dtype_config.input_dtype is None) or (
  264. dtype_config.input_dtype == qconfig_dtype
  265. and bool(dtype_config.is_dynamic) == bool(qconfig_is_dynamic)
  266. and _qconfig_satisfies_dtype_config_constraints(
  267. qconfig, dtype_config.input_dtype_with_constraints
  268. )
  269. )
  270. elif is_weight:
  271. # TODO: move dtype check into `_qconfig_satisfies_dtype_config_constraints` as well
  272. weight_obs_or_fq_ctr = node.meta["target_dtype_info"].get(
  273. "weight_obs_or_fq_ctr", None
  274. )
  275. weight_obs_or_fq = weight_obs_or_fq_ctr() if weight_obs_or_fq_ctr else None
  276. qconfig_weight_dtype, _ = _get_dtype_and_is_dynamic(weight_obs_or_fq)
  277. backend_config_weight_dtype = dtype_config.weight_dtype
  278. dtype_matches = qconfig_weight_dtype == backend_config_weight_dtype
  279. qconfig_satisfies_constraints = _qconfig_satisfies_dtype_config_constraints(
  280. qconfig, dtype_config.weight_dtype_with_constraints, is_activation=False
  281. )
  282. return backend_config_weight_dtype is None or (
  283. dtype_matches and qconfig_satisfies_constraints
  284. )
  285. else: # bias
  286. # TODO: move dtype check into `_qconfig_satisfies_dtype_config_constraints` as well
  287. bias_obs_or_fq_ctr = node.meta["target_dtype_info"].get(
  288. "bias_obs_or_fq_ctr", None
  289. )
  290. bias_obs_or_fq = bias_obs_or_fq_ctr() if bias_obs_or_fq_ctr else None
  291. qconfig_bias_dtype, _ = _get_dtype_and_is_dynamic(bias_obs_or_fq)
  292. backend_config_bias_dtype = dtype_config.bias_dtype
  293. return (
  294. backend_config_bias_dtype is None
  295. or qconfig_bias_dtype == backend_config_bias_dtype
  296. )
  297. def _is_output_dtype_supported_by_backend(
  298. node: Node,
  299. qconfig: QConfigAny,
  300. dtype_config: DTypeConfig,
  301. ) -> bool:
  302. """Check if the configured qconfig for the output
  303. is supported by the backend or not
  304. """
  305. # TODO: move dtype check into `_qconfig_satisfies_dtype_config_constraints` as well
  306. backend_config_output_dtype = dtype_config.output_dtype
  307. # TODO: we should check is_dynamic here as well, the code from _is_input_arg_dtype_supported_by_backend
  308. # from input activation check can be reused here
  309. qconfig_output_dtype = None
  310. output_act_obs_or_fq_ctr = node.meta["target_dtype_info"].get(
  311. "output_act_obs_or_fq_ctr", _DEFAULT_FP32_OBS_OR_FQ_CTR
  312. )
  313. output_act_obs_or_fq = (
  314. output_act_obs_or_fq_ctr() if output_act_obs_or_fq_ctr else None
  315. )
  316. qconfig_output_dtype, qconfig_output_is_dynamic = _get_dtype_and_is_dynamic(
  317. output_act_obs_or_fq
  318. )
  319. # TODO: this is a hack because we can only specify one activation_obs_or_fq for
  320. # qconfig (qconfig.activation), and we are only supporting dynamically quantized
  321. # linear op which has fp32 output dtype, this should be removed if we generalize
  322. # the structure of qconfig in the future
  323. if qconfig_output_is_dynamic:
  324. qconfig_output_dtype = torch.float32
  325. dtype_matches = qconfig_output_dtype == backend_config_output_dtype
  326. qconfig_satisfies_constraints = _qconfig_satisfies_dtype_config_constraints(
  327. qconfig, dtype_config.output_dtype_with_constraints
  328. )
  329. return backend_config_output_dtype is None or (
  330. dtype_matches and qconfig_satisfies_constraints
  331. )
  332. def _is_observer_in_same_graph(
  333. node: Node,
  334. named_modules: dict[str, torch.nn.Module],
  335. obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize],
  336. is_qat,
  337. ):
  338. """Check if observer in same graph
  339. when the node output is not fp32 and input is 'placeholder'
  340. the input is assumed to be quantized, so it is observed
  341. in a different place rather than not observed.
  342. """
  343. node_output_dtype = _get_arg_target_dtype_as_output(
  344. node, named_modules, obs_or_fq_map, is_qat
  345. )
  346. if len(node.args) > 0 and isinstance(node.args[0], Node):
  347. if (
  348. node_output_dtype in [torch.quint8, torch.uint8]
  349. and node.args[0].op == "placeholder"
  350. ):
  351. return False
  352. return True
  353. def _is_pattern_dtype_config_and_qconfig_supported_by_backend(
  354. pattern: Optional[Pattern],
  355. matched_node_pattern: Optional[list[Node]],
  356. qconfig: QConfigAny,
  357. backend_config: BackendConfig,
  358. ) -> bool:
  359. """Check if the dtype configuration of a pattern is supported by
  360. the backend or not, and whether the qconfig satisfies constraints
  361. specified in the corresponding dtype config.
  362. """
  363. if backend_config is None or pattern is None:
  364. return True
  365. assert matched_node_pattern is not None and len(matched_node_pattern) >= 1
  366. pattern_to_dtype_configs = get_pattern_to_dtype_configs(backend_config)
  367. dtype_configs: list[DTypeConfig] = pattern_to_dtype_configs.get(pattern, [])
  368. pattern_to_root_node_getter = get_fusion_pattern_to_root_node_getter(backend_config)
  369. root_node_getter = pattern_to_root_node_getter.get(
  370. pattern, _default_root_node_getter
  371. )
  372. root_node = root_node_getter(matched_node_pattern)
  373. input_node = root_node
  374. output_node = matched_node_pattern[0]
  375. for dtype_config in dtype_configs:
  376. # check if arg dtype are supported
  377. supported = True
  378. for arg in list(input_node.args) + list(input_node.kwargs.values()):
  379. supported = supported and _is_input_arg_dtype_supported_by_backend(
  380. arg, input_node, qconfig, dtype_config, backend_config
  381. )
  382. # check if output dtype is supported
  383. supported = supported and _is_output_dtype_supported_by_backend(
  384. output_node, qconfig, dtype_config
  385. )
  386. if supported:
  387. return True
  388. return False
  389. def _get_standalone_module_configs(
  390. node: Node,
  391. named_modules: dict[str, torch.nn.Module],
  392. prepare_custom_config: PrepareCustomConfig,
  393. parent_qconfig: QConfigAny,
  394. parent_backend_config: Optional[BackendConfig],
  395. ) -> tuple[
  396. QConfigMapping, tuple[Any, ...], PrepareCustomConfig, Optional[BackendConfig]
  397. ]:
  398. """
  399. Returns the standalone module QConfigMapping and PrepareCustomConfig
  400. for `node`, assuming that the module pointed to by `node` is
  401. a standalone modules.
  402. """
  403. module_name = str(node.target)
  404. module_type = type(named_modules[module_name]) # type: ignore[index]
  405. # name config has precedence over type config
  406. config_entry = StandaloneModuleConfigEntry(None, (), None, None)
  407. config_entry = prepare_custom_config.standalone_module_classes.get(
  408. module_type, config_entry
  409. )
  410. config_entry = prepare_custom_config.standalone_module_names.get(
  411. module_name, config_entry
  412. )
  413. # fallback to use parent module's qconfig if user didn't specify qconfig dict
  414. qconfig_mapping = config_entry.qconfig_mapping or QConfigMapping().set_global(
  415. parent_qconfig
  416. )
  417. example_inputs = config_entry.example_inputs
  418. prepare_custom_config = config_entry.prepare_custom_config or PrepareCustomConfig()
  419. backend_config = config_entry.backend_config or parent_backend_config
  420. return (qconfig_mapping, example_inputs, prepare_custom_config, backend_config)
  421. def _qat_swap_modules(
  422. root: torch.nn.Module, module_to_qat_module: dict[Pattern, type[torch.nn.Module]]
  423. ) -> None:
  424. convert(root, mapping=module_to_qat_module, inplace=True, remove_qconfig=False)
  425. def _add_matched_node_name_to_set(matched_node_pattern: NodePattern, s: set[str]):
  426. if isinstance(matched_node_pattern, Node):
  427. s.add(matched_node_pattern.name)
  428. elif isinstance(matched_node_pattern, (list, tuple)):
  429. for maybe_node in matched_node_pattern:
  430. _add_matched_node_name_to_set(maybe_node, s)
  431. def _insert_obs_or_fq(
  432. node: Node,
  433. obs_or_fq: ObserverOrFakeQuantize,
  434. model: torch.nn.Module,
  435. named_modules: dict[str, torch.nn.Module],
  436. graph: Graph,
  437. model_device: Optional[torch.device] = None,
  438. ) -> Node:
  439. """
  440. Attaches `obs_or_fq` to `model`, and creates a node which calls
  441. `obs_or_fq` on the output of `node`.
  442. obs_or_fq: an instance of Observer or FakeQuantize module
  443. """
  444. if model_device is None:
  445. model_device = assert_and_get_unique_device(model)
  446. if model_device:
  447. obs_or_fq.to(model_device)
  448. # add obs_or_fq module as attribute
  449. if is_equalization_observer(obs_or_fq):
  450. prefix = node.name + "_equalization_process_"
  451. else:
  452. prefix = "activation_post_process_"
  453. get_new_obs_or_fq_name = get_new_attr_name_with_prefix(prefix)
  454. obs_or_fq_name = get_new_obs_or_fq_name(model)
  455. setattr(model, obs_or_fq_name, obs_or_fq)
  456. named_modules[obs_or_fq_name] = obs_or_fq
  457. with graph.inserting_after(node):
  458. new_obs = graph.create_node("call_module", obs_or_fq_name, (node,), {})
  459. return new_obs
  460. def _set_target_dtype_info_for_matched_node_pattern(
  461. matched_node_pattern: NodePattern,
  462. last_node: Node,
  463. qconfig: QConfigAny,
  464. qhandler: Optional[QuantizeHandler],
  465. backend_config: BackendConfig,
  466. named_modules: dict[str, torch.nn.Module],
  467. cache_for_no_tensor_check: dict[Node, bool],
  468. processed_nodes: set[Node],
  469. ) -> None:
  470. """Sets the target_dtype_info for each node in matched_node_pattern
  471. Note: processed_nodes is used to ensure we only process each node once
  472. """
  473. if isinstance(matched_node_pattern, (list, tuple)):
  474. for node_pattern in matched_node_pattern:
  475. _set_target_dtype_info_for_matched_node_pattern(
  476. node_pattern,
  477. last_node,
  478. qconfig,
  479. qhandler,
  480. backend_config,
  481. named_modules,
  482. cache_for_no_tensor_check,
  483. processed_nodes,
  484. )
  485. # set target_dtype_info if matched_node_pattern is a Node
  486. # other types of matched object, e.g. int, float literals, are ignored
  487. elif isinstance(matched_node_pattern, Node):
  488. # for pyre
  489. assert isinstance(matched_node_pattern, Node)
  490. node = matched_node_pattern
  491. if node in processed_nodes:
  492. return
  493. processed_nodes.add(node)
  494. if qconfig is None:
  495. return
  496. # TODO: refactor the following code in terms of apply a qconfig to a pattern
  497. # e.g. for a pattern with op1 -> op2 -> op3, and qconfig = QConfig(input_act=obs0, output_act=obs1)
  498. # we set the input_obs_or_fq_ctr for the arguments of op1 to based on qconfig.input_act,
  499. # and set output_obs_or_fq_ctr based on qconfig.output_act
  500. # this also requires we extend the structure of QConfig to support more fine
  501. # grained configurations
  502. target_dtype_info: dict[str, Any] = _get_target_activation_dtype_for_node(
  503. node,
  504. qconfig,
  505. qhandler,
  506. named_modules,
  507. backend_config,
  508. cache_for_no_tensor_check,
  509. )
  510. node.meta["target_dtype_info"] = target_dtype_info
  511. def _get_target_activation_dtype_for_node(
  512. node: Node,
  513. qconfig: QConfigAny,
  514. qhandler: Optional[QuantizeHandler],
  515. named_modules: dict[str, torch.nn.Module],
  516. backend_config: BackendConfig,
  517. cache_for_no_tensor_check: dict[Node, bool],
  518. ) -> dict[str, Any]:
  519. """
  520. For each op attribute in the op's input activation, output activation,
  521. weight, bias - returns the settings of dtype and is_dynamic we expect
  522. for the `quantize` call in the reference model representation, or None
  523. if there is no `quantize` call needed.
  524. For example, if we have a node corresponding to `op0` in
  525. x0 -> op0 -> x1
  526. And we want a reference quantized representation to be
  527. x0 -> quant_static -> dequant -> op0 -> quant_dynamic -> dequant -> x1
  528. Then this function will return
  529. {
  530. "input_act_obs_or_fq_ctr": MinMaxObserver.with_args(dtype=torch.quint8, is_dynamic=False),
  531. "output_act_obs_or_fq_ctr": MinMaxObserver.with_args(dtype=torch.quint8, is_dynamic=False),
  532. }
  533. TODO(future PR, if needed): explicitly spell out the non-Tensor
  534. dtypes.
  535. """
  536. args_have_no_tensors = all_node_args_have_no_tensors(
  537. node, named_modules, cache_for_no_tensor_check
  538. )
  539. if args_have_no_tensors:
  540. return {
  541. "input_act_obs_or_fq_ctr": None,
  542. "output_act_obs_or_fq_ctr": None,
  543. }
  544. # get qconfig to determine the eventual dtype of this node
  545. if qconfig is not None:
  546. act_dtype, weight_dtype, input_act_is_dynamic = get_qconfig_dtypes(qconfig)
  547. # Currently `QConfig` only has one `activation` field.
  548. # For static quantization, it is reused for both input
  549. # and output activation. For dynamic quantization, this
  550. # field is currently only used for the input activation,
  551. # with the output activation being in fp32.
  552. # In the future this may change as we add more fields
  553. # to the `QConfig` object.
  554. bias_dtype = (
  555. torch.float16
  556. if (
  557. act_dtype == torch.float16
  558. and weight_dtype == torch.float16
  559. and (not input_act_is_dynamic)
  560. )
  561. else torch.float
  562. )
  563. is_general_tensor_value_op = (
  564. qhandler is not None and qhandler.is_general_tensor_value_op()
  565. )
  566. _is_standalone_module = qhandler is not None and qhandler.is_standalone_module()
  567. weight_index = None
  568. if (
  569. isinstance(node, Node)
  570. and node.op == "call_function"
  571. and node.target in backend_config._pattern_complex_format_to_config
  572. ):
  573. weight_index = backend_config._pattern_complex_format_to_config[
  574. node.target
  575. ]._input_type_to_index.get("weight")
  576. bias_index = None
  577. if (
  578. isinstance(node, Node)
  579. and node.op == "call_function"
  580. and node.target in backend_config._pattern_complex_format_to_config
  581. ):
  582. bias_index = backend_config._pattern_complex_format_to_config[
  583. node.target
  584. ]._input_type_to_index.get("bias")
  585. return {
  586. "input_act_obs_or_fq_ctr": qconfig.activation,
  587. "weight_obs_or_fq_ctr": qconfig.weight,
  588. "bias_obs_or_fq_ctr": PlaceholderObserver.with_args(dtype=bias_dtype),
  589. "weight_index": weight_index,
  590. "bias_index": bias_index,
  591. "output_act_obs_or_fq_ctr": qconfig.activation,
  592. "reuse_input_obs_or_fq": _is_reuse_input_qconfig(qconfig),
  593. "input_output_share_observers": is_general_tensor_value_op,
  594. "_is_standalone_module": _is_standalone_module,
  595. }
  596. return copy.copy(_DEFAULT_FP32_QCONFIG_FOR_TARGET_DTYPE_INFO)
  597. def _get_output_act_obs_or_fq(
  598. arg: Node,
  599. named_modules: dict[str, torch.nn.Module],
  600. obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize],
  601. is_qat: bool,
  602. ) -> Optional[ObserverOrFakeQuantize]:
  603. """Get the constructor for observer or fake quant object for
  604. the argument in the original graph as the output of previous node,
  605. skipping inserted observers
  606. We are assuming that the observers are inserted correctly, and the dtype for
  607. argument in quantized graph will match what is specified by the qconfig
  608. """
  609. assert isinstance(arg, Node)
  610. if "quantization_annotation" in arg.meta:
  611. return _create_obs_or_fq_from_qspec(
  612. arg.meta["quantization_annotation"].output_qspec, obs_or_fq_map, is_qat
  613. )
  614. # Custom module LSTM output is a tuple that we broke down into the internal nodes in order
  615. # to insert DeQuantStubs (see `_insert_dequant_stubs_for_custom_module_lstm_output`).
  616. # Since we modified the graph in this case, we must trace back from the args through
  617. # the specific nodes we added in order to reach the original LSTM node. Otherwise, we would
  618. # not be able to accurately detect whether this node is a consumer of custom module LSTM.
  619. custom_module_lstm_node = _maybe_get_custom_module_lstm_from_node_arg(
  620. arg, named_modules
  621. )
  622. output_act_obs_or_fq_ctr = None
  623. if custom_module_lstm_node is not None:
  624. output_act_obs_or_fq_ctr = custom_module_lstm_node.meta["target_dtype_info"][
  625. "output_act_obs_or_fq_ctr"
  626. ]
  627. output_act_obs_or_fq = (
  628. output_act_obs_or_fq_ctr() if output_act_obs_or_fq_ctr else None
  629. )
  630. elif _is_activation_post_process_node(arg, named_modules):
  631. observed_arg = arg.args[0]
  632. assert isinstance(observed_arg, Node), (
  633. "Currently we only support observing Node"
  634. )
  635. if "quantization_annotation" in observed_arg.meta:
  636. output_act_obs_or_fq = _create_obs_or_fq_from_qspec(
  637. observed_arg.meta["quantization_annotation"].output_qspec,
  638. obs_or_fq_map,
  639. is_qat,
  640. )
  641. else:
  642. assert "target_dtype_info" in observed_arg.meta
  643. output_act_obs_or_fq_ctr = observed_arg.meta["target_dtype_info"][
  644. "output_act_obs_or_fq_ctr"
  645. ]
  646. output_act_obs_or_fq = (
  647. output_act_obs_or_fq_ctr() if output_act_obs_or_fq_ctr else None
  648. )
  649. else:
  650. if "target_dtype_info" in arg.meta:
  651. output_act_obs_or_fq_ctr = arg.meta["target_dtype_info"].get(
  652. "output_act_obs_or_fq_ctr", _DEFAULT_FP32_OBS_OR_FQ_CTR
  653. )
  654. else:
  655. output_act_obs_or_fq_ctr = _DEFAULT_FP32_OBS_OR_FQ_CTR
  656. output_act_obs_or_fq = (
  657. output_act_obs_or_fq_ctr() if output_act_obs_or_fq_ctr else None
  658. )
  659. return output_act_obs_or_fq
  660. def _get_arg_target_dtype_as_output(
  661. arg: Node,
  662. named_modules: dict[str, torch.nn.Module],
  663. obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize],
  664. is_qat: bool,
  665. ) -> Optional[torch.dtype]:
  666. arg_as_output_act_obs_or_fq = _get_output_act_obs_or_fq(
  667. arg, named_modules, obs_or_fq_map, is_qat
  668. )
  669. arg_as_output_target_dtype, _ = _get_dtype_and_is_dynamic(
  670. arg_as_output_act_obs_or_fq
  671. )
  672. return arg_as_output_target_dtype
  673. def _get_arg_as_input_act_obs_or_fq(
  674. arg: Node,
  675. node: Node,
  676. named_modules: dict[str, torch.nn.Module],
  677. obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize],
  678. is_qat: bool,
  679. ) -> Optional[ObserverOrFakeQuantize]:
  680. """Get the observer or fake quant constructor for the Argument `arg`, as input
  681. to Node `node`
  682. """
  683. assert isinstance(arg, Node)
  684. # "input_qspec_map" is the more general design we'll use for pt2e path
  685. # it is a map from input argument node to observer or fake quant constructor, for example
  686. # for the following graph:
  687. # x -> conv -> output
  688. #
  689. # we may annotate conv node like the following:
  690. # conv.meta[...] = QuantizationAnnotation("input_qspec_map": {x: MinMaxObserver.with_args(dtype=torch.qint8)}, ...)
  691. #
  692. if "quantization_annotation" in node.meta:
  693. input_qspec_map = node.meta["quantization_annotation"].input_qspec_map
  694. input_arg_qspec = _get_qspec_for_arg(arg, input_qspec_map, named_modules)
  695. if input_arg_qspec is None:
  696. input_arg_obs_or_fq = _DEFAULT_FP32_OBS_OR_FQ_CTR()
  697. else:
  698. input_arg_obs_or_fq = _create_obs_or_fq_from_qspec(
  699. input_arg_qspec, obs_or_fq_map, is_qat
  700. )
  701. return input_arg_obs_or_fq
  702. # we can remove the following path in the future if fx graph mode quantization is
  703. # no longer used
  704. is_weight = node_arg_is_weight(node, arg)
  705. is_bias = node_arg_is_bias(node, arg)
  706. is_activation = not is_weight and not is_bias
  707. obs_or_fq_ctr = None
  708. if is_activation:
  709. obs_or_fq_ctr = node.meta["target_dtype_info"].get(
  710. "input_act_obs_or_fq_ctr", _DEFAULT_FP32_OBS_OR_FQ_CTR
  711. )
  712. elif is_weight:
  713. if node.target not in NON_QUANTIZABLE_WEIGHT_OPS:
  714. obs_or_fq_ctr = node.meta["target_dtype_info"].get(
  715. "weight_obs_or_fq_ctr", _DEFAULT_FP32_OBS_OR_FQ_CTR
  716. )
  717. else:
  718. obs_or_fq_ctr = node.meta["target_dtype_info"].get(
  719. "bias_obs_or_fq_ctr", _DEFAULT_FP32_OBS_OR_FQ_CTR
  720. )
  721. return obs_or_fq_ctr() if obs_or_fq_ctr else None
  722. def _maybe_insert_input_observer_for_arg_or_kwarg(
  723. node: Union[Node, Any],
  724. arg: Argument,
  725. qconfig: QConfigAny,
  726. model: torch.nn.Module,
  727. named_modules: dict[str, torch.nn.Module],
  728. graph: Graph,
  729. qhandler: Optional[QuantizeHandler],
  730. prepare_custom_config: PrepareCustomConfig,
  731. obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize],
  732. is_qat: bool,
  733. backend_config: Optional[BackendConfig] = None,
  734. model_device: Optional[torch.device] = None,
  735. ) -> Argument:
  736. """
  737. Given a `node` and an `arg`, inserts an input observer between
  738. `node` and `arg` if necessary.
  739. """
  740. # for ops such as torch.cat([x0, x1]),
  741. # traverse through the list
  742. if isinstance(arg, (list, tuple)):
  743. new_arg_to_return = []
  744. for inner_arg in arg:
  745. new_inner_arg = _maybe_insert_input_observer_for_arg_or_kwarg(
  746. node,
  747. inner_arg,
  748. qconfig,
  749. model,
  750. named_modules,
  751. graph,
  752. qhandler,
  753. prepare_custom_config,
  754. obs_or_fq_map,
  755. is_qat,
  756. backend_config,
  757. model_device,
  758. )
  759. new_arg_to_return.append(new_inner_arg)
  760. return type(arg)(new_arg_to_return)
  761. if not isinstance(arg, Node):
  762. return arg
  763. assert isinstance(arg, Node)
  764. # default (no observer)
  765. new_arg = arg
  766. is_standalone_module = qhandler is not None and qhandler.is_standalone_module()
  767. # TODO: move this to a separate function
  768. if not is_standalone_module:
  769. # Note: qconfig can be None in this branch this we are getting act/fq from
  770. # node.meta now
  771. # regular flow for most nodes, except standalone modules
  772. if "quantization_annotation" in node.meta:
  773. reuse_input_obs_or_fq = node.meta[
  774. "quantization_annotation"
  775. ]._reuse_input_obs_or_fq
  776. else:
  777. assert "target_dtype_info" in node.meta
  778. # TODO: we are assuming "target_dtype_info" exists here, maybe
  779. # a default value also need to be provided here
  780. target_dtype_info = node.meta["target_dtype_info"]
  781. # for nodes that doesn't have `reuse_input_obs_or_fq` configured,
  782. # we'll default to False, this makes configuring this field optional for users
  783. reuse_input_obs_or_fq = target_dtype_info.get(
  784. "reuse_input_obs_or_fq", False
  785. )
  786. arg_as_input_act_obs_or_fq = _get_arg_as_input_act_obs_or_fq(
  787. arg, node, named_modules, obs_or_fq_map, is_qat
  788. )
  789. (
  790. arg_as_input_target_dtype,
  791. arg_as_input_target_is_dynamic,
  792. ) = _get_dtype_and_is_dynamic(arg_as_input_act_obs_or_fq)
  793. arg_as_output_act_obs_or_fq = _get_output_act_obs_or_fq(
  794. arg, named_modules, obs_or_fq_map, is_qat
  795. )
  796. (
  797. arg_as_output_target_dtype,
  798. arg_as_output_target_is_dynamic,
  799. ) = _get_dtype_and_is_dynamic(arg_as_output_act_obs_or_fq)
  800. needs_obs_or_fq = _needs_obs_or_fq(
  801. arg_as_output_target_dtype,
  802. arg_as_output_target_is_dynamic,
  803. arg_as_input_target_dtype,
  804. arg_as_input_target_is_dynamic,
  805. reuse_input_obs_or_fq,
  806. is_zeroth_arg=len(node.args) > 0 and arg is node.args[0],
  807. )
  808. else:
  809. assert qconfig is not None
  810. # custom flow for standalone modules
  811. _, _, sm_prepare_custom_config, _ = _get_standalone_module_configs(
  812. node, named_modules, prepare_custom_config, qconfig, backend_config
  813. )
  814. sm_input_quantized_idxs = sm_prepare_custom_config.input_quantized_indexes
  815. # for args, this is set to the index of the current arg
  816. # for kwargs, this is left at None
  817. cur_input_idx = None
  818. for arg_idx, arg_to_check in enumerate(node.args):
  819. if arg_to_check is arg:
  820. cur_input_idx = arg_idx
  821. break
  822. if cur_input_idx is None:
  823. needs_obs_or_fq = False
  824. else:
  825. arg_as_output_target_dtype = _get_arg_target_dtype_as_output(
  826. arg, named_modules, obs_or_fq_map, is_qat
  827. )
  828. arg_as_input_target_dtype = (
  829. torch.quint8
  830. if cur_input_idx in sm_input_quantized_idxs
  831. else torch.float
  832. )
  833. needs_obs_or_fq = (
  834. arg_as_output_target_dtype != arg_as_input_target_dtype
  835. ) and (arg_as_input_target_dtype != torch.float)
  836. act_post_process_ctr = qconfig.activation
  837. arg_as_input_act_obs_or_fq = (
  838. act_post_process_ctr() if act_post_process_ctr else None
  839. )
  840. if needs_obs_or_fq:
  841. existing_obs_node = None
  842. # Before using the new observer, check if an observer
  843. # of the correct type already exists. If it does, use it.
  844. # This prevents duplicate observer insertions if a node is
  845. # used by multiple nodes.
  846. # TODO: this is looking into how the value is used in the future
  847. # we should remove this
  848. # removing this means we insert one observer for each use, even if they
  849. # have the same dtype, we can have an extra pass that removes the extra observers
  850. for maybe_obs_node in arg.users.keys():
  851. if maybe_obs_node.op == "call_module":
  852. maybe_obs_mod = named_modules[maybe_obs_node.target] # type: ignore[index]
  853. if (
  854. type(maybe_obs_mod) == type(arg_as_input_act_obs_or_fq)
  855. and maybe_obs_mod.dtype == arg_as_input_target_dtype # type: ignore[possibly-undefined]
  856. ):
  857. arg_as_input_act_obs_or_fq = maybe_obs_mod # type: ignore[assignment]
  858. existing_obs_node = maybe_obs_node
  859. break
  860. assert arg_as_input_act_obs_or_fq is not None
  861. obs_or_fq_map[(arg, node)] = arg_as_input_act_obs_or_fq
  862. if existing_obs_node is None:
  863. new_obs_node = _insert_obs_or_fq(
  864. arg,
  865. arg_as_input_act_obs_or_fq,
  866. model,
  867. named_modules,
  868. graph,
  869. model_device,
  870. )
  871. # override this arg to be the observed arg
  872. new_arg = new_obs_node
  873. else:
  874. new_arg = existing_obs_node
  875. return new_arg
  876. def _maybe_insert_input_observers_for_node(
  877. node: Node,
  878. qconfig: QConfigAny,
  879. model: torch.nn.Module,
  880. named_modules: dict[str, torch.nn.Module],
  881. graph: Graph,
  882. qhandler: Optional[QuantizeHandler],
  883. prepare_custom_config: PrepareCustomConfig,
  884. obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize],
  885. is_qat: bool,
  886. backend_config: Optional[BackendConfig] = None,
  887. model_device: Optional[torch.device] = None,
  888. ) -> None:
  889. """
  890. If needed, inserts observers to the input args and kwargs of `node`.
  891. Note: modifies `node` inplace.
  892. For example, if cur_node needs an observer after prev_node, we change from
  893. prev_node -> cur_node
  894. To
  895. prev_node -> obs -> cur_node
  896. Note: backend_config only needed for standalone_module node
  897. """
  898. # Look through every input arg. If that arg's target dtype does not
  899. # match the current node's target dtype, insert an observer.
  900. new_args = []
  901. for arg in node.args:
  902. new_arg = _maybe_insert_input_observer_for_arg_or_kwarg(
  903. node,
  904. arg,
  905. qconfig,
  906. model,
  907. named_modules,
  908. graph,
  909. qhandler,
  910. prepare_custom_config,
  911. obs_or_fq_map,
  912. is_qat,
  913. backend_config,
  914. model_device,
  915. )
  916. new_args.append(new_arg)
  917. new_kwargs = {}
  918. for k, kwarg in node.kwargs.items():
  919. new_kwarg = _maybe_insert_input_observer_for_arg_or_kwarg(
  920. node,
  921. kwarg,
  922. qconfig,
  923. model,
  924. named_modules,
  925. graph,
  926. qhandler,
  927. prepare_custom_config,
  928. obs_or_fq_map,
  929. is_qat,
  930. backend_config,
  931. model_device,
  932. )
  933. new_kwargs[k] = new_kwarg
  934. # assign the new args and kwargs to the node, inplace
  935. node.args = tuple(new_args)
  936. node.kwargs = new_kwargs
  937. def _maybe_insert_input_equalization_observers_for_node(
  938. node: Node,
  939. equalization_qconfig: Any,
  940. model: torch.nn.Module,
  941. named_modules: dict[str, torch.nn.Module],
  942. graph: Graph,
  943. is_branch: bool,
  944. ) -> None:
  945. """
  946. If `node` needs to be equalized, find the input/weight observers it needs in
  947. `equalization_qconfig`, creates them, and inserts it into `graph`.
  948. If `node` does not need an equalization observer, returns None.
  949. """
  950. if equalization_qconfig is None or not node_supports_equalization(
  951. node, named_modules
  952. ):
  953. return
  954. if is_branch:
  955. warnings.warn(f"Cannot equalize {node} because it is part of a branch.")
  956. return
  957. new_args = []
  958. for arg in node.args:
  959. if not isinstance(arg, Node) or node_arg_is_bias(node, arg):
  960. new_args.append(arg)
  961. continue
  962. is_weight = node_arg_is_weight(node, arg)
  963. act_eq_process_ctr = (
  964. equalization_qconfig.weight
  965. if is_weight
  966. else equalization_qconfig.input_activation
  967. )
  968. new_eq_obs_mod = act_eq_process_ctr()
  969. new_eq_obs_node = _insert_obs_or_fq(
  970. arg, new_eq_obs_mod, model, named_modules, graph
  971. )
  972. new_args.append(new_eq_obs_node)
  973. # assign the new args and kwargs to the node, inplace
  974. node.args = tuple(new_args)
  975. def _maybe_insert_output_observer_for_node(
  976. node: Node,
  977. model: torch.nn.Module,
  978. named_modules: dict[str, torch.nn.Module],
  979. graph: Graph,
  980. obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize],
  981. is_qat: bool,
  982. ) -> Optional[Node]:
  983. """
  984. If `node` needs an output observer, creates it, inserts it into `graph`
  985. and returns it.
  986. If `node` does not need an output observer, returns None.
  987. Note: inserting dynamic quantization ops for output is not supported in fx graph mode
  988. quantization code path right now
  989. """
  990. assert node.op != "output", "observer insertion for outputs is handled elsewhere"
  991. is_standalone_module = False
  992. if "quantization_annotation" in node.meta:
  993. output_act_obs_or_fq = _create_obs_or_fq_from_qspec(
  994. node.meta["quantization_annotation"].output_qspec, obs_or_fq_map, is_qat
  995. )
  996. else:
  997. assert "target_dtype_info" in node.meta
  998. is_standalone_module = node.meta["target_dtype_info"].get(
  999. "_is_standalone_module", False
  1000. )
  1001. output_act_obs_or_fq_ctr = node.meta["target_dtype_info"].get(
  1002. "output_act_obs_or_fq_ctr"
  1003. )
  1004. output_act_obs_or_fq = (
  1005. output_act_obs_or_fq_ctr() if output_act_obs_or_fq_ctr else None
  1006. )
  1007. target_dtype, target_is_dynamic = _get_dtype_and_is_dynamic(output_act_obs_or_fq)
  1008. # uncomment after we support reuse_input_obs_or_fq properly by having separate
  1009. # implementations for this key instead of reusing the input_output_share_observers
  1010. # code
  1011. # reuse_input_obs_or_fq = node.meta["target_dtype_info"].get("reuse_input_obs_or_fq", False)
  1012. # for now we set this to False since reuse_input_obs_or_fq for
  1013. # the output of a node is implementation in the same code path as observer sharing,
  1014. # we should refactor this part to make it clearer in the future
  1015. # and we would be able to read this from config directly
  1016. reuse_input_obs_or_fq = False
  1017. # Note: prev_output_dtype = torch.float and prev_output_is_dynamic=False
  1018. # because the prev_output is the output of an fp32 op, although technically
  1019. # we should get the dtype of the output from node.meta["val"] in the future
  1020. # if we deprecate fx graph mode quantization
  1021. needs_obs_or_fq = _needs_obs_or_fq(
  1022. torch.float, False, target_dtype, target_is_dynamic, reuse_input_obs_or_fq
  1023. )
  1024. # currently the activation in QConfig(activation=...,) is for both input
  1025. # and output, and when the activation is configured to be dynamic quantization
  1026. # e.g. PlaceholderObserver(dtype=torch.quint8, is_dynamic=True, ...), it means
  1027. # the input should by dynamically quantized, but output should not be quantized
  1028. #
  1029. # there is no way we can specify different observer/fq for input and output
  1030. # activation through QConfig today, this limitation is lifted in the
  1031. # quantizer/annotation API in pytorch 2.0 export quantization code path,
  1032. # but since this code is reused, annotating output to be dynamically quantized
  1033. # would not work either for that.
  1034. # we can change QConfig to support input/output activation if we want
  1035. # to remove the following check, or if we can deprecate fx graph mode quantization
  1036. if target_is_dynamic:
  1037. needs_obs_or_fq = False
  1038. # we never insert observers to output of standalone module, we assume
  1039. # if needed, they are inserted inside the standalone module
  1040. needs_obs_or_fq = needs_obs_or_fq and (not is_standalone_module)
  1041. if needs_obs_or_fq:
  1042. obs_or_fq_map[node] = output_act_obs_or_fq
  1043. return _insert_obs_or_fq(
  1044. node, output_act_obs_or_fq, model, named_modules, graph
  1045. )
  1046. else:
  1047. return None
  1048. def _maybe_insert_observers_before_graph_output(
  1049. graph_output_node: Node,
  1050. model: torch.nn.Module,
  1051. named_modules: dict[str, torch.nn.Module],
  1052. graph: Graph,
  1053. obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize],
  1054. is_qat: bool,
  1055. ) -> None:
  1056. """
  1057. If the output needs to be quantized and there are any nodes
  1058. in the output which are not already observed, inserts observers
  1059. for those nodes.
  1060. """
  1061. def _recursive_maybe_replace_node_with_obs(
  1062. maybe_node: Argument,
  1063. model: torch.nn.Module,
  1064. named_modules: dict[str, torch.nn.Module],
  1065. graph: Graph,
  1066. ) -> Argument:
  1067. """
  1068. Navigate an arbitrary data structure of lists, tuples, dicts.
  1069. For each container type, recurse on all inputs. Once any Node
  1070. is found, insert an observer if needed and do not recurse further.
  1071. For example, given a structure of
  1072. {'foo1': [[bar1]], 'foo2': {'foo3': [[[bar3]]]}}
  1073. we recurse down to bar1 and bar3, observe them if necessary,
  1074. and if we inserted an observer then replace the original node
  1075. with its observer.
  1076. Returns the data structure with all nodes needing observation being
  1077. replaced by their observers.
  1078. """
  1079. if isinstance(maybe_node, Node):
  1080. # check dtype of this node
  1081. arg_as_output_target_dtype = _get_arg_target_dtype_as_output(
  1082. maybe_node, named_modules, obs_or_fq_map, is_qat
  1083. )
  1084. observer_mod = None
  1085. arg_as_input_target_dtype = torch.float
  1086. if "target_dtype_info" in maybe_node.meta:
  1087. observer_cls = maybe_node.meta["target_dtype_info"].get(
  1088. "input_act_obs_or_fq_ctr", None
  1089. )
  1090. if observer_cls is not None:
  1091. observer_mod = observer_cls()
  1092. arg_as_input_target_dtype = observer_mod.dtype
  1093. # TODO: this does not handle dynamic quantization yet
  1094. need_obs = (
  1095. arg_as_output_target_dtype != arg_as_input_target_dtype
  1096. and arg_as_input_target_dtype != torch.float
  1097. )
  1098. if need_obs:
  1099. assert observer_mod is not None
  1100. # insert observer
  1101. observer_node = _insert_obs_or_fq(
  1102. maybe_node, observer_mod, model, named_modules, graph
  1103. )
  1104. return observer_node
  1105. else:
  1106. return maybe_node
  1107. elif isinstance(maybe_node, (list, tuple)):
  1108. results = [
  1109. _recursive_maybe_replace_node_with_obs(
  1110. inner_node, model, named_modules, graph
  1111. )
  1112. for inner_node in maybe_node
  1113. ]
  1114. if isinstance(maybe_node, list):
  1115. return results
  1116. else:
  1117. return tuple(results)
  1118. elif isinstance(maybe_node, dict):
  1119. results_dict = {}
  1120. for k, inner_v in maybe_node.items():
  1121. results_dict[k] = _recursive_maybe_replace_node_with_obs(
  1122. inner_v, model, named_modules, graph
  1123. )
  1124. return results_dict
  1125. elif maybe_node is None:
  1126. return None
  1127. else:
  1128. raise Exception( # noqa: TRY002
  1129. "Unhandled type for returned node:", maybe_node
  1130. )
  1131. new_args = [
  1132. _recursive_maybe_replace_node_with_obs(old_arg, model, named_modules, graph)
  1133. for old_arg in graph_output_node.args
  1134. ]
  1135. graph_output_node.args = tuple(new_args) # type: ignore[assignment]
  1136. def _maybe_propagate_dtype_for_node(
  1137. node: Node,
  1138. target_dtype: Union[torch.dtype, type],
  1139. node_name_to_match_result_with_qconfig: dict[str, _MatchResultWithQConfig],
  1140. ) -> None:
  1141. """
  1142. Assigns `target_dtype` to `node`, setting `is_dynamic` to False. If `node`
  1143. is a general tensor shape op, also call this function recursively on
  1144. the first argument, to propagate the dtype to the caller.
  1145. """
  1146. node.meta["target_dtype_info"]["input_act_obs_or_fq_ctr"] = None
  1147. node.meta["target_dtype_info"]["output_act_obs_or_fq_ctr"] = None
  1148. # if this is a copy node, propagate to first arg
  1149. (
  1150. _root_node,
  1151. _,
  1152. _pattern,
  1153. qhandler,
  1154. _qconfig,
  1155. ) = node_name_to_match_result_with_qconfig.get(
  1156. node.name, (None, None, None, None, None)
  1157. )
  1158. # TODO: probably need to remove `is_general_tensor_value_op`
  1159. if qhandler is not None and qhandler.is_general_tensor_value_op():
  1160. prev_node = node.args[0]
  1161. if isinstance(prev_node, Node):
  1162. _maybe_propagate_dtype_for_node(
  1163. prev_node, target_dtype, node_name_to_match_result_with_qconfig
  1164. )
  1165. def propagate_dtypes_for_known_nodes(
  1166. graph: Graph,
  1167. node_name_to_match_result_with_qconfig: dict[str, _MatchResultWithQConfig],
  1168. ) -> None:
  1169. """
  1170. Currently we assume that inputs to the graph are either `torch.float` or
  1171. `torch.quint8`, which is not always correct. For ops such as
  1172. `x.masked_fill(mask, value)`, we know that the dtype of `mask` is a
  1173. `BoolTensor`. Propagate this information throughout the graph.
  1174. Note: not all dtypes in the graph will be correct after this pass, but a
  1175. higher percentage of them will be correct. Hopefully in the future we can
  1176. replace this with a better way to reason about dtypes of tensors.
  1177. """
  1178. for node in graph.nodes:
  1179. non_observable_arg_dict = get_non_observable_arg_indexes_and_types(node)
  1180. for arg_type in non_observable_arg_dict:
  1181. non_observable_indices = non_observable_arg_dict[arg_type](node)
  1182. for index in non_observable_indices:
  1183. arg = node.args[index]
  1184. # when an argument is a tuple, it does not show up as another node so we need to go through
  1185. # all elements of the tuple manually
  1186. if isinstance(arg, (tuple, list)):
  1187. arg_list = list(arg)
  1188. else:
  1189. arg_list = [arg]
  1190. for cur_arg in arg_list:
  1191. # hard coded arguments show up but aren't `Node` typed and do not need dtype propagated
  1192. if isinstance(cur_arg, torch.fx.node.Node):
  1193. _maybe_propagate_dtype_for_node(
  1194. cur_arg, arg_type, node_name_to_match_result_with_qconfig
  1195. )
  1196. def _maybe_make_input_output_share_observers(
  1197. node: Node,
  1198. model: torch.nn.Module,
  1199. named_modules: dict[str, torch.nn.Module],
  1200. ) -> bool:
  1201. """
  1202. Ensures that we share an observer
  1203. for all input arguments as well as the output argument. In detail, given
  1204. a graph of
  1205. x0 -> obs0 -> op -> x2
  1206. /
  1207. x1 -> obs1 /
  1208. where node obs0 points to observer instance observer0,
  1209. obs1 points to observer1 and obs2 points to observer2, we make nodes obs1
  1210. and ob2 point to observer0.
  1211. Returns: whether the operation succeeded or not
  1212. """
  1213. first_arg = None
  1214. # find the first non-Tensor arg
  1215. for i in range(len(node.args)):
  1216. if isinstance(node.args[i], (Node, list, tuple)):
  1217. first_arg = node.args[i]
  1218. break
  1219. # if there is no non-Tensor arg, return directly
  1220. if first_arg is None:
  1221. return False
  1222. if isinstance(first_arg, (list, tuple)):
  1223. first_arg_arg = first_arg[0]
  1224. elif isinstance(first_arg, Node):
  1225. first_arg_arg = first_arg
  1226. else:
  1227. return False
  1228. # if we have a graph such as
  1229. # observed_node -> non_observed_node -> cat
  1230. # we need to navigate up to the first observer
  1231. iteration_guard = 0
  1232. while not _is_activation_post_process_node(first_arg_arg, named_modules):
  1233. if not isinstance(first_arg_arg, Node):
  1234. return False
  1235. # did not find an activation_post_process for the op
  1236. if first_arg_arg.op == "placeholder":
  1237. return False
  1238. # trace back the args until we found the first Tensor/Node
  1239. trace_back_node = None
  1240. for i in range(len(first_arg_arg.args)):
  1241. trace_back_node = first_arg_arg.args[i]
  1242. if isinstance(trace_back_node, Node):
  1243. break
  1244. if trace_back_node is None:
  1245. return False
  1246. first_arg_arg = trace_back_node
  1247. iteration_guard += 1
  1248. if iteration_guard > 10000:
  1249. raise AssertionError("Unable to find observer of previous node")
  1250. assert isinstance(first_arg_arg, Node)
  1251. target_to_use = first_arg_arg.target
  1252. assert isinstance(target_to_use, str)
  1253. obs_mod_to_use = named_modules[target_to_use]
  1254. if isinstance(first_arg, (list, tuple)):
  1255. # set all other input observer nodes to use that module
  1256. for input_idx, input_arg in enumerate(first_arg):
  1257. if input_idx == 0:
  1258. continue
  1259. iteration_guard = 0
  1260. while not _is_activation_post_process_node(input_arg, named_modules):
  1261. # failed to trace back since no input arg for the current node
  1262. if len(input_arg.args) < 1:
  1263. return False
  1264. input_arg = input_arg.args[0]
  1265. iteration_guard += 1
  1266. if iteration_guard > 10000:
  1267. raise AssertionError("Unable to find observer of previous node")
  1268. parent_name, name = _parent_name(input_arg.target)
  1269. setattr(named_modules[parent_name], name, obs_mod_to_use)
  1270. # set the output observer node to use that module
  1271. for output_obs_node in node.users.keys():
  1272. assert _is_activation_post_process_node(output_obs_node, named_modules)
  1273. parent_name, name = _parent_name(output_obs_node.target)
  1274. setattr(named_modules[parent_name], name, obs_mod_to_use)
  1275. # TODO(future PR): delete the orphaned observer modules
  1276. return True
  1277. def _remove_output_observer(
  1278. node: Node, model: torch.nn.Module, named_modules: dict[str, torch.nn.Module]
  1279. ):
  1280. items = list(node.users.items())
  1281. for output_obs_node, _ in items:
  1282. assert _is_activation_post_process_node(output_obs_node, named_modules)
  1283. output_obs_node.replace_all_uses_with(node)
  1284. model.graph.erase_node(output_obs_node) # type: ignore[union-attr, operator]
  1285. def _swap_custom_module_to_observed(
  1286. node: Node,
  1287. qconfig: QConfigAny,
  1288. named_modules: dict[str, torch.nn.Module],
  1289. prepare_custom_config: PrepareCustomConfig,
  1290. ):
  1291. custom_module = named_modules[node.target] # type: ignore[index]
  1292. custom_module_class_mapping = prepare_custom_config.float_to_observed_mapping
  1293. observed_custom_module_class = get_swapped_custom_module_class(
  1294. custom_module, custom_module_class_mapping, qconfig
  1295. )
  1296. observed_custom_module = observed_custom_module_class.from_float(custom_module)
  1297. parent_name, name = _parent_name(node.target)
  1298. setattr(named_modules[parent_name], name, observed_custom_module)
  1299. def insert_observers_for_model(
  1300. model: GraphModule,
  1301. node_name_to_match_result_with_qconfig: dict[str, _MatchResultWithQConfig],
  1302. node_name_to_qconfig: dict[str, QConfigAny],
  1303. prepare_custom_config: PrepareCustomConfig,
  1304. equalization_config_map: dict[str, Any],
  1305. backend_config: BackendConfig,
  1306. observed_node_names: set[str],
  1307. is_qat: bool,
  1308. ) -> Optional[Node]:
  1309. """
  1310. Inserts observers, using the following high level algorithm:
  1311. For each node in the graph:
  1312. 1. determine the target dtype of this node in the quantized graph, and save
  1313. it for future steps
  1314. 2. determine the target dtype or all args and kwargs of this node
  1315. 3. if any arg or kwarg's target dtype does not match the current node's
  1316. dtype, insert an observer
  1317. 4. if the current node needs an output observer, insert it
  1318. For example:
  1319. - starting graph:
  1320. x0 -> linear -> x1
  1321. - observed graph after processing x0:
  1322. x0(fp32)
  1323. - observed graph after processing linear:
  1324. x0(fp32) -> x0_obs0(int8) -> linear(int8) -> linear_obs0(int8)
  1325. - observed graph after processing x1:
  1326. x0(fp32) -> x0_obs0(int8) -> linear(int8) -> linear_obs0(int8) -> x1
  1327. After a node is processed, the naive observer placement is guaranteed to be
  1328. complete for that node and all of its predecessors. There can be future
  1329. passes which optimize the graph by deduplicating observers, etc.
  1330. """
  1331. # node.meta["target_dtype_info"] stores the target dtype information
  1332. # that's derived from qconfig for the Node, for example, if we have
  1333. # a conv2d node that has a qconfig
  1334. # qconfig = QConfig(activation=..., weight=...)
  1335. # # information for input and bias node omitted
  1336. # # for getattr node
  1337. # # weight = getattr(self, 'weight')
  1338. # weight.meta["target_dtype_info"] = {
  1339. # 'output_act_obs_or_fq_ctr': qconfig.weight,
  1340. # }
  1341. # # for conv2d node
  1342. # # conv2d = call_function[target=torch.nn.functional.conv2d](
  1343. # # args=(input, weight, bias))
  1344. # conv2d.meta["target_dtype_info"] = {
  1345. # 'input_act_obs_or_fq_ctr': qconfig.activation
  1346. # 'weight_obs_or_fq_ctr': qconfig.weight,
  1347. # 'bias_obs_or_fq_ctr': PlaceholderObserver.with_args(dtype=torch.float32),
  1348. # 'output_act_obs_or_fq_ctr': qconfig.activation,
  1349. # }
  1350. #
  1351. cache_for_no_tensor_check: dict[Node, bool] = {}
  1352. # first, populate the dtype map based only on qconfig and qhandler
  1353. # this assumes:
  1354. # graph inputs are fp32 by default, and int8 where overridden
  1355. # other nodes output dtype is specified by the qconfig
  1356. named_modules = dict(model.named_modules(remove_duplicate=False))
  1357. input_quantized_idxs: list[int] = prepare_custom_config.input_quantized_indexes
  1358. output_quantized_idxs: list[int] = prepare_custom_config.output_quantized_indexes
  1359. processed_nodes: set[Node] = set()
  1360. # initialize target_dtype_info
  1361. for node in model.graph.nodes:
  1362. node.meta["target_dtype_info"] = copy.copy(
  1363. _DEFAULT_FP32_QCONFIG_FOR_TARGET_DTYPE_INFO
  1364. )
  1365. inputs_seen_counter = 0
  1366. outputs_seen_counter = 0
  1367. placeholder_node_to_input_index: dict[Node, int] = {}
  1368. # TODO: we probably don't need this counter since each graph will only have
  1369. # one output node?
  1370. output_node_to_output_index: dict[Node, int] = {}
  1371. for node in model.graph.nodes:
  1372. if node.op == "placeholder":
  1373. placeholder_node_to_input_index[node] = inputs_seen_counter
  1374. inputs_seen_counter += 1
  1375. if node.op == "output":
  1376. output_node_to_output_index[node] = outputs_seen_counter
  1377. outputs_seen_counter += 1
  1378. # Step 1, set the observer or fake quantize module constructor for each node in the
  1379. # matched_node_pattern
  1380. for match_res_with_qconfig in node_name_to_match_result_with_qconfig.values():
  1381. (
  1382. last_node,
  1383. matched_node_pattern,
  1384. pattern,
  1385. qhandler,
  1386. qconfig,
  1387. ) = match_res_with_qconfig
  1388. assert qhandler is not None
  1389. _set_target_dtype_info_for_matched_node_pattern(
  1390. matched_node_pattern,
  1391. last_node,
  1392. qconfig,
  1393. qhandler,
  1394. backend_config,
  1395. named_modules,
  1396. cache_for_no_tensor_check,
  1397. processed_nodes,
  1398. )
  1399. # Step 2. Special cases for some operators, we might be able to remove them
  1400. # in the future if we know dtype information of each node better
  1401. # Step 2.1. some settings are not based on patterns, we need to process each node
  1402. # instead
  1403. for node in model.graph.nodes:
  1404. if (
  1405. node.op == "placeholder"
  1406. and placeholder_node_to_input_index[node] in input_quantized_idxs
  1407. ):
  1408. # users are not supposed to call calculate_qparams on PlaceholderObserver, and
  1409. # this is OK because we are using this as a way to encode the dtypes of input
  1410. # tensor, we won't actually insert these observers in the graph and won't
  1411. # actually call calculate_qparams
  1412. node.meta["target_dtype_info"] = copy.copy(
  1413. _DEFAULT_QUINT8_QCONFIG_FOR_TARGET_DTYPE_INFO
  1414. )
  1415. elif node.op in ("call_module", "call_method", "call_function"):
  1416. args_have_no_tensors = all_node_args_have_no_tensors(
  1417. node, named_modules, cache_for_no_tensor_check
  1418. )
  1419. if args_have_no_tensors:
  1420. node.meta["target_dtype_info"] = {
  1421. "input_act_obs_or_fq_ctr": None,
  1422. "output_act_obs_or_fq_ctr": None,
  1423. }
  1424. elif (
  1425. node.op == "output"
  1426. and output_node_to_output_index[node] in output_quantized_idxs
  1427. ):
  1428. # TODO(future PR): update the output_quantized_idxs API to match
  1429. # arbitrary data structures. There is always a single output, and
  1430. # that output can have arbitrary nesting of values. List[int] is
  1431. # not the right data type for this.
  1432. # TODO(future PR): support more dtypes in model outputs, if necessary
  1433. node.meta["target_dtype_info"] = copy.copy(
  1434. _DEFAULT_QUINT8_QCONFIG_FOR_TARGET_DTYPE_INFO
  1435. )
  1436. # Step 2.2, for nodes with known input dtypes, propagate them throughout the
  1437. # graph. For example, if there is a call such as
  1438. # x1 = x0.masked_fill(mask, 1)
  1439. # we propagate the type of mask to be torch.bool
  1440. propagate_dtypes_for_known_nodes(
  1441. model.graph, node_name_to_match_result_with_qconfig
  1442. )
  1443. # Step 3, check if the requested target_dtype_info is supported by backend or not
  1444. # if not, we'll reset the target_dtye_info to use the default (float Tensor)
  1445. # reset the counters and set of processed_nodes
  1446. processed_nodes: set[Node] = set()
  1447. for match_res_with_qconfig in node_name_to_match_result_with_qconfig.values():
  1448. (
  1449. last_node,
  1450. matched_node_pattern,
  1451. pattern,
  1452. qhandler,
  1453. qconfig,
  1454. ) = match_res_with_qconfig
  1455. is_supported_by_backend = (
  1456. _is_pattern_dtype_config_and_qconfig_supported_by_backend(
  1457. pattern, matched_node_pattern, qconfig, backend_config
  1458. )
  1459. )
  1460. assert qhandler is not None
  1461. # get output_act_dtype so that we don't also reset the special typed nodes
  1462. # TODO: we might want to handle these more uniformly with the default path
  1463. # this can be improved if we can use node.meta["val"]
  1464. output_act_or_fq_ctr = node.meta["target_dtype_info"][
  1465. "output_act_obs_or_fq_ctr"
  1466. ]
  1467. output_act_or_fq = output_act_or_fq_ctr() if output_act_or_fq_ctr else None
  1468. output_act_dtype, _ = _get_dtype_and_is_dynamic(output_act_or_fq)
  1469. if not is_supported_by_backend and output_act_dtype not in [
  1470. None,
  1471. int,
  1472. float,
  1473. torch.bool,
  1474. ]:
  1475. # restore target_dtype_info to default if it is not supported by backend
  1476. _set_target_dtype_info_for_matched_node_pattern(
  1477. matched_node_pattern,
  1478. last_node,
  1479. torch.ao.quantization.qconfig._default_fp32_placeholder_qconfig,
  1480. None,
  1481. backend_config,
  1482. named_modules,
  1483. cache_for_no_tensor_check,
  1484. processed_nodes,
  1485. )
  1486. # After this point, the current node and all of its arguments
  1487. # have a target_dtype_info assigned. Now, we insert observers for inputs
  1488. # of this node (if needed for this node), and the output of this node
  1489. # (if needed for this node).
  1490. # Since we are mutating the graph as we go, we iterate over the original
  1491. # nodes before observer insertion, instead of model.graph.nodes.
  1492. nodes_before_observation = list(model.graph.nodes)
  1493. # Avoid duplicates custom module swaps for multiple nodes with same target.
  1494. custom_module_names_already_swapped: set[str] = set()
  1495. # TODO: reuse placeholder_node_to_input_index and output_node_to_output_index
  1496. # reset inputs/outputs counters
  1497. inputs_seen_counter = 0
  1498. outputs_seen_counter = 0
  1499. results_node = None
  1500. obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize] = {}
  1501. model_device = assert_and_get_unique_device(model)
  1502. # TODO: change this to insert obs/fq by pattern instead of by node
  1503. for node in nodes_before_observation:
  1504. if node.op == "placeholder":
  1505. # if a graph input is in fp32, it does not need observation
  1506. # if a graph input is in int8, we assume the observation happens
  1507. # outside of the graph, and no additional observation is needed
  1508. pass
  1509. elif node.op in ("call_module", "call_method", "call_function", "output"):
  1510. # check for matches
  1511. (
  1512. last_node,
  1513. matched_node_pattern,
  1514. pattern,
  1515. qhandler,
  1516. qconfig,
  1517. ) = node_name_to_match_result_with_qconfig.get( # type: ignore[assignment]
  1518. node.name, (None, None, None, None, None)
  1519. )
  1520. equalization_qconfig = equalization_config_map.get(node.name, None)
  1521. this_node_dtype_info = node.meta["target_dtype_info"]
  1522. if "val" in node.meta:
  1523. output_is_a_tensor = this_node_dtype_info is not None and isinstance(
  1524. node.meta["val"], FakeTensor
  1525. )
  1526. else:
  1527. output_is_a_tensor = this_node_dtype_info is not None
  1528. skip_inserting_observers = (
  1529. (qconfig is None) or not output_is_a_tensor
  1530. ) and (not node.op == "output")
  1531. # TODO: take a closer look to see if we can remove this check
  1532. # right now it is here because of `observed_node_names`, we are using
  1533. # it as an indicator for swapping the modules to reference modules in
  1534. # convert
  1535. is_supported_by_backend = (
  1536. _is_pattern_dtype_config_and_qconfig_supported_by_backend(
  1537. pattern, matched_node_pattern, qconfig, backend_config
  1538. )
  1539. )
  1540. if not skip_inserting_observers and is_supported_by_backend:
  1541. named_modules = dict(model.named_modules(remove_duplicate=False))
  1542. if node.op != "output":
  1543. assert matched_node_pattern is not None
  1544. # add matched nodes to the observed node name set
  1545. _add_matched_node_name_to_set(
  1546. matched_node_pattern, observed_node_names
  1547. )
  1548. # This is currently only used for equalization.
  1549. # Checks if the current node is in a branch in which the two
  1550. # first layers are both being quantized.
  1551. #
  1552. # ex. conv2
  1553. # /
  1554. # x -> conv1
  1555. #
  1556. # If this is the case, we will not apply equalization to the
  1557. # initial two layers.
  1558. is_quantized_branch = False
  1559. if (
  1560. len(node.args) > 0
  1561. and isinstance(node.args[0], Node)
  1562. and len(node.args[0].users) > 1
  1563. ):
  1564. for user in node.args[0].users:
  1565. # Checks if there exists another user being quantized
  1566. is_user_quantized = node_name_to_qconfig.get(
  1567. user.name, None
  1568. ) is not None or (
  1569. user.op == "call_module"
  1570. and isinstance(
  1571. named_modules[str(user.target)], ObserverBase
  1572. )
  1573. )
  1574. if user != node and is_user_quantized:
  1575. is_quantized_branch = True
  1576. pattern_to_root_node_getter = (
  1577. get_fusion_pattern_to_root_node_getter(backend_config)
  1578. )
  1579. root_node_getter = pattern_to_root_node_getter.get(
  1580. pattern, _default_root_node_getter
  1581. )
  1582. root_node = root_node_getter(matched_node_pattern)
  1583. is_input_node_of_the_pattern = node is root_node
  1584. if is_input_node_of_the_pattern:
  1585. # this modifies node inplace
  1586. _maybe_insert_input_observers_for_node(
  1587. node,
  1588. qconfig,
  1589. model,
  1590. named_modules,
  1591. model.graph,
  1592. qhandler,
  1593. prepare_custom_config,
  1594. obs_or_fq_map,
  1595. is_qat,
  1596. backend_config,
  1597. model_device,
  1598. )
  1599. # insert equalization input observers if needed
  1600. _maybe_insert_input_equalization_observers_for_node(
  1601. node,
  1602. equalization_qconfig,
  1603. model,
  1604. named_modules,
  1605. model.graph,
  1606. is_quantized_branch,
  1607. )
  1608. is_last_node_of_pattern = node is last_node
  1609. input_output_share_observers = node.meta["target_dtype_info"].get(
  1610. "input_output_share_observers", False
  1611. )
  1612. reuse_input_obs_or_fq = node.meta["target_dtype_info"].get(
  1613. "reuse_input_obs_or_fq", False
  1614. )
  1615. if is_last_node_of_pattern:
  1616. if _is_custom_module_lstm(
  1617. node, named_modules, qconfig, qhandler
  1618. ):
  1619. # Currently custom module outputs are assumed to be already quantized,
  1620. # so we need to insert a DeQuantStub after the output. For custom module
  1621. # LSTM specifically, the outputs are also a nested tuple, so we must first
  1622. # break down the tuple to insert DeQuantStubs after the internal nodes.
  1623. # TODO: This currently diverges from how custom modules are handled today,
  1624. # where we insert observers after the output instead of DeQuantStubs, and
  1625. # replace these observers with "dequantize" nodes during convert. Conceptually,
  1626. # these output observers are the same as DeQuantStubs. In the future, we
  1627. # should resolve this inconsistency by inserting DeQuantStubs for all custom
  1628. # modules, not just for LSTM.
  1629. _insert_dequant_stubs_for_custom_module_lstm_output(
  1630. node, model, named_modules, model.graph
  1631. )
  1632. if node.target not in custom_module_names_already_swapped:
  1633. custom_module_names_already_swapped.add(node.target)
  1634. _swap_custom_module_to_observed(
  1635. node, qconfig, named_modules, prepare_custom_config
  1636. )
  1637. else:
  1638. # this returns the new observer node if it was needed
  1639. maybe_output_obs_node = (
  1640. _maybe_insert_output_observer_for_node(
  1641. node,
  1642. model,
  1643. named_modules,
  1644. model.graph,
  1645. obs_or_fq_map,
  1646. is_qat,
  1647. )
  1648. )
  1649. if maybe_output_obs_node is not None:
  1650. # Update users of original node to use the output observer
  1651. # instead. For example, change
  1652. #
  1653. # next_node
  1654. # /
  1655. # cur_node -> obs
  1656. #
  1657. # to
  1658. #
  1659. # next_node
  1660. # /
  1661. # cur_node -> obs
  1662. #
  1663. # We need to save orig users before updating uses because
  1664. # the list of users will change as we update uses
  1665. orig_users = list(node.users.keys())
  1666. for user_node in orig_users:
  1667. if user_node is maybe_output_obs_node:
  1668. continue
  1669. user_node.replace_input_with(
  1670. node, maybe_output_obs_node
  1671. )
  1672. _is_observer_in_same_graph_ = (
  1673. _is_observer_in_same_graph(
  1674. node, named_modules, obs_or_fq_map, is_qat
  1675. )
  1676. )
  1677. # for ops whose inputs and outputs share observer/fqs, we modify the graph
  1678. # to make all inputs and outputs use the first input's
  1679. # observer/fq
  1680. if (
  1681. input_output_share_observers
  1682. and _is_observer_in_same_graph_
  1683. ) or reuse_input_obs_or_fq:
  1684. if not _maybe_make_input_output_share_observers(
  1685. node, model, named_modules
  1686. ):
  1687. _remove_output_observer(
  1688. node, model, named_modules
  1689. )
  1690. if qhandler is not None and qhandler.is_custom_module():
  1691. if (
  1692. node.target
  1693. not in custom_module_names_already_swapped
  1694. ):
  1695. custom_module_names_already_swapped.add(
  1696. node.target
  1697. )
  1698. _swap_custom_module_to_observed(
  1699. node,
  1700. qconfig,
  1701. named_modules,
  1702. prepare_custom_config,
  1703. )
  1704. else: # output
  1705. _maybe_insert_observers_before_graph_output(
  1706. node, model, named_modules, model.graph, obs_or_fq_map, is_qat
  1707. )
  1708. #
  1709. # After this point, the current node has input and output observers
  1710. # that it needs for itself inserted.
  1711. #
  1712. # increment the counters, so future inputs and outputs are assigned
  1713. # correct dtypes
  1714. if node.op == "placeholder":
  1715. inputs_seen_counter += 1
  1716. elif node.op == "output":
  1717. outputs_seen_counter += 1
  1718. results_node = node
  1719. return results_node
  1720. def _run_prepare_fx_on_standalone_modules(
  1721. model: torch.nn.Module,
  1722. is_qat: bool,
  1723. named_modules: dict[str, torch.nn.Module],
  1724. node_name_to_match_result_with_qconfig: Any,
  1725. prepare_custom_config: PrepareCustomConfig,
  1726. backend_config: BackendConfig,
  1727. ) -> None:
  1728. """
  1729. Runs prepare_fx on each standalone module. Note: this does
  1730. not modify the graph, it just replaces the unobserved modules with
  1731. their observed versions.
  1732. """
  1733. for (
  1734. root_node,
  1735. _,
  1736. _pattern,
  1737. qhandler,
  1738. qconfig,
  1739. ) in node_name_to_match_result_with_qconfig.values():
  1740. if qhandler is None:
  1741. continue
  1742. elif not qhandler.is_standalone_module():
  1743. continue
  1744. (
  1745. sm_qconfig_mapping,
  1746. sm_example_inputs,
  1747. sm_prepare_custom_config,
  1748. sm_backend_config,
  1749. ) = _get_standalone_module_configs(
  1750. root_node, named_modules, prepare_custom_config, qconfig, backend_config
  1751. )
  1752. standalone_module = named_modules[root_node.target]
  1753. prepare = torch.ao.quantization.quantize_fx._prepare_standalone_module_fx # type: ignore[attr-defined]
  1754. observed_standalone_module = prepare(
  1755. standalone_module,
  1756. sm_qconfig_mapping,
  1757. is_qat,
  1758. example_inputs=sm_example_inputs,
  1759. prepare_custom_config=sm_prepare_custom_config,
  1760. backend_config=sm_backend_config,
  1761. )
  1762. parent_name, name = _parent_name(root_node.target)
  1763. setattr(named_modules[parent_name], name, observed_standalone_module)
  1764. named_modules[root_node.target] = observed_standalone_module
  1765. def _save_state(
  1766. observed: GraphModule,
  1767. node_name_to_qconfig: dict[str, QConfigAny],
  1768. node_name_to_scope: dict[str, tuple[str, type]],
  1769. prepare_custom_config: PrepareCustomConfig,
  1770. equalization_node_name_to_qconfig: dict[str, Any],
  1771. qconfig_mapping: QConfigMapping,
  1772. is_qat: bool,
  1773. observed_node_names: set[str],
  1774. ) -> None:
  1775. observed.meta["_observed_graph_module_attrs"] = ObservedGraphModuleAttrs(
  1776. node_name_to_qconfig=node_name_to_qconfig,
  1777. node_name_to_scope=node_name_to_scope,
  1778. prepare_custom_config=prepare_custom_config,
  1779. equalization_node_name_to_qconfig=equalization_node_name_to_qconfig,
  1780. qconfig_mapping=qconfig_mapping,
  1781. is_qat=is_qat,
  1782. observed_node_names=observed_node_names,
  1783. )
  1784. def prepare(
  1785. model: GraphModule,
  1786. qconfig_mapping: Union[QConfigMapping, dict[str, Any]],
  1787. is_qat: bool,
  1788. node_name_to_scope: dict[str, tuple[str, type]],
  1789. example_inputs: tuple[Any, ...],
  1790. prepare_custom_config: Union[PrepareCustomConfig, dict[str, Any], None] = None,
  1791. _equalization_config: Union[QConfigMapping, dict[str, Any], None] = None,
  1792. backend_config: Union[BackendConfig, dict[str, Any], None] = None,
  1793. is_standalone_module: bool = False,
  1794. ) -> GraphModule:
  1795. """standalone_module means it a submodule that is not inlined in
  1796. parent module, and will be quantized separately as one unit.
  1797. How the standalone module is observed is specified by `input_quantized_idxs` and
  1798. `output_quantized_idxs` in the prepare_custom_config for the standalone module
  1799. Args:
  1800. node_name_to_scope: mapping from node name to the scope of the module which contains the node.
  1801. The scope is a tuple of fully qualified path of the module and the type of the module
  1802. Returns:
  1803. model(GraphModule): prepared standalone module
  1804. attributes related to standalone module
  1805. in model.meta["_observed_graph_module_attrs"]:
  1806. is_observed_standalone_module (bool): boolean value that shows whether the
  1807. current model is a observed standalone module or not
  1808. standalone_module_input_quantized_idxs(List[Int]): a list of
  1809. indexes for the graph input that is expected to be quantized,
  1810. same as input_quantized_idxs configuration provided
  1811. for the standalone module
  1812. standalone_module_output_quantized_idxs(List[Int]): a list of
  1813. indices for the graph output that is quantized
  1814. same as input_quantized_idxs configuration provided
  1815. for the standalone module
  1816. """
  1817. if prepare_custom_config is None:
  1818. prepare_custom_config = PrepareCustomConfig()
  1819. if _equalization_config is None:
  1820. _equalization_config = QConfigMapping()
  1821. if isinstance(qconfig_mapping, dict):
  1822. warnings.warn(
  1823. "Passing a QConfig dictionary to prepare is deprecated and will not be supported "
  1824. "in a future version. Please pass in a QConfigMapping instead.",
  1825. FutureWarning,
  1826. stacklevel=2,
  1827. )
  1828. qconfig_mapping = QConfigMapping.from_dict(qconfig_mapping)
  1829. if isinstance(_equalization_config, dict):
  1830. warnings.warn(
  1831. "Passing a QConfig dictionary to prepare for equalization is deprecated and will not "
  1832. "be supported in a future version. Please pass in a QConfigMapping instead.",
  1833. FutureWarning,
  1834. stacklevel=2,
  1835. )
  1836. _equalization_config = QConfigMapping.from_dict(_equalization_config)
  1837. if isinstance(prepare_custom_config, dict):
  1838. warnings.warn(
  1839. "Passing a prepare_custom_config_dict to prepare is deprecated and will not be supported "
  1840. "in a future version. Please pass in a PrepareCustomConfig instead.",
  1841. FutureWarning,
  1842. stacklevel=2,
  1843. )
  1844. prepare_custom_config = PrepareCustomConfig.from_dict(prepare_custom_config)
  1845. if isinstance(backend_config, dict):
  1846. warnings.warn(
  1847. "Passing a backend_config_dict to prepare is deprecated and will not be supported "
  1848. "in a future version. Please pass in a BackendConfig instead.",
  1849. FutureWarning,
  1850. stacklevel=2,
  1851. )
  1852. backend_config = BackendConfig.from_dict(backend_config)
  1853. assert isinstance(qconfig_mapping, QConfigMapping)
  1854. assert isinstance(_equalization_config, QConfigMapping)
  1855. qconfig_mapping = copy.deepcopy(qconfig_mapping)
  1856. _equalization_config = copy.deepcopy(_equalization_config)
  1857. # mapping from a tuple of nodes in reverse order to uninitialized
  1858. # QuantizeHandler subclass. For example,
  1859. # {
  1860. # # match a single node
  1861. # (<class 'torch.nn.modules.conv.Conv3d'>:
  1862. # <class 'torch.ao.quantization.fx.quantize.ConvRelu'>),
  1863. # # match multiple nodes in reverse order
  1864. # ((<function relu at 0x7f766a7360d0>, <built-in function add>):
  1865. # <class 'torch.ao.quantization.fx.quantize.Add'>),
  1866. # }
  1867. pattern_to_quantize_handler: dict[Pattern, QuantizeHandler] = {}
  1868. if backend_config is None:
  1869. backend_config = get_native_backend_config()
  1870. pattern_to_quantize_handler = _get_pattern_to_quantize_handlers(backend_config)
  1871. pattern_to_quantize_handler = _sorted_patterns_dict(pattern_to_quantize_handler)
  1872. root_node_getter_mapping = get_fusion_pattern_to_root_node_getter(backend_config)
  1873. _update_qconfig_for_fusion(model, qconfig_mapping)
  1874. _update_qconfig_for_fusion(model, _equalization_config)
  1875. flattened_qconfig_dict = _get_flattened_qconfig_dict(qconfig_mapping)
  1876. # TODO: support regex as well
  1877. propagate_qconfig_(model, flattened_qconfig_dict, prepare_custom_config.to_dict())
  1878. if is_qat:
  1879. module_to_qat_module = get_module_to_qat_module(backend_config)
  1880. _qat_swap_modules(model, module_to_qat_module)
  1881. _update_qconfig_for_qat(qconfig_mapping, backend_config)
  1882. # mapping from fully qualified module name to module instance
  1883. # for example,
  1884. # {
  1885. # '': Model(...),
  1886. # 'linear': Linear(...),
  1887. # 'linear.weight_fake_quant': PerChannelMinMaxObserver(...),
  1888. # }
  1889. named_modules = dict(model.named_modules(remove_duplicate=False))
  1890. # fill node_name_to_qconfig, a map from node name to qconfig, used in _find_matches
  1891. equalization_node_name_to_qconfig = _generate_node_name_to_qconfig(
  1892. model, named_modules, model.graph, _equalization_config, node_name_to_scope
  1893. )
  1894. node_name_to_qconfig = _generate_node_name_to_qconfig(
  1895. model, named_modules, model.graph, qconfig_mapping, node_name_to_scope
  1896. )
  1897. # match the patterns that will get quantized
  1898. standalone_module_names = list(prepare_custom_config.standalone_module_names.keys())
  1899. standalone_module_classes = list(
  1900. prepare_custom_config.standalone_module_classes.keys()
  1901. )
  1902. custom_module_classes = get_custom_module_class_keys(
  1903. prepare_custom_config.float_to_observed_mapping
  1904. )
  1905. matches_without_qconfig = _find_matches(
  1906. model.graph,
  1907. named_modules,
  1908. pattern_to_quantize_handler,
  1909. root_node_getter_mapping,
  1910. standalone_module_names,
  1911. standalone_module_classes,
  1912. custom_module_classes,
  1913. )
  1914. # map qconfig instances to matches
  1915. node_name_to_match_result_with_qconfig = {}
  1916. for node_name, match_without_qconfig in matches_without_qconfig.items():
  1917. match_with_qconfig = (*match_without_qconfig, node_name_to_qconfig[node_name])
  1918. node_name_to_match_result_with_qconfig[node_name] = match_with_qconfig
  1919. _run_prepare_fx_on_standalone_modules(
  1920. model,
  1921. is_qat,
  1922. named_modules,
  1923. node_name_to_match_result_with_qconfig,
  1924. prepare_custom_config,
  1925. backend_config,
  1926. )
  1927. # record names for the set of observed node, so that in convert step
  1928. # we know whether we need to convert a floating point module to reference
  1929. # quantized module or not
  1930. observed_node_names: set[str] = set()
  1931. result_node = insert_observers_for_model(
  1932. model,
  1933. node_name_to_match_result_with_qconfig,
  1934. node_name_to_qconfig,
  1935. prepare_custom_config,
  1936. equalization_node_name_to_qconfig,
  1937. backend_config,
  1938. observed_node_names,
  1939. is_qat,
  1940. )
  1941. model = GraphModule(model, model.graph)
  1942. _save_state(
  1943. model,
  1944. node_name_to_qconfig,
  1945. node_name_to_scope,
  1946. prepare_custom_config,
  1947. equalization_node_name_to_qconfig,
  1948. qconfig_mapping,
  1949. is_qat,
  1950. observed_node_names,
  1951. )
  1952. if is_standalone_module:
  1953. assert result_node is not None
  1954. assert isinstance(result_node.args[0], Node), (
  1955. "standalone module only supports returning simple value currently"
  1956. "(not tuple, dict etc.)"
  1957. )
  1958. # these inputs are observed in parent
  1959. # converting List[int] to Tensor since module attribute is
  1960. # Union[Tensor, Module]
  1961. input_quantized_idxs: list[int] = prepare_custom_config.input_quantized_indexes
  1962. output_quantized_idxs: list[int] = (
  1963. prepare_custom_config.output_quantized_indexes
  1964. )
  1965. observed_graph_module_attrs = model.meta["_observed_graph_module_attrs"]
  1966. # inplace modification
  1967. observed_graph_module_attrs.is_observed_standalone_module = True
  1968. observed_graph_module_attrs.standalone_module_input_quantized_idxs = (
  1969. input_quantized_idxs
  1970. )
  1971. observed_graph_module_attrs.standalone_module_output_quantized_idxs = (
  1972. output_quantized_idxs
  1973. )
  1974. return model