utils.py 36 KB

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