convert.py 59 KB

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