utils.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. # mypy: allow-untyped-defs
  2. import copy
  3. import functools
  4. import operator
  5. import warnings
  6. from collections import namedtuple
  7. from collections.abc import Callable
  8. from dataclasses import dataclass
  9. from typing import Any
  10. import torch
  11. import torch.nn as nn
  12. from torch.ao.quantization import QConfigAny, QuantType
  13. from torch.ao.quantization.backend_config import DTypeWithConstraints
  14. from torch.ao.quantization.fake_quantize import (
  15. FakeQuantizeBase,
  16. FixedQParamsFakeQuantize,
  17. )
  18. from torch.ao.quantization.observer import (
  19. _is_activation_post_process,
  20. FixedQParamsObserver,
  21. ObserverBase,
  22. )
  23. from torch.ao.quantization.qconfig import (
  24. float16_dynamic_qconfig,
  25. float16_static_qconfig,
  26. qconfig_equals,
  27. )
  28. from torch.ao.quantization.qconfig_mapping import QConfigMapping
  29. from torch.ao.quantization.stubs import DeQuantStub
  30. from torch.ao.quantization.utils import (
  31. _assert_and_get_unique_device,
  32. activation_is_statically_quantized,
  33. )
  34. from torch.fx import GraphModule, map_arg
  35. from torch.fx.graph import Graph, Node
  36. # importing the lib so that the quantized_decomposed ops are registered
  37. from ._decomposed import quantized_decomposed_lib # noqa: F401
  38. from .custom_config import PrepareCustomConfig
  39. # TODO: revisit this list. Many helper methods shouldn't be public
  40. __all__ = [
  41. "all_node_args_except_first",
  42. "all_node_args_have_no_tensors",
  43. "assert_and_get_unique_device",
  44. "collect_producer_nodes",
  45. "create_getattr_from_value",
  46. "create_node_from_old_node_preserve_meta",
  47. "EMPTY_ARG_DICT",
  48. "get_custom_module_class_keys",
  49. "get_linear_prepack_op_for_dtype",
  50. "get_new_attr_name_with_prefix",
  51. "get_non_observable_arg_indexes_and_types",
  52. "get_qconv_prepack_op",
  53. "get_skipped_module_name_and_classes",
  54. "graph_module_from_producer_nodes",
  55. "maybe_get_next_module",
  56. "NodeInfo",
  57. "node_arg_is_bias",
  58. "node_arg_is_weight",
  59. "NON_OBSERVABLE_ARG_DICT",
  60. "NON_QUANTIZABLE_WEIGHT_OPS",
  61. "return_arg_list",
  62. "ObservedGraphModuleAttrs",
  63. ]
  64. NON_QUANTIZABLE_WEIGHT_OPS = {
  65. torch.nn.functional.layer_norm,
  66. torch.nn.functional.group_norm,
  67. torch.nn.functional.instance_norm,
  68. }
  69. @dataclass
  70. class ObservedGraphModuleAttrs:
  71. node_name_to_qconfig: dict[str, QConfigAny]
  72. node_name_to_scope: dict[str, tuple[str, type]]
  73. prepare_custom_config: PrepareCustomConfig
  74. equalization_node_name_to_qconfig: dict[str, Any]
  75. qconfig_mapping: QConfigMapping
  76. is_qat: bool
  77. observed_node_names: set[str]
  78. is_observed_standalone_module: bool = False
  79. standalone_module_input_quantized_idxs: list[int] | None = None
  80. standalone_module_output_quantized_idxs: list[int] | None = None
  81. def node_arg_is_weight(node: Node, arg: Any) -> bool:
  82. """Returns if node arg is weight"""
  83. weight_index = None
  84. if "target_dtype_info" in node.meta:
  85. weight_index = node.meta["target_dtype_info"].get("weight_index", None)
  86. if (
  87. weight_index is not None
  88. and weight_index < len(node.args)
  89. and node.args[weight_index] is arg
  90. ):
  91. return True
  92. return node.kwargs.get("weight") is arg
  93. def node_arg_is_bias(node: Node, arg: Any) -> bool:
  94. """Returns if node arg is bias"""
  95. bias_index = None
  96. if "target_dtype_info" in node.meta:
  97. bias_index = node.meta["target_dtype_info"].get("bias_index", None)
  98. if (
  99. bias_index is not None
  100. and bias_index < len(node.args)
  101. and node.args[bias_index] is arg
  102. ):
  103. return True
  104. return node.kwargs.get("bias") is arg
  105. def get_custom_module_class_keys(
  106. custom_module_mapping: dict[QuantType, dict[type, type]],
  107. ) -> list[Any]:
  108. r"""Get all the unique custom module keys in the custom config dict
  109. e.g.
  110. Input:
  111. {
  112. QuantType.STATIC: {
  113. CustomModule1: ObservedCustomModule
  114. },
  115. QuantType.DYNAMIC: {
  116. CustomModule2: DynamicObservedCustomModule
  117. },
  118. QuantType.WEIGHT_ONLY: {
  119. CustomModule3: WeightOnlyObservedCustomModule
  120. },
  121. }
  122. Output:
  123. # extract the keys across all inner STATIC, DYNAMIC, and WEIGHT_ONLY dicts
  124. [CustomModule1, CustomModule2, CustomModule3]
  125. """
  126. # using set to dedup
  127. float_custom_module_classes: set[Any] = set()
  128. for quant_mode in [QuantType.STATIC, QuantType.DYNAMIC, QuantType.WEIGHT_ONLY]:
  129. quant_mode_custom_module_config = custom_module_mapping.get(quant_mode, {})
  130. quant_mode_custom_module_classes = set(quant_mode_custom_module_config.keys())
  131. float_custom_module_classes |= quant_mode_custom_module_classes
  132. return list(float_custom_module_classes)
  133. def get_linear_prepack_op_for_dtype(dtype):
  134. if dtype == torch.float16:
  135. return torch.ops.quantized.linear_prepack_fp16
  136. elif dtype == torch.qint8:
  137. return torch.ops.quantized.linear_prepack
  138. else:
  139. raise Exception("can't get linear prepack op for dtype:", dtype) # noqa: TRY002
  140. def get_qconv_prepack_op(conv_op: Callable) -> Callable:
  141. prepack_ops = {
  142. torch.nn.functional.conv1d: torch.ops.quantized.conv1d_prepack,
  143. torch.nn.functional.conv2d: torch.ops.quantized.conv2d_prepack,
  144. torch.nn.functional.conv3d: torch.ops.quantized.conv3d_prepack,
  145. torch.nn.functional.conv_transpose1d: torch.ops.quantized.conv_transpose1d_prepack,
  146. torch.nn.functional.conv_transpose2d: torch.ops.quantized.conv_transpose2d_prepack,
  147. torch.nn.functional.conv_transpose3d: torch.ops.quantized.conv_transpose3d_prepack,
  148. }
  149. prepack_op = prepack_ops.get(conv_op)
  150. if prepack_op is None:
  151. raise AssertionError(f"Didn't find prepack op for {conv_op}")
  152. return prepack_op
  153. # Returns a function that can get a new attribute name for module with given
  154. # prefix, for example,
  155. # >> get_new_observer_name = get_new_attr_name_with_prefix('_observer')
  156. # >> new_name = get_new_observer_name(module)
  157. # new_name will be an unused attribute name on module, e.g. `_observer_1`
  158. def get_new_attr_name_with_prefix(prefix: str) -> Callable:
  159. prefix = prefix.replace(".", "_")
  160. def get_new_attr_name(module: torch.nn.Module):
  161. def get_attr_name(i: int):
  162. return prefix + str(i)
  163. i = 0
  164. attr_name = get_attr_name(i)
  165. while hasattr(module, attr_name):
  166. i += 1
  167. attr_name = get_attr_name(i)
  168. return attr_name
  169. return get_new_attr_name
  170. def collect_producer_nodes(node: Node) -> list[Node] | None:
  171. r"""Starting from a target node, trace back until we hit input or
  172. getattr node. This is used to extract the chain of operators
  173. starting from getattr to the target node, for example::
  174. def forward(self, x):
  175. observed = self.observer(self.weight)
  176. return F.linear(x, observed)
  177. collect_producer_nodes(observed) will either return a list of nodes that
  178. produces the observed node or None if we can't extract a self contained
  179. graph without free variables(inputs of the forward function).
  180. """
  181. nodes = [node]
  182. frontier = [node]
  183. while frontier:
  184. node = frontier.pop()
  185. all_args = list(node.args) + list(node.kwargs.values())
  186. for arg in all_args:
  187. if not isinstance(arg, Node):
  188. continue
  189. if arg.op == "placeholder":
  190. # hit input, can't fold in this case
  191. return None
  192. nodes.append(arg)
  193. if not (arg.op == "call_function" and arg.target is getattr):
  194. frontier.append(arg)
  195. return nodes
  196. def graph_module_from_producer_nodes(
  197. root: GraphModule, producer_nodes: list[Node]
  198. ) -> GraphModule:
  199. r"""Construct a graph module from extracted producer nodes
  200. from `collect_producer_nodes` function
  201. Args:
  202. root: the root module for the original graph
  203. producer_nodes: a list of nodes we use to construct the graph
  204. Return:
  205. A graph module constructed from the producer nodes
  206. """
  207. if len(producer_nodes) == 0:
  208. raise AssertionError("list of producer nodes can not be empty")
  209. # since we traced back from node to getattr
  210. producer_nodes.reverse()
  211. graph = Graph()
  212. env: dict[Any, Any] = {}
  213. def load_arg(a):
  214. return map_arg(a, lambda node: env[node])
  215. for producer_node in producer_nodes:
  216. env[producer_node] = graph.node_copy(producer_node, load_arg)
  217. graph.output(load_arg(producer_nodes[-1]))
  218. graph_module = GraphModule(root, graph)
  219. return graph_module
  220. # TODO: delete
  221. @functools.cache
  222. def assert_and_get_unique_device(module: torch.nn.Module) -> Any:
  223. """
  224. Returns the unique device for a module, or None if no device is found.
  225. Throws an error if multiple devices are detected.
  226. """
  227. return _assert_and_get_unique_device(module)
  228. def create_getattr_from_value(
  229. module: torch.nn.Module,
  230. graph: Graph,
  231. prefix: str,
  232. value: Any,
  233. device: torch.device | None = None,
  234. ) -> Node:
  235. """
  236. Given a value of any type, creates a getattr node corresponding to the value and
  237. registers the value as a buffer to the module.
  238. """
  239. get_new_attr_name = get_new_attr_name_with_prefix(prefix)
  240. attr_name = get_new_attr_name(module)
  241. if device is None:
  242. device = assert_and_get_unique_device(module)
  243. new_value = (
  244. value.detach().clone()
  245. if isinstance(value, torch.Tensor)
  246. else torch.tensor(value, device=device)
  247. )
  248. module.register_buffer(attr_name, new_value)
  249. # Create get_attr with value
  250. attr_node = graph.create_node("get_attr", attr_name)
  251. return attr_node
  252. def all_node_args_have_no_tensors(
  253. node: Node, modules: dict[str, torch.nn.Module], cache: dict[Node, bool]
  254. ) -> bool:
  255. """
  256. If we know for sure that all of this node's args have no
  257. tensors (are primitives), return True. If we either
  258. find a tensor or are not sure, return False. Note: this
  259. function is not exact.
  260. """
  261. if cache and node in cache:
  262. return cache[node]
  263. result = False # will be overwritten
  264. if not isinstance(node, Node):
  265. result = True
  266. elif node.op == "placeholder":
  267. result = False
  268. elif node.op == "call_module":
  269. if not isinstance(node.target, str):
  270. raise AssertionError("node.target must be a string for call_module nodes")
  271. if _is_activation_post_process(modules[node.target]):
  272. result = all_node_args_have_no_tensors(node.args[0], modules, cache) # type: ignore[arg-type]
  273. elif node.op == "call_module":
  274. result = False
  275. elif node.op == "call_function" and node.target is operator.getitem:
  276. result = all_node_args_have_no_tensors(node.args[0], modules, cache) # type: ignore[arg-type]
  277. elif node.op == "get_attr":
  278. result = False
  279. elif node.target is getattr and node.args[1] in ["ndim", "shape"]:
  280. # x1 = x0.ndim
  281. result = True
  282. elif node.op == "call_method" and node.target == "size":
  283. # x1 = x0.size(0)
  284. result = True
  285. else:
  286. found_one_tensor = False
  287. for arg in node.args:
  288. if isinstance(arg, list):
  289. for list_el in arg:
  290. if isinstance(list_el, Node):
  291. this_list_el_args_have_no_tensors = (
  292. all_node_args_have_no_tensors(list_el, modules, cache)
  293. )
  294. found_one_tensor = found_one_tensor or (
  295. not this_list_el_args_have_no_tensors
  296. )
  297. # If found_one_tensor is True, there is no point in
  298. # recursing further as the end result will always
  299. # be True.
  300. # TODO(future PR): remove this entire function and
  301. # change to dtype inference without recursion.
  302. if found_one_tensor:
  303. result = not found_one_tensor
  304. if cache:
  305. cache[node] = result
  306. return result
  307. elif isinstance(arg, int):
  308. pass
  309. else:
  310. if isinstance(arg, Node):
  311. this_arg_args_have_no_tensors = all_node_args_have_no_tensors(
  312. arg, modules, cache
  313. )
  314. found_one_tensor = found_one_tensor or (
  315. not this_arg_args_have_no_tensors
  316. )
  317. # If found_one_tensor is True, there is no point in
  318. # recursing further as the end result will always
  319. # be True.
  320. # TODO(future PR): remove this entire function and
  321. # change to dtype inference without recursion.
  322. if found_one_tensor:
  323. result = not found_one_tensor
  324. if cache:
  325. cache[node] = result
  326. return result
  327. else:
  328. found_one_tensor = True
  329. result = not found_one_tensor
  330. if cache:
  331. cache[node] = result
  332. return result
  333. def all_node_args_except_first(node: Node) -> list[int]:
  334. """
  335. Returns all node arg indices after first
  336. """
  337. return list(range(1, len(node.args)))
  338. def return_arg_list(arg_indices: list[int]) -> Callable[[Node], list[int]]:
  339. """
  340. Constructs a function that takes a node as arg and returns the arg_indices
  341. that are valid for node.args
  342. """
  343. def arg_indices_func(node: Node) -> list[int]:
  344. return [i for i in arg_indices if i < len(node.args)]
  345. return arg_indices_func
  346. NodeInfo = namedtuple("NodeInfo", "op target")
  347. # this dict identifies which indices of a node are non tensors
  348. # so that they can be propagated correctly since inserting observers
  349. # for them would cause errors
  350. NON_OBSERVABLE_ARG_DICT: dict[
  351. NodeInfo, dict[type | torch.dtype, Callable[[Node], list[int]]]
  352. ] = {
  353. NodeInfo("call_method", "masked_fill"): {
  354. torch.bool: return_arg_list([1]),
  355. float: return_arg_list([2]),
  356. },
  357. NodeInfo("call_method", "permute"): {int: all_node_args_except_first},
  358. NodeInfo("call_method", "repeat"): {int: all_node_args_except_first},
  359. NodeInfo("call_method", "reshape"): {int: all_node_args_except_first},
  360. NodeInfo("call_method", "size"): {int: return_arg_list([1])},
  361. NodeInfo("call_method", "transpose"): {int: all_node_args_except_first},
  362. NodeInfo("call_method", torch.transpose): {int: all_node_args_except_first},
  363. NodeInfo("call_method", "unsqueeze"): {int: return_arg_list([1])},
  364. NodeInfo("call_method", "unsqueeze_"): {int: return_arg_list([1])},
  365. NodeInfo("call_method", torch.unsqueeze): {int: return_arg_list([1])},
  366. NodeInfo("call_method", "view"): {int: all_node_args_except_first},
  367. }
  368. EMPTY_ARG_DICT: dict[type | torch.dtype, Callable[[Node], list[int]]] = {}
  369. def get_non_observable_arg_indexes_and_types(
  370. node: Node,
  371. ) -> dict[type | torch.dtype, Callable[[Node], list[int]]]:
  372. """
  373. Returns a dict with of non float tensor types as keys and values which correspond to a
  374. function to retrieve the list (which takes the node as an argument)
  375. """
  376. info = NodeInfo(node.op, node.target)
  377. return NON_OBSERVABLE_ARG_DICT.get(info, EMPTY_ARG_DICT)
  378. def maybe_get_next_module(
  379. node: Node,
  380. modules: dict[str, nn.Module],
  381. target_module_type: type[nn.Module] | None = None,
  382. target_functional_type: Any = None,
  383. ) -> Node | None:
  384. """Gets the next module that matches what is needed in
  385. is_target_module_type if it exists
  386. Args:
  387. node: The node whose users we want to look at
  388. target_module_type: Module type that we want to check
  389. target_functional_type: Functional type that we want to check
  390. """
  391. for user in node.users:
  392. if (
  393. user.op == "call_module"
  394. and target_module_type is not None
  395. and isinstance(modules[str(user.target)], target_module_type)
  396. ):
  397. return user
  398. elif (
  399. user.op == "call_function"
  400. and target_functional_type is not None
  401. and user.target == target_functional_type
  402. ):
  403. return user
  404. return None
  405. def create_node_from_old_node_preserve_meta(
  406. quantized_graph: Graph,
  407. create_node_args: tuple[Any, ...],
  408. old_node: Node,
  409. ) -> Node:
  410. """
  411. Creates `new_node` and copies the necessary metadata to it from `old_node`.
  412. """
  413. new_node = quantized_graph.create_node(*create_node_args)
  414. new_node.stack_trace = old_node.stack_trace
  415. return new_node
  416. def get_skipped_module_name_and_classes(
  417. prepare_custom_config: PrepareCustomConfig, is_standalone_module: bool
  418. ) -> tuple[list[str], list[type[Any]]]:
  419. skipped_module_names = copy.copy(prepare_custom_config.non_traceable_module_names)
  420. skipped_module_classes = copy.copy(
  421. prepare_custom_config.non_traceable_module_classes
  422. )
  423. if not is_standalone_module:
  424. # standalone module and custom module config are applied in top level module
  425. skipped_module_names += list(
  426. prepare_custom_config.standalone_module_names.keys()
  427. )
  428. skipped_module_classes += list(
  429. prepare_custom_config.standalone_module_classes.keys()
  430. )
  431. skipped_module_classes += get_custom_module_class_keys(
  432. prepare_custom_config.float_to_observed_mapping
  433. )
  434. return skipped_module_names, skipped_module_classes
  435. def _is_custom_module_lstm(
  436. node: Node,
  437. named_modules: dict[str, torch.nn.Module],
  438. qconfig: QConfigAny = None,
  439. # QuantizeHandler, but we cannot include the type here due to circular imports
  440. qhandler: Any | None = None,
  441. ) -> bool:
  442. """
  443. Return whether this refers to the custom module LSTM flow.
  444. """
  445. mod = _get_module(node, named_modules)
  446. if qconfig is not None and qhandler is not None:
  447. if not isinstance(
  448. qhandler, torch.ao.quantization.fx.quantize_handler.QuantizeHandler
  449. ): # type: ignore[attr-defined]
  450. raise AssertionError("qhandler must be a QuantizeHandler when provided")
  451. return (
  452. isinstance(mod, torch.nn.LSTM)
  453. and activation_is_statically_quantized(qconfig)
  454. and qhandler.is_custom_module()
  455. )
  456. else:
  457. return isinstance(mod, torch.ao.nn.quantizable.LSTM)
  458. def _is_custom_module_mha(
  459. node: Node,
  460. named_modules: dict[str, torch.nn.Module],
  461. qconfig: QConfigAny = None,
  462. # QuantizeHandler, but we cannot include the type here due to circular imports
  463. qhandler: Any | None = None,
  464. ) -> bool:
  465. """
  466. Return whether this refers to the custom module MultiheadAttention flow.
  467. """
  468. mod = _get_module(node, named_modules)
  469. if qconfig is not None and qhandler is not None:
  470. if not isinstance(
  471. qhandler, torch.ao.quantization.fx.quantize_handler.QuantizeHandler
  472. ): # type: ignore[attr-defined]
  473. raise AssertionError("qhandler must be a QuantizeHandler when provided")
  474. return (
  475. isinstance(mod, torch.nn.MultiheadAttention)
  476. and activation_is_statically_quantized(qconfig)
  477. and qhandler.is_custom_module()
  478. )
  479. else:
  480. return isinstance(mod, torch.ao.nn.quantizable.MultiheadAttention)
  481. def _get_module(
  482. node: Node, named_modules: dict[str, torch.nn.Module]
  483. ) -> torch.nn.Module | None:
  484. """
  485. If `node` refers to a call_module node, return the module, else None.
  486. """
  487. if node.op == "call_module" and str(node.target) in named_modules:
  488. return named_modules[str(node.target)]
  489. else:
  490. return None
  491. def _insert_dequant_stub(
  492. node: Node,
  493. model: torch.nn.Module,
  494. named_modules: dict[str, torch.nn.Module],
  495. graph: Graph,
  496. ) -> Node:
  497. """
  498. Attach a `DeQuantStub` to the model and create a node that calls this
  499. `DeQuantStub` on the output of `node`, similar to how observers are inserted.
  500. """
  501. prefix = "dequant_stub_"
  502. get_new_dequant_stub_name = get_new_attr_name_with_prefix(prefix)
  503. dequant_stub_name = get_new_dequant_stub_name(model)
  504. dequant_stub = DeQuantStub()
  505. setattr(model, dequant_stub_name, dequant_stub)
  506. named_modules[dequant_stub_name] = dequant_stub
  507. with graph.inserting_after(node):
  508. return graph.call_module(dequant_stub_name, (node,))
  509. def _insert_dequant_stubs_for_custom_module_lstm_output(
  510. node: Node,
  511. model: torch.nn.Module,
  512. named_modules: dict[str, torch.nn.Module],
  513. graph: Graph,
  514. ) -> Node:
  515. """
  516. Insert DeQuantStubs after each internal output node of custom module LSTM.
  517. Custom module LSTM outputs are nested tuples of the structure (output, (hidden0, hidden1)),
  518. Since we cannot dequantize a tuple as a whole, we must first break down the tuple into its
  519. components through `getitem`. This function transforms the graph as follows:
  520. (1) Split the LSTM node into (output, (hidden0, hidden1))
  521. (2) Insert a DeQuantStub after each internal node
  522. (3) Recombine the DeQuantStubs into the same structure as before
  523. (4) Reroute all consumers of the original LSTM node and its sub-nodes
  524. (e.g. lstm[0])
  525. Before:
  526. lstm_output
  527. |
  528. v
  529. original_user(s)
  530. After:
  531. lstm_output
  532. / \\
  533. / (getitem) \\
  534. / \\
  535. v v
  536. output hidden
  537. | / \\
  538. (DeQuantStub) (getitem)
  539. | / \\
  540. v v v
  541. output_dq hidden0 hidden1
  542. | | |
  543. | (DeQuantStub) (DeQuantStub)
  544. | | |
  545. | v v
  546. | hidden0_dq hidden1_dq
  547. | \\ /
  548. | (tuple)
  549. | \\ /
  550. | v v
  551. | hidden_dq
  552. \\ /
  553. \\ (tuple) /
  554. v v
  555. lstm_output_dq
  556. |
  557. v
  558. original_user(s)
  559. For step (4), reroute all users of the original LSTM node(s) as follows:
  560. lstm_output -> lstm_output_dq
  561. lstm_output[0] -> output_dq
  562. lstm_output[1] -> hidden_dq
  563. lstm_output[1][0] -> hidden0_dq
  564. lstm_output[1][1] -> hidden1_dq
  565. Return the node `lstm_output_dq`.
  566. """
  567. # (1) Split the LSTM node into (output, (hidden0, hidden1))
  568. # (2) Insert a DeQuantStub after each internal node
  569. with graph.inserting_after(node):
  570. output = graph.call_function(operator.getitem, (node, 0))
  571. output_dq = _insert_dequant_stub(output, model, named_modules, graph)
  572. with graph.inserting_after(output_dq):
  573. hidden = graph.call_function(operator.getitem, (node, 1))
  574. with graph.inserting_after(hidden):
  575. hidden0 = graph.call_function(operator.getitem, (hidden, 0))
  576. hidden0_dq = _insert_dequant_stub(hidden0, model, named_modules, graph)
  577. with graph.inserting_after(hidden0_dq):
  578. hidden1 = graph.call_function(operator.getitem, (hidden, 1))
  579. hidden1_dq = _insert_dequant_stub(hidden1, model, named_modules, graph)
  580. # (3) Recombine the DeQuantStubs into the same structure as before
  581. with graph.inserting_after(hidden1_dq):
  582. hidden_dq = graph.call_function(tuple, ([hidden0_dq, hidden1_dq],))
  583. with graph.inserting_after(hidden_dq):
  584. lstm_output_dq = graph.call_function(tuple, ([output_dq, hidden_dq],))
  585. # (4) Reroute all consumers of the original LSTM node and its sub-nodes
  586. for user in list(node.users.keys()):
  587. if user != output and user != hidden:
  588. user.replace_input_with(node, lstm_output_dq)
  589. # The getitem and tuple nodes we added here may interfere with reference quantized
  590. # pattern matching, so we need to redirect the consumers of internal nodes to the
  591. # corresponding nodes with DeQuantStubs (e.g. lstm_output_dq[0] -> output_dq) attached,
  592. # in order to preserve reference patterns like "dequantize - consumer - quantize".
  593. _reroute_tuple_getitem_pattern(graph)
  594. return lstm_output_dq
  595. def _maybe_get_custom_module_lstm_from_node_arg(
  596. arg: Node,
  597. named_modules: dict[str, torch.nn.Module],
  598. ) -> Node | None:
  599. """
  600. Given an argument of a node, if the argument refers to the path through which the node
  601. is a consumer of custom module LSTM, return the custom module LSTM node, or None otherwise.
  602. This is used to determine whether a node is a consumer of custom module LSTM, and, if so,
  603. skip inserting input observers for this node. This is because custom module LSTM produces
  604. quantized outputs, so inserting an input observer for the consumer of custom module LSTM
  605. would unnecessarily quantize the outputs again.
  606. lstm -> consumer
  607. In practice, however, custom module LSTM outputs a tuple (output, (hidden0, hidden1)) with
  608. DeQuantStubs attached to each internal node (see `_insert_dequant_stubs_for_custom_module_lstm_output`).
  609. This tuple can be consumed in one of four ways:
  610. lstm -> getitem -> DeQuantStub -> consumer # consume lstm[0]
  611. lstm -> getitem -> getitem -> DeQuantStub -> tuple -> consumer # consume lstm[1]
  612. lstm -> getitem -> getitem -> DeQuantStub -> consumer # consume lstm[1][0] or lstm[1][1]
  613. lstm -> getitem -> DeQuantStub -> tuple -> consumer # consume lstm
  614. Thus, we must match against the above patterns instead of simply checking the parent node
  615. to determine whether this node is a consumer of a custom module LSTM.
  616. """
  617. def match_dq(a):
  618. return isinstance(_get_module(a, named_modules), DeQuantStub)
  619. def match_lstm(a):
  620. return _is_custom_module_lstm(a, named_modules)
  621. def match_getitem(a):
  622. return a.op == "call_function" and a.target is operator.getitem
  623. def match_tuple(a):
  624. return a.op == "call_function" and a.target is tuple
  625. def _match_pattern(match_pattern: list[Callable]) -> Node | None:
  626. """
  627. Traverse up the graph and match the args one by one.
  628. If there is a match, return the last matched node, or None otherwise.
  629. """
  630. a = arg
  631. # pyrefly: ignore [bad-assignment]
  632. for i, match in enumerate(match_pattern):
  633. if not match(a):
  634. return None
  635. # Match next arg, for tuple the arg is a tuple of a list, e.g. ([dq_1, other_node],)
  636. if i < len(match_pattern) - 1:
  637. if match is match_tuple:
  638. a = a.args[0][0] # type: ignore[assignment,index]
  639. else:
  640. a = a.args[0] # type: ignore[assignment]
  641. # pyrefly: ignore [bad-return]
  642. return a
  643. all_match_patterns = [
  644. [match_dq, match_getitem, match_lstm],
  645. [match_tuple, match_dq, match_getitem, match_getitem, match_lstm],
  646. [match_dq, match_getitem, match_getitem, match_lstm],
  647. [match_tuple, match_dq, match_getitem, match_lstm],
  648. ]
  649. for p in all_match_patterns:
  650. matched_node = _match_pattern(p)
  651. if matched_node is not None:
  652. return matched_node
  653. return None
  654. def _reroute_tuple_getitem_pattern(graph: Graph):
  655. """
  656. Search for patterns where N consecutive `tuple` call_function nodes are followed by
  657. N consecutive `getitem` call_function nodes that are "reverses" of the `tuple` nodes.
  658. If we find this pattern, reroute the consumers of the last `getitem` to skip these
  659. N `tuple` and `getitem` nodes.
  660. Before:
  661. a b c
  662. | \\ /
  663. \\ tuple
  664. \\ /
  665. tuple
  666. |
  667. getitem(1)
  668. |
  669. getitem(0)
  670. |
  671. d
  672. After:
  673. b
  674. |
  675. d
  676. """
  677. def find_patterns(
  678. node: Node,
  679. index_stack: list[int],
  680. current_pattern: list[Node],
  681. matched_patterns: list[list[Node]],
  682. seen: set[tuple[Node, tuple[int, ...]]],
  683. ):
  684. """
  685. Traverse the graph recursively to match for the N-tuple - N-getitem patterns,
  686. starting at the given node.
  687. We use a stack to keep track of the expected `getitem` indices, since these are
  688. reversed from the `tuple` indices. In the above example, the stack after
  689. (b -> tuple -> tuple) will be [0, 1], which will be popped by getitem(1) first
  690. and then by getitem(0).
  691. TODO: traverse upwards from the output and handle the case when tuple is not a
  692. separate node, e.g. graph.call_function(operator.getitem, args=(a, (b, c)))
  693. """
  694. if len(index_stack) == 0 and len(current_pattern) > 0:
  695. matched_patterns.append(copy.copy(current_pattern))
  696. current_pattern.clear()
  697. # Avoid duplicating work
  698. state = (node, tuple(index_stack))
  699. if state in seen:
  700. return
  701. seen.add(state)
  702. # Iterate through users of this node to find tuple/getitem nodes to match
  703. for user in node.users:
  704. if user.op == "call_function" and user.target is tuple:
  705. for i, user_arg in enumerate(user.args[0]): # type: ignore[arg-type]
  706. if user_arg == node:
  707. index_stack.append(i)
  708. current_pattern.append(user)
  709. find_patterns(
  710. user, index_stack, current_pattern, matched_patterns, seen
  711. )
  712. elif user.op == "call_function" and user.target is operator.getitem:
  713. if len(index_stack) > 0:
  714. if user.args[1] == index_stack[-1]:
  715. index_stack.pop()
  716. current_pattern.append(user)
  717. find_patterns(
  718. user, index_stack, current_pattern, matched_patterns, seen
  719. )
  720. return matched_patterns
  721. # Collect all matched patterns
  722. matched_patterns: list[list[Node]] = []
  723. seen: set[tuple[Node, tuple[int, ...]]] = set() # (node, index_stack)
  724. for node in graph.nodes:
  725. find_patterns(node, [], [], matched_patterns, seen)
  726. # For each pattern, redirect all consumers of the last getitem node to the correct input
  727. # of the first tuple node
  728. for pattern in matched_patterns:
  729. first_tuple = pattern[0]
  730. last_getitem = pattern[-1]
  731. if not (first_tuple.op == "call_function" and first_tuple.target is tuple):
  732. raise AssertionError(
  733. "first tuple node must be a call_function with target tuple"
  734. )
  735. if not (
  736. last_getitem.op == "call_function"
  737. and last_getitem.target is operator.getitem
  738. ):
  739. raise AssertionError(
  740. "last getitem node must be a call_function with target operator.getitem"
  741. )
  742. last_getitem_index = last_getitem.args[1]
  743. new_input = first_tuple.args[0][last_getitem_index] # type: ignore[index]
  744. for user in list(last_getitem.users.keys()):
  745. user.replace_input_with(last_getitem, new_input) # type: ignore[arg-type]
  746. def _get_observer_from_activation_post_process(
  747. activation_post_process: ObserverBase | FakeQuantizeBase,
  748. ) -> ObserverBase:
  749. """
  750. If `activation_post_process` is an observer, return the observer.
  751. If `activation_post_process` is a fake quantize, return the internal observer.
  752. """
  753. if isinstance(activation_post_process, ObserverBase):
  754. return activation_post_process
  755. else:
  756. if not isinstance(activation_post_process, FakeQuantizeBase):
  757. raise AssertionError(
  758. "activation_post_process must be an ObserverBase or FakeQuantizeBase"
  759. )
  760. return activation_post_process.activation_post_process # type: ignore[return-value]
  761. def _qconfig_satisfies_dtype_config_constraints(
  762. qconfig: QConfigAny,
  763. dtype_with_constraints: DTypeWithConstraints,
  764. is_activation: bool = True,
  765. ) -> bool:
  766. """
  767. Return whether `qconfig` satisfies the following constraints from the backend,
  768. specified through the activation and weight DTypeWithConstraints.
  769. 1. QConfig specified a quantization range that falls within the backend's, if any
  770. 2. QConfig specified a min scale value that is >= the backend's, if any
  771. 3. QConfig specified a FixedQParamsObserver or FixedQParamsFakeQuantize that has
  772. scale and zero point that match the backend's, if any
  773. If `is_activation` is True, we check `qconfig.activation`, else we check `qconfig.weight`.
  774. If `qconfig` or `dtype_with_constraints.dtype` is None, or the dtypes do not match, return True.
  775. """
  776. # TODO: log warnings only when the user enabled a debug flag
  777. def _activation_post_process_satisfies_dtype_config_constraints(
  778. activation_post_process: ObserverBase | FakeQuantizeBase,
  779. dtype_with_constraints: DTypeWithConstraints,
  780. debug_string: str,
  781. ) -> bool:
  782. observer = _get_observer_from_activation_post_process(activation_post_process)
  783. app_quant_min = getattr(observer, "quant_min", None)
  784. app_quant_max = getattr(observer, "quant_max", None)
  785. # TODO: for now, just use the existing eps value as scale_min. In the future, we should
  786. # resolve the differences between the two, either by renaming eps or some other way
  787. app_scale_min = getattr(observer, "eps", None)
  788. backend_quant_min = dtype_with_constraints.quant_min_lower_bound
  789. backend_quant_max = dtype_with_constraints.quant_max_upper_bound
  790. backend_scale_min = dtype_with_constraints.scale_min_lower_bound
  791. backend_scale_exact_match = dtype_with_constraints.scale_exact_match
  792. backend_zero_point_exact_match = dtype_with_constraints.zero_point_exact_match
  793. # check quantization ranges
  794. if backend_quant_min is not None and backend_quant_max is not None:
  795. if app_quant_min is None or app_quant_max is None:
  796. warnings.warn(
  797. f"QConfig {debug_string} must specify 'quant_min' and 'quant_max', ignoring {qconfig}",
  798. stacklevel=2,
  799. )
  800. return False
  801. elif app_quant_min < backend_quant_min or app_quant_max > backend_quant_max:
  802. warnings.warn(
  803. f"QConfig {debug_string} quantization range must fall within the backend's:\n"
  804. f"QConfig range = ({app_quant_min}, {app_quant_max}), "
  805. f"BackendConfig range = ({backend_quant_min}, {backend_quant_max}), "
  806. f"ignoring {qconfig}",
  807. stacklevel=2,
  808. )
  809. return False
  810. # check scale min
  811. if backend_scale_min is not None:
  812. if app_scale_min is None:
  813. warnings.warn(
  814. f"QConfig {debug_string} must specify 'eps', ignoring {qconfig}",
  815. stacklevel=2,
  816. )
  817. return False
  818. if app_scale_min < backend_scale_min:
  819. warnings.warn(
  820. f"QConfig {debug_string} eps ({app_scale_min}) must be greater than or equal to "
  821. f"the backend's min scale value ({backend_scale_min}), ignoring {qconfig}",
  822. stacklevel=2,
  823. )
  824. return False
  825. # check fixed scale and zero point
  826. if (
  827. backend_scale_exact_match is not None
  828. and backend_zero_point_exact_match is not None
  829. ):
  830. # For tests only, accept the following qconfigs for now
  831. # TODO: handle fp16 qconfigs properly
  832. for accepted_qconfig in [float16_static_qconfig, float16_dynamic_qconfig]:
  833. if qconfig_equals(qconfig, accepted_qconfig):
  834. return True
  835. suggestion_str = (
  836. "Please use torch.ao.quantization.get_default_qconfig_mapping or "
  837. "torch.ao.quantization.get_default_qat_qconfig_mapping. Example:\n"
  838. ' qconfig_mapping = get_default_qconfig_mapping("fbgemm")\n'
  839. " model = prepare_fx(model, qconfig_mapping, example_inputs)"
  840. )
  841. if not isinstance(
  842. activation_post_process, FixedQParamsObserver
  843. ) and not isinstance(activation_post_process, FixedQParamsFakeQuantize):
  844. warnings.warn(
  845. f"QConfig must specify a FixedQParamsObserver or a FixedQParamsFakeQuantize "
  846. f"for fixed qparams ops, ignoring {qconfig}.\n{suggestion_str}",
  847. stacklevel=2,
  848. )
  849. return False
  850. if (
  851. observer.scale != backend_scale_exact_match
  852. or observer.zero_point != backend_zero_point_exact_match
  853. ):
  854. warnings.warn(
  855. f"QConfig fixed scale ({observer.scale}) and zero point ({observer.zero_point}) "
  856. f"do not match the backend's ({backend_scale_exact_match} and {backend_zero_point_exact_match}), "
  857. f"ignoring {qconfig}.\n{suggestion_str}",
  858. stacklevel=2,
  859. )
  860. return False
  861. return True
  862. if qconfig is None or dtype_with_constraints.dtype is None:
  863. return True
  864. activation_post_process_ctr = (
  865. qconfig.activation if is_activation else qconfig.weight
  866. )
  867. debug_string = "activation" if is_activation else "weight"
  868. satisfies_constraints = True
  869. if activation_post_process_ctr is not None:
  870. activation_post_process = activation_post_process_ctr()
  871. if not _is_activation_post_process(activation_post_process):
  872. raise AssertionError(
  873. "activation_post_process must be an activation post process"
  874. )
  875. # If dtypes don't match, don't check the activation_post_process and return True early
  876. if activation_post_process.dtype != dtype_with_constraints.dtype:
  877. return True
  878. satisfies_constraints = (
  879. _activation_post_process_satisfies_dtype_config_constraints(
  880. activation_post_process, dtype_with_constraints, debug_string
  881. )
  882. )
  883. return satisfies_constraints