convert.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. from typing import Any, Dict, List, Optional, Set, Tuple, Union, Type, Callable
  2. from torch.ao.quantization.quant_type import QuantType
  3. import torch
  4. import copy
  5. import warnings
  6. from torch.fx import (
  7. GraphModule,
  8. )
  9. from torch.fx.graph import (
  10. Graph,
  11. Node,
  12. Argument,
  13. )
  14. from ..utils import (
  15. activation_is_statically_quantized,
  16. weight_is_quantized,
  17. get_qparam_dict,
  18. _parent_name,
  19. get_swapped_custom_module_class,
  20. )
  21. from ..qconfig import (
  22. QConfigAny,
  23. qconfig_equals
  24. )
  25. from ..qconfig_mapping import QConfigMapping
  26. from .qconfig_mapping_utils import (
  27. _generate_node_name_to_qconfig,
  28. _compare_prepare_convert_qconfig_mappings,
  29. _update_qconfig_for_fusion,
  30. _is_qconfig_supported_by_dtype_configs,
  31. _update_qconfig_for_qat,
  32. )
  33. from torch.ao.quantization.backend_config.utils import (
  34. get_root_module_to_quantized_reference_module,
  35. get_pattern_to_dtype_configs,
  36. get_fused_module_classes,
  37. get_qat_module_classes,
  38. )
  39. from torch.ao.quantization.backend_config import (
  40. BackendConfig,
  41. get_native_backend_config,
  42. )
  43. from torch.ao.quantization.observer import _is_activation_post_process
  44. from .graph_module import (
  45. _is_observed_module,
  46. _is_observed_standalone_module,
  47. )
  48. from ._equalize import update_obs_for_equalization, convert_eq_obs
  49. from torch.nn.utils.parametrize import type_before_parametrizations
  50. from .utils import (
  51. _get_module,
  52. _is_custom_module_lstm,
  53. get_custom_module_class_keys,
  54. create_getattr_from_value,
  55. collect_producer_nodes,
  56. graph_module_from_producer_nodes,
  57. node_arg_is_weight,
  58. )
  59. from torch.ao.quantization.utils import (
  60. is_per_channel,
  61. to_underlying_dtype,
  62. )
  63. from torch.ao.quantization.quantize import (
  64. _remove_qconfig,
  65. )
  66. from torch.ao.quantization.stubs import DeQuantStub
  67. from .custom_config import (
  68. ConvertCustomConfig,
  69. PrepareCustomConfig,
  70. )
  71. from .lower_to_fbgemm import lower_to_fbgemm
  72. # importing the lib so that the quantized_decomposed ops are registered
  73. from ._decomposed import quantized_decomposed_lib # noqa: F401
  74. import operator
  75. __all__ = [
  76. "convert",
  77. "convert_custom_module",
  78. "convert_standalone_module",
  79. "convert_weighted_module",
  80. ]
  81. def _replace_observer_with_quantize_dequantize_node_decomposed(
  82. model: torch.nn.Module,
  83. graph: Graph,
  84. node: Node,
  85. modules: Dict[str, torch.nn.Module],
  86. node_name_to_scope: Dict[str, Tuple[str, type]],
  87. node_name_to_qconfig: Dict[str, QConfigAny]) -> None:
  88. """ Replace activation_post_process module call node with quantize and
  89. dequantize node working with decomposed Tensor
  90. Before:
  91. ... -> observer_0(x) -> ...
  92. After:
  93. ... -> torch.ops.quantized_decomposed.quantize_per_tensor(x, ...) ->
  94. torch.ops.quantized_decomposed.dequantize_per_tensor() -> ...
  95. or quantize_per_channel and dequantize_per_channel
  96. """
  97. assert modules is not None
  98. assert isinstance(node.target, str)
  99. module_path, prefix = _get_module_path_and_prefix(node, node_name_to_scope, node_name_to_qconfig)
  100. activation_post_process = modules[node.target]
  101. # skip replacing observers to quant/dequant nodes if the qconfigs of all
  102. # consumers and producers of this observer are None
  103. skip_replacement = all([
  104. _has_none_qconfig(n, node_name_to_qconfig) for n in
  105. list(node.args) + list(node.users.keys())])
  106. if skip_replacement or not _is_conversion_supported(activation_post_process):
  107. # didn't find correponding quantize op and info for the activation_post_process
  108. # so we just remove the observer
  109. with graph.inserting_before(node):
  110. node.replace_all_uses_with(node.args[0])
  111. graph.erase_node(node)
  112. return
  113. # otherwise, we can convert the activation_post_process module call to quantize/dequantize node
  114. # 1. extract the information from activation_post_process module for generating
  115. # the quantize and dequantize operator
  116. dtype = activation_post_process.dtype # type: ignore[attr-defined]
  117. is_dynamic = False
  118. if hasattr(activation_post_process, "is_dynamic"):
  119. is_dynamic = activation_post_process.is_dynamic # type: ignore[assignment]
  120. if dtype in [torch.quint8, torch.qint8, torch.qint32] and \
  121. (not is_dynamic):
  122. # TODO: probably should cleanup this condition check, it's hard
  123. # to reason about this if and the following elif
  124. # uint8/int8/int32 static quantization branch
  125. # 1. extract information for inserting q/dq node from activation_post_process
  126. node_type = "call_function"
  127. quantize_op : Optional[Callable] = None
  128. scale, zero_point = activation_post_process.calculate_qparams() # type: ignore[attr-defined, operator]
  129. if is_per_channel(activation_post_process.qscheme): # type: ignore[attr-defined]
  130. ch_axis = int(activation_post_process.ch_axis) # type: ignore[attr-defined, arg-type]
  131. quantize_op = torch.ops.quantized_decomposed.quantize_per_channel
  132. dequantize_op = torch.ops.quantized_decomposed.dequantize_per_channel
  133. quant_min = activation_post_process.quant_min
  134. quant_max = activation_post_process.quant_max
  135. dtype_ = to_underlying_dtype(dtype)
  136. qparams = {
  137. "_scale_": scale,
  138. "_zero_point_": zero_point,
  139. "_axis_": ch_axis,
  140. "_quant_min_": quant_min,
  141. "_quant_max_": quant_max,
  142. "_dtype_": dtype_
  143. }
  144. else:
  145. quantize_op = torch.ops.quantized_decomposed.quantize_per_tensor
  146. dequantize_op = torch.ops.quantized_decomposed.dequantize_per_tensor
  147. scale = float(scale)
  148. zero_point = int(zero_point)
  149. quant_min = activation_post_process.quant_min # type: ignore[attr-defined]
  150. quant_max = activation_post_process.quant_max # type: ignore[attr-defined]
  151. dtype_ = to_underlying_dtype(dtype)
  152. qparams = {
  153. "_scale_": scale,
  154. "_zero_point_": zero_point,
  155. "_quant_min_": quant_min,
  156. "_quant_max_": quant_max,
  157. "_dtype_": dtype_
  158. }
  159. # 2. replace activation_post_process node with quantize and dequantize
  160. with graph.inserting_before(node):
  161. input_node = node.args[0]
  162. quantize_op_inputs = [input_node]
  163. for key, value_or_node in qparams.items():
  164. # TODO: we can add the information of whether a value needs to
  165. # be registered as an attribute in qparams dict itself
  166. if key in ['_scale_', '_zero_point_']:
  167. # For scale and zero_point values we register them as buffers in the root module.
  168. # TODO: maybe need more complex attr name here
  169. qparam_node = create_getattr_from_value(
  170. model, graph, module_path + prefix + key, value_or_node)
  171. quantize_op_inputs.append(qparam_node)
  172. else:
  173. # for qparams that are not scale/zero_point (like axis, dtype) we store them as literals in the graph.
  174. quantize_op_inputs.append(value_or_node)
  175. quantized_node = graph.create_node(node_type, quantize_op, tuple(quantize_op_inputs), {})
  176. # use the same qparams from quantize op
  177. dq_inputs = [quantized_node] + quantize_op_inputs[1:]
  178. dequantized_node = graph.call_function(
  179. dequantize_op,
  180. tuple(dq_inputs),
  181. {}
  182. )
  183. node.replace_all_uses_with(dequantized_node)
  184. graph.erase_node(node)
  185. elif is_dynamic:
  186. # uint8/int8/fp16 dynamic quantization
  187. # 1. extract information for inserting q/dq node from activation_post_process
  188. node_type = "call_function"
  189. quantize_op = torch.ops.quantized_decomposed.quantize_per_tensor.tensor
  190. # we only use choose_qparams for is_decomposed now,
  191. # but we should probably align the non-decomposed path with this as well,
  192. # and that can be done after we remove reduce_range flag
  193. # 1. extract qparams from activation_post_process module
  194. dtype_ = to_underlying_dtype(dtype)
  195. assert dtype_ in [torch.uint8, torch.int8], \
  196. "only uint8 and int8 are supported in reference flow for " \
  197. "dynamic quantization right now"
  198. quant_min = activation_post_process.quant_min # type: ignore[attr-defined]
  199. quant_max = activation_post_process.quant_max # type: ignore[attr-defined]
  200. # note: scale and zero_point are missing for quantize_per_tensor op
  201. # we'll need to get this from choose_qparams op, which we'll add after
  202. # this step
  203. qparams = {
  204. "_quant_min_": quant_min,
  205. "_quant_max_": quant_max,
  206. "_dtype_": dtype_
  207. }
  208. # 2. insert choose_qparams op and update the qparams list
  209. with graph.inserting_before(node):
  210. input_node = node.args[0]
  211. choose_qparams_op_inputs = [node.args[0]]
  212. for key, value in qparams.items():
  213. # we have quant_min, quant_max and dtype, all should be stored
  214. # as literals
  215. choose_qparams_op_inputs.append(value)
  216. choose_qparams_node = graph.create_node(
  217. "call_function",
  218. torch.ops.quantized_decomposed.choose_qparams.tensor,
  219. tuple(choose_qparams_op_inputs),
  220. {}
  221. )
  222. # choose_qparms returns (scale, zero_point)
  223. scale_node = graph.create_node(
  224. "call_function",
  225. operator.getitem,
  226. (choose_qparams_node, 0),
  227. {}
  228. )
  229. zero_point_node = graph.create_node(
  230. "call_function",
  231. operator.getitem,
  232. (choose_qparams_node, 1),
  233. {}
  234. )
  235. quant_min = qparams["_quant_min_"]
  236. quant_max = qparams["_quant_max_"]
  237. dtype = qparams["_dtype_"]
  238. qparams = {
  239. "_scale_": scale_node,
  240. "_zero_point_": zero_point_node,
  241. "_quant_min_": quant_min,
  242. "_quant_max_": quant_max,
  243. "_dtype_": dtype
  244. }
  245. # 3. replace activation_post_process node to quantize and dequantize node
  246. with graph.inserting_before(node):
  247. input_node = node.args[0]
  248. quantize_op_inputs = [input_node]
  249. for key, value_or_node in qparams.items():
  250. # TODO: we can add the information of whether a value needs to
  251. # be registered as an attribute in qparams dict itself
  252. if key in ['_scale_', '_zero_point_']:
  253. # in this case we have a node in the graph since it's dynamically
  254. # computed from the input, with choose_qparams op
  255. qparam_node = value_or_node
  256. quantize_op_inputs.append(qparam_node)
  257. else:
  258. # for qparams that are not scale/zero_point (like axis, dtype) we
  259. # store them as literals in the graph.
  260. quantize_op_inputs.append(value_or_node)
  261. quantized_node = graph.create_node(node_type, quantize_op, tuple(quantize_op_inputs), {})
  262. # use the same qparams from quantize op
  263. dq_inputs = [quantized_node] + quantize_op_inputs[1:]
  264. # need to use the tensor variant of this op, since scale and zero_point
  265. # from choose_qparam are Tensors, instead of float/int, this is to
  266. # prevent these nodes being traced away by downstream systems
  267. dequantize_op = torch.ops.quantized_decomposed.dequantize_per_tensor.tensor
  268. dequantized_node = graph.call_function(
  269. dequantize_op,
  270. tuple(dq_inputs),
  271. {}
  272. )
  273. node.replace_all_uses_with(dequantized_node)
  274. graph.erase_node(node)
  275. elif dtype == torch.float16:
  276. raise NotImplementedError("decomposed to float16 op not implemented yet")
  277. # should not reach since we have checks in the begining to make sure the
  278. # activation_post_process is supported
  279. def _replace_observer_with_quantize_dequantize_node(
  280. model: torch.nn.Module,
  281. graph: Graph,
  282. node: Node,
  283. modules: Dict[str, torch.nn.Module],
  284. node_name_to_scope: Dict[str, Tuple[str, type]],
  285. node_name_to_qconfig: Dict[str, QConfigAny]) -> None:
  286. """ Replace activation_post_process module call node with quantize and
  287. dequantize node
  288. Before:
  289. ... -> observer_0(x) -> ...
  290. After:
  291. ... -> torch.quantize_per_tensor(x, ...) -> x.dequantize() -> ...
  292. """
  293. assert modules is not None
  294. assert isinstance(node.target, str)
  295. module_path, prefix = _get_module_path_and_prefix(node, node_name_to_scope, node_name_to_qconfig)
  296. activation_post_process = modules[node.target]
  297. # skip replacing observers to quant/dequant nodes if the qconfigs of all
  298. # consumers and producers of this observer are None
  299. skip_replacement = all([
  300. _has_none_qconfig(n, node_name_to_qconfig) for n in
  301. list(node.args) + list(node.users.keys())])
  302. if skip_replacement or not _is_conversion_supported(activation_post_process):
  303. # didn't find correponding quantize op and info for the activation_post_process
  304. # so we just remove the observer
  305. with graph.inserting_before(node):
  306. node.replace_all_uses_with(node.args[0])
  307. graph.erase_node(node)
  308. return
  309. # otherwise, we can convert the activation_post_process module call to quantize/dequantize node
  310. dtype = activation_post_process.dtype # type: ignore[attr-defined]
  311. is_dynamic = False
  312. if hasattr(activation_post_process, "is_dynamic"):
  313. is_dynamic = activation_post_process.is_dynamic # type: ignore[attr-defined, assignment]
  314. if dtype in [torch.quint8, torch.qint8, torch.qint32] and \
  315. (not is_dynamic):
  316. # TODO: probably should cleanup this condition check, it's hard
  317. # to reason about this if and the following elif
  318. # uint8/int8/int32 static quantization branch
  319. # 1. extract the information from activation_post_process module for generating
  320. # the quantize and dequantize operator
  321. node_type = "call_function"
  322. quantize_op : Optional[Callable] = None
  323. scale, zero_point = activation_post_process.calculate_qparams() # type: ignore[attr-defined, operator]
  324. if is_per_channel(activation_post_process.qscheme): # type: ignore[attr-defined]
  325. ch_axis = int(activation_post_process.ch_axis) # type: ignore[attr-defined, arg-type]
  326. qparams = {"_scale_": scale, "_zero_point_": zero_point, "_axis_": ch_axis, "_dtype_": dtype}
  327. quantize_op = torch.quantize_per_channel
  328. else:
  329. scale = float(scale)
  330. zero_point = int(zero_point)
  331. qparams = {"_scale_": scale, "_zero_point_": zero_point, "_dtype_": dtype}
  332. quantize_op = torch.quantize_per_tensor
  333. # 2. replace activation_post_process node with quantize and dequantize
  334. with graph.inserting_before(node):
  335. input_node = node.args[0]
  336. quantize_op_inputs = [input_node]
  337. for key, value_or_node in qparams.items():
  338. # TODO: we can add the information of whether a value needs to
  339. # be registered as an attribute in qparams dict itself
  340. if key in ['_scale_', '_zero_point_']:
  341. # For scale and zero_point values we register them as buffers in the root module.
  342. # TODO: maybe need more complex attr name here
  343. qparam_node = create_getattr_from_value(
  344. model, graph, module_path + prefix + key, value_or_node)
  345. quantize_op_inputs.append(qparam_node)
  346. else:
  347. # for qparams that are not scale/zero_point (like axis, dtype) we store them as literals in the graph.
  348. quantize_op_inputs.append(value_or_node)
  349. quantized_node = graph.create_node(node_type, quantize_op, tuple(quantize_op_inputs), {})
  350. dequantized_node = graph.call_method("dequantize", args=(quantized_node,))
  351. node.replace_all_uses_with(dequantized_node)
  352. graph.erase_node(node)
  353. elif is_dynamic:
  354. # uint8/int8/fp16 dynamic quantization branch
  355. node_type = "call_function"
  356. quantize_op = torch.quantize_per_tensor_dynamic
  357. # TODO: get reduce range from observer
  358. # reduce_range = activation_post_process.reduce_range
  359. reduce_range = torch.backends.quantized.engine in ("fbgemm", "x86")
  360. qparams = {"_dtype_": dtype, "_reduce_range_": reduce_range}
  361. with graph.inserting_before(node):
  362. input_node = node.args[0]
  363. quantize_op_inputs = [input_node]
  364. for key, value in qparams.items():
  365. quantize_op_inputs.append(value)
  366. quantized_node = graph.create_node(node_type, quantize_op, tuple(quantize_op_inputs), {})
  367. dequantized_node = graph.call_method("dequantize", args=(quantized_node,))
  368. node.replace_all_uses_with(dequantized_node)
  369. graph.erase_node(node)
  370. elif dtype == torch.float16:
  371. node_type = "call_method"
  372. quantize_op = "to" # type: ignore[assignment]
  373. qparams = {"_dtype_": dtype}
  374. with graph.inserting_before(node):
  375. input_node = node.args[0]
  376. quantize_op_inputs = [input_node]
  377. for key, value in qparams.items():
  378. # TODO: we can add the information of whether a value needs to
  379. # be registered as an attribute in qparams dict itself
  380. quantize_op_inputs.append(value)
  381. quantized_node = graph.create_node(node_type, quantize_op, tuple(quantize_op_inputs), {})
  382. dequantized_node = graph.call_method("dequantize", args=(quantized_node,))
  383. node.replace_all_uses_with(dequantized_node)
  384. graph.erase_node(node)
  385. # should not reach since we have checks in the begining to make sure the
  386. # activation_post_process is supported
  387. # this is a temporary hack for custom module, we may want to implement
  388. # this properly after the custom module class design is finalized
  389. # TODO: DeQuantStubs are currently inserted only after custom module LSTM, while observers are inserted
  390. # after all other custom modules. In the future, we should simply insert QuantStubs before and DeQuantStubs
  391. # after custom modules in general, and replace these with "quantize" and "dequantize" nodes respectively.
  392. def _replace_observer_or_dequant_stub_with_dequantize_node(node: Node, graph: Graph):
  393. call_custom_module_node = node.args[0]
  394. assert isinstance(call_custom_module_node, Node), \
  395. f"Expecting the for call custom module node to be a Node, but got {call_custom_module_node}"
  396. node.replace_all_uses_with(call_custom_module_node)
  397. graph.erase_node(node)
  398. _insert_dequantize_node(call_custom_module_node, graph)
  399. def _is_conversion_supported(activation_post_process: torch.nn.Module) -> bool:
  400. dtype = activation_post_process.dtype # type: ignore[attr-defined]
  401. is_dynamic = False
  402. if hasattr(activation_post_process, "is_dynamic"):
  403. is_dynamic = activation_post_process.is_dynamic # type: ignore[attr-defined, assignment]
  404. return (
  405. (dtype in [torch.quint8, torch.qint8, torch.qint32] and (not is_dynamic)) or # type: ignore[return-value]
  406. is_dynamic or
  407. dtype == torch.float16
  408. )
  409. def _has_none_qconfig(node: Argument, node_name_to_qconfig: Dict[str, QConfigAny]) -> bool:
  410. """ Check if a node has a qconfig of None, i.e. user requested to not quantize
  411. the node
  412. """
  413. return isinstance(node, Node) and node.name in node_name_to_qconfig and node_name_to_qconfig[node.name] is None
  414. def _run_weight_observers(observed: GraphModule, backend_config: BackendConfig) -> None:
  415. """ Extract the subgraph that produces the weight for dynamic quant
  416. or weight only quant node and run the subgraph to observe the weight.
  417. Note that the observers of dynamic quant or weight only quant ops are
  418. run during the convert step.
  419. """
  420. for node in observed.graph.nodes:
  421. if node.op != "call_function":
  422. continue
  423. for node_arg in node.args:
  424. # node_arg is weight
  425. if node_arg and node_arg_is_weight(node, node_arg, backend_config):
  426. weight_observer_nodes = collect_producer_nodes(node_arg)
  427. if weight_observer_nodes is None:
  428. continue
  429. weight_observer_module = \
  430. graph_module_from_producer_nodes(
  431. observed, weight_observer_nodes)
  432. # run the weight observer
  433. weight_observer_module()
  434. def _maybe_recursive_remove_dequantize(arg: Any, node: Node, graph: Graph):
  435. """ If the arg is a dequantize Node, or a list/tuple/dict of dequantize Node,
  436. we'll recursively remove the dequantize Node
  437. """
  438. if isinstance(arg, Node) and \
  439. arg.op == "call_method" and \
  440. arg.target == "dequantize":
  441. quantize_node = arg.args[0]
  442. # we only replace the specific use since dequantize could be used by other nodes
  443. # as well
  444. node.replace_input_with(arg, quantize_node)
  445. elif isinstance(arg, (list, tuple)):
  446. for arg_element in arg:
  447. _maybe_recursive_remove_dequantize(arg_element, node, graph)
  448. elif isinstance(arg, dict):
  449. for arg_element in arg.values():
  450. _maybe_recursive_remove_dequantize(arg_element, node, graph)
  451. else:
  452. warnings.warn(f"Unsupported node type in recursive remove dequantize: {type(arg)}")
  453. def _get_module_path_and_prefix(
  454. obs_node: Node,
  455. node_name_to_scope: Dict[str, Tuple[str, type]],
  456. node_name_to_qconfig: Dict[str, QConfigAny]):
  457. """ Given and observer node, get the `Scope` or the fully qualified name for
  458. the submodule containing the observed node, also return a prefix of "_input"
  459. when the observed node is an input of a F.linear op, and not the output of another
  460. quantized op.
  461. TODO: this logic is hacky, we should think about how to remove it or make it more
  462. general
  463. """
  464. observed_node = obs_node.args[0]
  465. # an observer can be inserted for both input of the next operator or output of the previous
  466. # operator (they can be the same)
  467. # this flag identifies if the observer is inserted only because the observed node is
  468. # the input of the next operator
  469. assert isinstance(observed_node, Node), \
  470. f"Expecting observed node to be a Node, but got {observed_node}"
  471. is_input_observer_only = node_name_to_qconfig[observed_node.name] is None \
  472. if observed_node.name in node_name_to_qconfig else None
  473. if is_input_observer_only:
  474. # if the quantize function is at the input of op, then we find the first user of the observer_node
  475. # to get the path. If a linear call_function is in the user list, we return the first instance
  476. # of linear node to get the FQN.
  477. users = list(obs_node.users)
  478. first_linear_use_or_first_use = users[0] if users else None
  479. linear_node = None
  480. for n in users:
  481. if n.op == "call_function" and n.target == torch.nn.functional.linear:
  482. linear_node = n
  483. break
  484. if linear_node:
  485. first_linear_use_or_first_use = linear_node
  486. prefix = "_input"
  487. else:
  488. # if the quantize function is at the output of the op, we use the observer input node to get the path
  489. first_linear_use_or_first_use = observed_node
  490. prefix = ""
  491. if first_linear_use_or_first_use and first_linear_use_or_first_use.name in node_name_to_scope:
  492. module_path, _ = node_name_to_scope[first_linear_use_or_first_use.name]
  493. else:
  494. # TODO: it's not used, so actually we can skip quantization
  495. # but this requires changing return type of quantize_node
  496. # we can fix it later if needed
  497. module_path = ""
  498. return module_path, prefix
  499. def _insert_dequantize_node(
  500. node: Node,
  501. graph: Graph):
  502. """ Inserts dequantize node for `node` in `graph`
  503. """
  504. with graph.inserting_after(node):
  505. dequantize_node = graph.call_method("dequantize", (node,))
  506. for user_node in dict(node.users):
  507. if user_node is not dequantize_node:
  508. user_node.replace_input_with(node, dequantize_node)
  509. def _maybe_get_observer_for_node(
  510. node: Node,
  511. modules: Dict[str, torch.nn.Module]
  512. ) -> Optional[torch.nn.Module]:
  513. """
  514. If the node is observed, return the observer
  515. instance. Otherwise, return None.
  516. """
  517. for maybe_obs_node, _ in node.users.items():
  518. if maybe_obs_node.op == 'call_module':
  519. maybe_obs = modules[str(maybe_obs_node.target)]
  520. if _is_activation_post_process(maybe_obs):
  521. return maybe_obs
  522. return None
  523. def convert_standalone_module(
  524. node: Node,
  525. modules: Dict[str, torch.nn.Module],
  526. model: torch.fx.GraphModule,
  527. is_reference: bool,
  528. backend_config: Optional[BackendConfig]):
  529. """ Converts a observed standalone module to a quantized standalone module by calling
  530. the fx convert api, currently using the same `is_reference` flag as parent, but we may
  531. changing this behavior in the future (e.g. separating quantization and lowering for
  532. standalone module as well)
  533. Args:
  534. - node: The call_module node of the observed standalone module
  535. - modules: named_module of original model
  536. - model: original model
  537. - is_reference: a flag from parent provided by user to decide if we want to
  538. produce a reference model or a fbgemm/qnnpack model
  539. - backend_config: backend configuration of the target backend of quantization
  540. """
  541. # TODO: remove is_reference flag
  542. if is_reference:
  543. convert_fn = torch.ao.quantization.quantize_fx.convert_to_reference_fx
  544. else:
  545. convert_fn = torch.ao.quantization.quantize_fx.convert_fx # type: ignore[attr-defined]
  546. # We know that observed standalone module is a GraphModule since
  547. # it's produced by us
  548. observed_standalone_module : GraphModule = modules[str(node.target)] # type: ignore[assignment]
  549. sm_input_quantized_idxs = \
  550. observed_standalone_module \
  551. .meta["_observed_graph_module_attrs"].standalone_module_input_quantized_idxs
  552. # remove the dequantize nodes for inputs
  553. args = list(node.args)
  554. for idx in range(len(args)):
  555. if idx in sm_input_quantized_idxs:
  556. arg = args[idx]
  557. if arg.op == "call_method" and arg.target == "dequantize": # type: ignore[union-attr]
  558. quantize_node = arg.args[0] # type: ignore[union-attr]
  559. node.replace_input_with(arg, quantize_node)
  560. if len(arg.users) == 0: # type: ignore[union-attr]
  561. model.graph.erase_node(arg)
  562. # add dequantize node for output
  563. sm_output_quantized_idxs = \
  564. observed_standalone_module \
  565. .meta["_observed_graph_module_attrs"].standalone_module_output_quantized_idxs
  566. if len(sm_output_quantized_idxs) > 0:
  567. assert sm_output_quantized_idxs[0] == 0, "Currently only quantized"
  568. "output idxs = [0] is supported"
  569. # if it's non-empty, then it means the output is kept in quantized form
  570. # we'll just add a dequantize node after this node
  571. _insert_dequantize_node(node, model.graph)
  572. # TODO: allow convert_custom_config to override backend_config
  573. # for standalone module
  574. quantized_standalone_module = convert_fn(
  575. observed_standalone_module,
  576. backend_config=backend_config)
  577. parent_name, name = _parent_name(node.target)
  578. # update the modules dict
  579. setattr(modules[parent_name], name, quantized_standalone_module)
  580. modules[str(node.target)] = quantized_standalone_module
  581. def convert_weighted_module(
  582. node: Node,
  583. modules: Dict[str, torch.nn.Module],
  584. observed_node_names: Set[str],
  585. node_name_to_qconfig: Dict[str, QConfigAny],
  586. backend_config: BackendConfig,
  587. is_decomposed: bool = False):
  588. """ Convert a weighted module to reference quantized module in the model
  589. If the QConfig of a QAT module is not set, the module will still be converted to
  590. a float module.
  591. Args:
  592. - node: The call_module node of the observed standalone module
  593. - modules: named_module of original model
  594. - observed_node_names: names for the set of observed fx node, we can skip
  595. this conversion if the node is not observed
  596. """
  597. original_module = modules[str(node.target)]
  598. qconfig: QConfigAny = original_module.qconfig # type: ignore[assignment]
  599. weight_post_process = None
  600. qat_module_classes = get_qat_module_classes(backend_config)
  601. if isinstance(
  602. original_module,
  603. qat_module_classes):
  604. # Converting qat module to a float module, we need to attch
  605. # weight fake_quant to the module, weight fake_quant is assumed to be run during
  606. # QAT so we don't need to run it again here
  607. weight_post_process = original_module.weight_fake_quant
  608. original_module = original_module.to_float() # type: ignore[operator]
  609. # change qat module to float module
  610. parent_name, name = _parent_name(node.target)
  611. setattr(modules[parent_name], name, original_module)
  612. is_observed = node.name in observed_node_names
  613. # If a qconfig is not defined for this node, then skip converting to a reference module
  614. if qconfig is None or _has_none_qconfig(node, node_name_to_qconfig) or not is_observed:
  615. return
  616. # skip converting to reference quantized module if the qconfig is not supported
  617. pattern_to_dtype_configs = get_pattern_to_dtype_configs(backend_config)
  618. dtype_configs = pattern_to_dtype_configs.get(type(original_module), [])
  619. if not _is_qconfig_supported_by_dtype_configs(qconfig, dtype_configs):
  620. return
  621. # TODO: rename weight_is_statically_quantized to weight_is_int8_quantized
  622. is_weight_quantized = weight_is_quantized(qconfig)
  623. # the condition for swapping the module to reference quantized module is:
  624. # weights need to be quantized
  625. if not is_weight_quantized:
  626. return
  627. fused_module = None
  628. float_module = original_module
  629. # extract the inidividual float_module and fused module
  630. if isinstance(original_module, torch.ao.nn.intrinsic._FusedModule):
  631. fused_module = float_module
  632. float_module = fused_module[0] # type: ignore[index]
  633. # TODO: move this to the reference quantized module
  634. # weight_qparams or weight_qparams dict
  635. wq_or_wq_dict = {"is_decomposed": is_decomposed}
  636. if isinstance(float_module, torch.nn.RNNCellBase):
  637. weight_post_process_ih = qconfig.weight() # type: ignore[union-attr, operator]
  638. weight_post_process_hh = qconfig.weight() # type: ignore[union-attr, operator]
  639. weight_post_process_ih(float_module.weight_ih)
  640. weight_post_process_hh(float_module.weight_hh)
  641. weight_qparams_ih = get_qparam_dict(weight_post_process_ih)
  642. weight_qparams_hh = get_qparam_dict(weight_post_process_hh)
  643. wq_or_wq_dict.update({
  644. "weight_ih": weight_qparams_ih,
  645. "weight_hh": weight_qparams_hh,
  646. })
  647. elif isinstance(float_module, (torch.nn.LSTM, torch.nn.GRU)):
  648. # format for wq_or_wq_dict (flattened attributes):
  649. # {"weight_ih_l0_scale": ..., "weight_ih_l0_qscheme": ..., ...}
  650. for wn in float_module._flat_weights_names:
  651. if hasattr(float_module, wn) and wn.startswith("weight"):
  652. weight = getattr(float_module, wn)
  653. weight_post_process = qconfig.weight() # type: ignore[union-attr, operator]
  654. if weight_post_process.dtype == torch.qint8: # type: ignore[union-attr]
  655. weight_post_process(weight) # type: ignore[operator, misc]
  656. wq_or_wq_dict[wn] = get_qparam_dict(weight_post_process)
  657. else:
  658. # weight_post_process is None means the original module is not a QAT module
  659. # we need to get weight_post_process from qconfig in this case
  660. if weight_post_process is None:
  661. weight_post_process = qconfig.weight() # type: ignore[union-attr, operator]
  662. # run weight observer
  663. # TODO: This is currently a hack for QAT to get the right shapes for scale and zero point.
  664. # In the future, we should require the user to calibrate the model after calling prepare
  665. # Issue: https://github.com/pytorch/pytorch/issues/73941
  666. weight_post_process(float_module.weight) # type: ignore[operator]
  667. wq_or_wq_dict.update(get_qparam_dict(weight_post_process))
  668. # We use the same reference module for all modes of quantization: static, dynamic, weight_only
  669. # root_module_to_quantized_reference_module: module mapping from root (floating point) module class
  670. # to quantized reference module class, e.g. nn.Conv2d to nn.quantized._reference.Conv2d
  671. root_module_to_quantized_reference_module = get_root_module_to_quantized_reference_module(backend_config)
  672. ref_qmodule_cls = root_module_to_quantized_reference_module.get(type_before_parametrizations(float_module), None)
  673. assert (
  674. ref_qmodule_cls is not None
  675. ), f"No reference quantized module class configured for {type_before_parametrizations(float_module)}"
  676. ref_qmodule = ref_qmodule_cls.from_float(float_module, wq_or_wq_dict) # type: ignore[attr-defined]
  677. if fused_module is not None:
  678. fused_module[0] = ref_qmodule # type: ignore[operator]
  679. else:
  680. parent_name, name = _parent_name(node.target)
  681. setattr(modules[parent_name], name, ref_qmodule)
  682. def _remove_previous_dequantize_in_custom_module(node: Node, prev_node: Node, graph: Graph):
  683. """
  684. Given a custom module `node`, if the previous node is a dequantize, reroute the custom as follows:
  685. Before: quantize - dequantize - custom_module
  686. After: quantize - custom_module
  687. \\ - dequantize
  688. """
  689. # expecting the input node for a custom module node to be a Node
  690. assert isinstance(prev_node, Node), \
  691. f"Expecting the argument for custom module node to be a Node, but got {prev_node}"
  692. if prev_node.op == "call_method" and prev_node.target == "dequantize":
  693. node.replace_input_with(prev_node, prev_node.args[0])
  694. # Remove the dequantize node if it doesn't have other users
  695. if len(prev_node.users) == 0:
  696. graph.erase_node(prev_node)
  697. def convert_custom_module(
  698. node: Node,
  699. graph: Graph,
  700. modules: Dict[str, torch.nn.Module],
  701. custom_module_class_mapping: Dict[QuantType, Dict[Type, Type]],
  702. statically_quantized_custom_module_nodes: Set[Node]):
  703. """ Converts an observed custom module to a quantized custom module based on
  704. `custom_module_class_mapping`
  705. For static quantization, we'll also remove the previous `dequantize` node and
  706. attach the observer node for output to the module, the observer for the node
  707. will be converted to a dequantize node instead of quantize-dequantize pairs
  708. later in the graph. In the end we would have a quantized custom module that
  709. has the same interface as a default quantized module in nn.quantized namespace,
  710. i.e. quantized input and quantized output.
  711. Args:
  712. - node: The call_module node of the observed standalone module
  713. - graph: The graph containing the node
  714. - modules: named_module of original model
  715. - custom_module_class_mapping: mapping from observed custom module class to
  716. quantized custom module class, used to swap custom modules
  717. - statically_quantized_custom_module_nodes: we'll add the custom module node
  718. if we find it is statically quantized, this will be used later when converting
  719. observers to quant/dequant node pairs, if the observed node is a statically
  720. quantized custom module nodes, we'll convert the observer to a dequantize node,
  721. this is to keep the interface the same as the default quantized module.
  722. TODO: maybe we want to redesign this part to align with reference model design
  723. as well, but there has been some discussions around the interface, so we can do
  724. it later.
  725. """
  726. observed_custom_module = modules[str(node.target)]
  727. maybe_obs = _maybe_get_observer_for_node(node, modules)
  728. qconfig = observed_custom_module.qconfig
  729. if activation_is_statically_quantized(qconfig):
  730. statically_quantized_custom_module_nodes.add(node)
  731. if _is_custom_module_lstm(node, modules):
  732. # The inputs are tuples in the form (input, (hidden0, hidden1))
  733. # Ensure all three input nodes are quantized
  734. assert (
  735. len(node.args) == 2 and
  736. isinstance(node.args[1], tuple) and
  737. len(node.args[1]) == 2
  738. )
  739. (inputs, (hidden0, hidden1)) = node.args # type: ignore[misc]
  740. assert isinstance(inputs, Node)
  741. assert isinstance(hidden0, Node)
  742. assert isinstance(hidden1, Node)
  743. _remove_previous_dequantize_in_custom_module(node, inputs, graph)
  744. _remove_previous_dequantize_in_custom_module(node, hidden0, graph)
  745. _remove_previous_dequantize_in_custom_module(node, hidden1, graph)
  746. else:
  747. # remove the previous dequant node to ensure the inputs are quantized
  748. arg = node.args[0]
  749. assert isinstance(arg, Node)
  750. _remove_previous_dequantize_in_custom_module(node, arg, graph)
  751. # absorb the following observer into the module conversion
  752. activation_post_process = _maybe_get_observer_for_node(node, modules)
  753. assert activation_post_process is not None
  754. observed_custom_module.activation_post_process = activation_post_process
  755. # swap the observed custom module to quantized custom module
  756. quantized_custom_module_class = get_swapped_custom_module_class(
  757. observed_custom_module, custom_module_class_mapping, qconfig)
  758. quantized_custom_module = \
  759. quantized_custom_module_class.from_observed(observed_custom_module)
  760. parent_name, name = _parent_name(node.target)
  761. setattr(modules[parent_name], name, quantized_custom_module)
  762. def convert(
  763. model: GraphModule, is_reference: bool = False,
  764. convert_custom_config: Union[ConvertCustomConfig, Dict[str, Any], None] = None,
  765. is_standalone_module: bool = False,
  766. _remove_qconfig_flag: bool = True,
  767. qconfig_mapping: Union[QConfigMapping, Dict[str, Any], None] = None,
  768. backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
  769. is_decomposed: bool = False) -> torch.nn.Module:
  770. """
  771. We will convert an observed model (a module with observer calls) to a reference
  772. quantized model, the rule is simple:
  773. 1. for each observer module call in the graph, we'll convert it to calls to
  774. quantize and dequantize functions based on the observer instance
  775. 2. for weighted operations like linear/conv, we need to convert them to reference
  776. quantized module, this requires us to know whether the dtype configured for the
  777. weight is supported in the backend, this is done in prepare step and the result
  778. is stored in observed_node_names, we can decide whether we need to swap the
  779. module based on this set
  780. Args:
  781. * `is_standalone_module`: when this flag is True, it means we are quantizing
  782. a submodule that is not inlined in parent module, and will be quantized
  783. separately as one unit.
  784. * `is_decomposed`: a boolean flag to indicate whether we want to use the
  785. quantize operator for decomposed quantized tensor
  786. (torch.ops.quantized_decomposed.quantize_per_tensor) or default/standalone
  787. quantized tensor (torch.quantize_per_tensor)
  788. Returns:
  789. a quantized standalone module, whether input/output is quantized is
  790. specified by prepare_custom_config, with
  791. input_quantized_idxs, output_quantized_idxs, please
  792. see docs for :func:`~torch.ao.quantization.prepare_fx` for details
  793. """
  794. if convert_custom_config is None:
  795. convert_custom_config = ConvertCustomConfig()
  796. if isinstance(convert_custom_config, Dict):
  797. warnings.warn(
  798. "Passing a convert_custom_config_dict to convert is deprecated and will not be supported "
  799. "in a future version. Please pass in a ConvertCustomConfig instead.")
  800. convert_custom_config = ConvertCustomConfig.from_dict(convert_custom_config)
  801. if isinstance(qconfig_mapping, Dict):
  802. warnings.warn(
  803. "Passing a QConfig dictionary to convert is deprecated and will not be supported "
  804. "in a future version. Please pass in a QConfigMapping instead.")
  805. qconfig_mapping = QConfigMapping.from_dict(qconfig_mapping) if qconfig_mapping else None
  806. qconfig_mapping = copy.deepcopy(qconfig_mapping)
  807. assert(qconfig_mapping is None or isinstance(qconfig_mapping, QConfigMapping))
  808. if isinstance(backend_config, Dict):
  809. warnings.warn(
  810. "Passing a backend_config_dict to prepare is deprecated and will not be supported "
  811. "in a future version. Please pass in a BackendConfig instead.")
  812. backend_config = BackendConfig.from_dict(backend_config)
  813. if backend_config is None:
  814. backend_config = get_native_backend_config()
  815. assert _is_observed_module(model), \
  816. 'incoming model must be produced by prepare_fx'
  817. observed_graph_module_attrs = model.meta["_observed_graph_module_attrs"]
  818. node_name_to_scope: Dict[str, Tuple[str, type]] = observed_graph_module_attrs.node_name_to_scope
  819. prepare_custom_config: PrepareCustomConfig = observed_graph_module_attrs.prepare_custom_config
  820. observed_node_names: Set[str] = observed_graph_module_attrs.observed_node_names
  821. node_name_to_qconfig: Dict[str, QConfigAny] = observed_graph_module_attrs.node_name_to_qconfig # type: ignore[assignment]
  822. # mapping from fully qualified module name to module instance
  823. # for example,
  824. # {
  825. # '': Model(...),
  826. # 'linear': Linear(...),
  827. # 'linear.weight_fake_quant': PerChannelMinMaxObserver(...),
  828. # }
  829. # We use remove_duplicate=False here because torch.cat uses
  830. # the same activation_post_process module instance but different names
  831. modules = dict(model.named_modules(remove_duplicate=False))
  832. # TODO refactor this code once we update the prepare logic to have additional information on
  833. # which graph nodes have been observed and share that with convert to decide which observers to ignore.
  834. if qconfig_mapping:
  835. prepare_qconfig_mapping: QConfigMapping = observed_graph_module_attrs.qconfig_mapping # type: ignore[assignment]
  836. modules_copy = copy.deepcopy(modules)
  837. if observed_graph_module_attrs.is_qat:
  838. _update_qconfig_for_qat(qconfig_mapping, backend_config)
  839. _update_qconfig_for_fusion(model, qconfig_mapping)
  840. _compare_prepare_convert_qconfig_mappings(prepare_qconfig_mapping, qconfig_mapping) # type: ignore[arg-type]
  841. convert_node_name_to_qconfig = _generate_node_name_to_qconfig(
  842. model, modules_copy, model.graph, qconfig_mapping, node_name_to_scope)
  843. # check the convert_node_name_to_qconfig generated and ensure that
  844. # all the values either match what was set in prepare node_name_to_qconfig
  845. # or are set to None in the convert_node_name_to_qconfig.
  846. for k, v in node_name_to_qconfig.items():
  847. assert k in convert_node_name_to_qconfig, 'Expected key {} in convert node_name_to_qconfig'.format(k)
  848. if convert_node_name_to_qconfig[k] is not None:
  849. assert qconfig_equals(v, convert_node_name_to_qconfig[k]), \
  850. "Expected k {} to have the same value in prepare and convert QConfigMappings, " \
  851. "but {} was updated to {}".format(k, v, convert_node_name_to_qconfig[k])
  852. node_name_to_qconfig = convert_node_name_to_qconfig
  853. custom_module_classes = get_custom_module_class_keys(convert_custom_config.observed_to_quantized_mapping)
  854. custom_module_class_mapping = convert_custom_config.observed_to_quantized_mapping
  855. if observed_graph_module_attrs.equalization_node_name_to_qconfig is not None:
  856. # If we want to do equalization then do the following:
  857. # Calculate the equalization scale, update the observers with the scaled
  858. # inputs, and scale the weight
  859. weight_eq_obs_dict = update_obs_for_equalization(model, modules)
  860. convert_eq_obs(model, modules, weight_eq_obs_dict)
  861. # always run weight observers in the top level forward method
  862. # for dynamic quant ops or weight only quant ops
  863. _run_weight_observers(model, backend_config)
  864. graph_inputs: List[str] = []
  865. for node in model.graph.nodes:
  866. if node.op == 'placeholder':
  867. graph_inputs.append(node.name)
  868. # additional state to override inputs to be quantized, if specified
  869. # by the user
  870. placeholder_node_seen_cnt = 0
  871. input_quantized_idxs: List[int] = prepare_custom_config.input_quantized_indexes
  872. output_quantized_idxs: List[int] = prepare_custom_config.output_quantized_indexes
  873. root_module_to_quantized_reference_module = get_root_module_to_quantized_reference_module(backend_config)
  874. # convert tuples so that it can work with isinstance(module, tuple_of_classes)
  875. root_module_classes = tuple(root_module_to_quantized_reference_module.keys())
  876. qat_module_classes = get_qat_module_classes(backend_config)
  877. fused_module_classes = get_fused_module_classes(backend_config)
  878. statically_quantized_custom_module_nodes: Set[Node] = set()
  879. for node in list(model.graph.nodes):
  880. if node.op == 'placeholder':
  881. cur_placeholder_node_idx = placeholder_node_seen_cnt
  882. placeholder_node_seen_cnt += 1
  883. if cur_placeholder_node_idx in input_quantized_idxs:
  884. # Inputs are assumed to be quantized if the user specifid the
  885. # input_quantized_idxs override.
  886. # we need to dequantize the inputs since all operators took
  887. # floating point inputs in reference quantized models
  888. _insert_dequantize_node(node, model.graph)
  889. elif node.op == "output":
  890. # If the argument is empty we don't need to do anything
  891. if len(output_quantized_idxs) == 0:
  892. continue
  893. # Result are kept quantized if the user specified the
  894. # output_quantized_idxs override.
  895. # Remove the dequantize operator for the node in the end if any
  896. return_node = node
  897. output = node.args[0]
  898. # outputs can be Node, list, tuple, dict, other cases are not supported yet
  899. if isinstance(output, (list, tuple)):
  900. for idx in output_quantized_idxs:
  901. _maybe_recursive_remove_dequantize(output[idx], return_node, model.graph)
  902. elif isinstance(output, (Node, dict)):
  903. # we treat dict as a single argument currently, but it can be extended
  904. # to support {"key": dtype} after we change output_quantized_idxs to
  905. # dict
  906. if 0 in output_quantized_idxs:
  907. _maybe_recursive_remove_dequantize(output, return_node, model.graph)
  908. else:
  909. warnings.warn(f"Unsupported node type for output_quantized_idxs: {type(output)}")
  910. elif node.op == "call_module":
  911. mod = _get_module(node, modules)
  912. assert mod is not None
  913. if _is_activation_post_process(mod):
  914. observed_node = node.args[0]
  915. if observed_node in statically_quantized_custom_module_nodes:
  916. _replace_observer_or_dequant_stub_with_dequantize_node(node, model.graph)
  917. else:
  918. if is_decomposed:
  919. _replace_observer_with_quantize_dequantize_node_decomposed(
  920. model, model.graph, node, modules, node_name_to_scope,
  921. node_name_to_qconfig)
  922. else:
  923. _replace_observer_with_quantize_dequantize_node(
  924. model, model.graph, node, modules, node_name_to_scope,
  925. node_name_to_qconfig)
  926. elif isinstance(mod, DeQuantStub):
  927. _replace_observer_or_dequant_stub_with_dequantize_node(node, model.graph)
  928. elif _is_observed_standalone_module(mod):
  929. convert_standalone_module(
  930. node, modules, model, is_reference, backend_config)
  931. # below this point `type_before_parametrizations` is used
  932. # instead of `type` to handle situations with fx quant + sparsity
  933. elif type_before_parametrizations(mod) in set(
  934. root_module_classes).union(qat_module_classes).union(fused_module_classes):
  935. # extra check for fused module classes to make sure they are fused module classes
  936. # of target modules
  937. if type_before_parametrizations(mod) in fused_module_classes and \
  938. type_before_parametrizations(mod[0]) not in root_module_classes: # type: ignore[index]
  939. continue
  940. convert_weighted_module(
  941. node, modules, observed_node_names, node_name_to_qconfig, backend_config, is_decomposed)
  942. elif type_before_parametrizations(mod) in custom_module_classes:
  943. convert_custom_module(
  944. node, model.graph, modules, custom_module_class_mapping,
  945. statically_quantized_custom_module_nodes)
  946. # remove deadcode after converting observers to quant/dequant ops
  947. model.graph.eliminate_dead_code()
  948. model = GraphModule(model, model.graph)
  949. # TODO: maybe move this to quantize_fx.py
  950. if not is_reference:
  951. model = lower_to_fbgemm(model, node_name_to_qconfig, node_name_to_scope)
  952. # TODO: this looks hacky, we want to check why we need this and see if we can
  953. # remove this
  954. # removes qconfig and activation_post_process modules
  955. if _remove_qconfig_flag:
  956. _remove_qconfig(model)
  957. model.delete_all_unused_submodules()
  958. model.meta.pop("_observed_graph_module_attrs", None)
  959. return model