utils.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. # mypy: allow-untyped-decorators
  2. # mypy: allow-untyped-defs
  3. import enum
  4. import operator
  5. from typing import Callable, Optional, Union
  6. import torch
  7. import torch.ao.nn.intrinsic.quantized as nniq
  8. import torch.ao.nn.quantized as nnq
  9. import torch.nn as nn
  10. from torch.ao.quantization import FakeQuantizeBase, ObserverBase
  11. from torch.ao.quantization.observer import _is_activation_post_process
  12. from torch.ao.quantization.utils import getattr_from_fqn
  13. from torch.fx import GraphModule
  14. from torch.fx.graph import Node
  15. from .ns_types import NSNodeTargetType, NSResultsType
  16. toq = torch.ops.quantized
  17. # TODO(future PR): consider deleting this enum and using the torch types
  18. # directly. This might be tricky because it is not a one to one mapping.
  19. class NodeInputOrOutputType(enum.Enum):
  20. FP32 = enum.auto() # torch.float
  21. INT8 = enum.auto() # torch.qint8 or torch.quint8
  22. FP16 = enum.auto() # torch.float16
  23. UNKNOWN = enum.auto() # we cannot determine input/output dtype
  24. # TODO(future PR): while these functions can support multiple dtypes,
  25. # for the purposes of numerical debugging we want to get the actual
  26. # dtype used in the model. We will likely need some kind of dtype
  27. # propagation to estimate this.
  28. FP32_OR_INT8 = enum.auto() # either torch.float or torch.quint8 or torch.qint8
  29. # TODO(future PRs): dynamic quant, fake quant, etc
  30. def get_node_first_input_and_output_type(
  31. node: Node,
  32. gm: GraphModule,
  33. logger_cls: Callable,
  34. node_type_to_io_type_map: dict[str, set[NSNodeTargetType]],
  35. ) -> tuple[NodeInputOrOutputType, NodeInputOrOutputType]:
  36. # TODO(future PR): clean this up
  37. FUNS_IO_TYPE_FP32 = node_type_to_io_type_map["funs_io_type_fp32"]
  38. FUNS_IO_TYPE_FP16 = node_type_to_io_type_map["funs_io_type_fp16"]
  39. FUNS_IO_TYPE_INT8 = node_type_to_io_type_map["funs_io_type_int8"]
  40. FUNS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["funs_io_type_fp32_or_int8"]
  41. MODS_IO_TYPE_FP32 = node_type_to_io_type_map["mods_io_type_fp32"]
  42. MODS_IO_TYPE_INT8 = node_type_to_io_type_map["mods_io_type_int8"]
  43. MODS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["mods_io_type_fp32_or_int8"]
  44. METHS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["meths_io_type_fp32_or_int8"]
  45. if node.op == "call_function":
  46. if node.target in FUNS_IO_TYPE_FP32:
  47. return (NodeInputOrOutputType.FP32, NodeInputOrOutputType.FP32)
  48. if node.target in FUNS_IO_TYPE_FP16:
  49. return (NodeInputOrOutputType.FP16, NodeInputOrOutputType.FP16)
  50. elif node.target in FUNS_IO_TYPE_INT8:
  51. return (NodeInputOrOutputType.INT8, NodeInputOrOutputType.INT8)
  52. elif node.target in FUNS_IO_TYPE_FP32_OR_INT8:
  53. first_arg = get_normalized_nth_input(node, gm, 0)
  54. assert isinstance(first_arg, Node)
  55. (
  56. _prev_node_input_type,
  57. prev_node_output_type,
  58. ) = get_node_first_input_and_output_type(
  59. first_arg, gm, logger_cls, node_type_to_io_type_map
  60. )
  61. return (prev_node_output_type, prev_node_output_type)
  62. else:
  63. return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
  64. elif node.op == "call_module":
  65. assert node.op == "call_module"
  66. assert isinstance(node.target, str)
  67. mod = getattr_from_fqn(gm, node.target)
  68. is_known_fp32_or_int8_input_module = any(
  69. isinstance(mod, target_type) # type: ignore[arg-type]
  70. for target_type in MODS_IO_TYPE_FP32_OR_INT8
  71. )
  72. if (
  73. isinstance(mod, (logger_cls, ObserverBase, FakeQuantizeBase)) # type: ignore[arg-type]
  74. or is_known_fp32_or_int8_input_module
  75. ):
  76. # A logger or observer's input and output type is the output
  77. # type of the preceding node.
  78. first_arg = get_normalized_nth_input(node, gm, 0)
  79. assert isinstance(first_arg, Node)
  80. (
  81. _prev_node_input_type,
  82. prev_node_output_type,
  83. ) = get_node_first_input_and_output_type(
  84. first_arg, gm, logger_cls, node_type_to_io_type_map
  85. )
  86. return (prev_node_output_type, prev_node_output_type)
  87. is_known_fp32_input_module = any(
  88. isinstance(mod, target_type) # type: ignore[arg-type]
  89. for target_type in MODS_IO_TYPE_FP32
  90. )
  91. is_known_int8_input_module = any(
  92. isinstance(mod, target_type) # type: ignore[arg-type]
  93. for target_type in MODS_IO_TYPE_INT8
  94. )
  95. if is_known_fp32_input_module:
  96. return (NodeInputOrOutputType.FP32, NodeInputOrOutputType.FP32)
  97. elif is_known_int8_input_module:
  98. return (NodeInputOrOutputType.INT8, NodeInputOrOutputType.INT8)
  99. else:
  100. return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
  101. elif node.op == "call_method":
  102. if node.target == "dequantize":
  103. # Dequantize is a special node because it allows multiple input types.
  104. # So, we look up the output type of the previous node and return that
  105. # as the input type of this node instance.
  106. prev_node = get_normalized_nth_input(node, gm, 0)
  107. assert isinstance(prev_node, Node)
  108. (
  109. _prev_node_input_type,
  110. prev_node_output_type,
  111. ) = get_node_first_input_and_output_type(
  112. prev_node, gm, logger_cls, node_type_to_io_type_map
  113. )
  114. return (prev_node_output_type, NodeInputOrOutputType.FP32)
  115. elif node.target == "to":
  116. # to is a special node because it allows multiple input types.
  117. # So, we look up the output type of the previous node and return that
  118. # as the input type of this node instance. We also look up the target
  119. # of to and return the correct output type.
  120. prev_node = get_normalized_nth_input(node, gm, 0)
  121. assert isinstance(prev_node, Node)
  122. (
  123. _prev_node_input_type,
  124. prev_node_output_type,
  125. ) = get_node_first_input_and_output_type(
  126. prev_node, gm, logger_cls, node_type_to_io_type_map
  127. )
  128. cur_node_dtype_target = get_normalized_nth_input(node, gm, 1)
  129. assert cur_node_dtype_target is torch.float16, (
  130. f"{cur_node_dtype_target} handling needs to be added"
  131. )
  132. return (prev_node_output_type, NodeInputOrOutputType.FP16)
  133. elif node.target in METHS_IO_TYPE_FP32_OR_INT8:
  134. first_arg = get_normalized_nth_input(node, gm, 0)
  135. assert isinstance(first_arg, Node)
  136. (
  137. _prev_node_input_type,
  138. prev_node_output_type,
  139. ) = get_node_first_input_and_output_type(
  140. first_arg, gm, logger_cls, node_type_to_io_type_map
  141. )
  142. return (prev_node_output_type, prev_node_output_type)
  143. return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
  144. else:
  145. return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
  146. def get_node_input_qparams(
  147. node: Node,
  148. gm: GraphModule,
  149. node_type_to_io_type_map: dict[str, set[NSNodeTargetType]],
  150. ) -> Optional[tuple[Union[torch.Tensor, float], Union[torch.Tensor, int]]]:
  151. """
  152. Returns the qparams (scale, zero_point) of the first input to `node`,
  153. if they can be inferred from the graph.
  154. """
  155. prev_node = get_normalized_nth_input(node, gm, 0)
  156. if not isinstance(prev_node, Node):
  157. return None
  158. MODS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["mods_io_type_fp32_or_int8"]
  159. def _get_scale_zp_from_function_args(node, gm, scale_arg_idx, zp_arg_idx):
  160. scale_node = get_normalized_nth_input(node, gm, scale_arg_idx)
  161. zp_node = get_normalized_nth_input(node, gm, zp_arg_idx)
  162. assert isinstance(scale_node, Node) and isinstance(scale_node.target, str)
  163. assert isinstance(zp_node, Node) and isinstance(zp_node.target, str)
  164. scale_obj = getattr_from_fqn(gm, scale_node.target)
  165. zp_obj = getattr_from_fqn(gm, zp_node.target)
  166. return (scale_obj, zp_obj)
  167. if prev_node.op == "call_function":
  168. # quantize - read the args directly
  169. if prev_node.target == torch.quantize_per_tensor:
  170. return _get_scale_zp_from_function_args(prev_node, gm, 1, 2)
  171. elif prev_node.target in (toq.add, toq.add_relu, toq.mul, toq.mul_relu):
  172. return _get_scale_zp_from_function_args(prev_node, gm, 2, 3)
  173. return None
  174. # TODO(future PR): handle more functionals
  175. # TODO(future PR): handle functional ops which inherit qparams from input
  176. elif prev_node.op == "call_module":
  177. # get type of the module
  178. assert isinstance(prev_node.target, str)
  179. module_obj = getattr_from_fqn(gm, prev_node.target)
  180. if isinstance(
  181. module_obj,
  182. (
  183. nnq.Linear,
  184. nnq.Conv1d,
  185. nnq.Conv2d,
  186. nniq.ConvReLU2d,
  187. nnq.Conv3d,
  188. nnq.BatchNorm2d,
  189. nnq.BatchNorm3d,
  190. nnq.ConvTranspose1d,
  191. nnq.ConvTranspose2d,
  192. nnq.ELU,
  193. nnq.GroupNorm,
  194. nnq.InstanceNorm1d,
  195. nnq.InstanceNorm2d,
  196. nnq.InstanceNorm3d,
  197. nnq.LayerNorm,
  198. nnq.Hardswish,
  199. nnq.LeakyReLU,
  200. nnq.ReLU6,
  201. nniq.BNReLU2d,
  202. nniq.BNReLU3d,
  203. nniq.ConvReLU1d,
  204. nniq.ConvReLU2d,
  205. nniq.ConvReLU3d,
  206. nniq.LinearReLU,
  207. ),
  208. ):
  209. return (module_obj.scale, module_obj.zero_point) # type: ignore[return-value]
  210. is_known_fp32_or_int8_input_module = any(
  211. isinstance(module_obj, target_type) # type: ignore[arg-type]
  212. for target_type in MODS_IO_TYPE_FP32_OR_INT8
  213. )
  214. if is_known_fp32_or_int8_input_module:
  215. return get_node_input_qparams(prev_node, gm, node_type_to_io_type_map)
  216. return None
  217. def return_first_non_observer_node(
  218. node: Node,
  219. gm: GraphModule,
  220. ) -> Node:
  221. """
  222. If node is not an observer, returns it. If node is an observer,
  223. navigates up the graph and returns the first parent which is not an
  224. observer. For example,
  225. graph: (node_non_obs), node = node_non_obs : returns node_non_obs
  226. graph: (node_non_obs -> obs0), node = obs0 : returns node_non_obs
  227. graph: (node_non_obs -> obs0 -> fq0), node = fq0 : returns node_non_obs
  228. """
  229. if node.op == "call_module":
  230. node_obj = getattr_from_fqn(gm, node.target) # type: ignore[arg-type]
  231. if _is_activation_post_process(node_obj):
  232. assert len(node.args) == 1
  233. assert isinstance(node.args[0], Node)
  234. node = node.args[0]
  235. # code duplication intended, not worth refactoring
  236. assert isinstance(node.target, str)
  237. node_obj = getattr_from_fqn(gm, node.target)
  238. if _is_activation_post_process(node_obj):
  239. assert len(node.args) == 1
  240. assert isinstance(node.args[0], Node)
  241. node = node.args[0]
  242. return node
  243. def get_number_of_non_param_args(
  244. node: Node,
  245. gm: GraphModule,
  246. ) -> int:
  247. """
  248. Assumes that all non-param args occur first. Returns the number of
  249. non-param args expected for a node. For example, for
  250. F.linear(x, weight, bias)
  251. Returns 1, because x is a non-param arg and weight and bias are params.
  252. For
  253. lstm_mod(x, hid)
  254. Returns 2, because both x and hid are non-param args.
  255. """
  256. if node.op == "call_module":
  257. node_obj = getattr_from_fqn(gm, node.target) # type: ignore[arg-type]
  258. if isinstance(node_obj, nn.LSTM):
  259. return 2
  260. # default is 1
  261. return 1
  262. def get_arg_indices_of_inputs_to_log(node: Node) -> list[int]:
  263. """
  264. Returns the indices of args of the node which we should attach
  265. loggers to, if input logging is enabled.
  266. For example,
  267. * for (x + y), returns [0, 1]
  268. * for (1 + y), returns [1]
  269. * for (x + 1), returns [0]
  270. * for (linear(x, w, b)) returns [0]
  271. * by default, returns [0]
  272. """
  273. if len(node.args) == 0:
  274. return []
  275. if node.op == "call_function" and (
  276. # TODO(future PR): use relationship map instead of hardcoding
  277. node.target in (torch.add, torch.ops.quantized.add, operator.add)
  278. or node.target in (torch.mul, torch.ops.quantized.mul, operator.mul)
  279. ):
  280. result = [i for i in range(2) if type(node.args[i]) == Node]
  281. return result
  282. return [0]
  283. def get_target_type_str(node: Node, gm: GraphModule) -> str:
  284. """
  285. Returns a string representation of the type of the function or module
  286. pointed to by this node, or '' for other node types.
  287. """
  288. target_type = ""
  289. if node.op in ("call_function", "call_method"):
  290. target_type = torch.typename(node.target)
  291. elif node.op == "call_module":
  292. assert isinstance(node.target, str)
  293. target_mod = getattr_from_fqn(gm, node.target)
  294. target_type = torch.typename(target_mod)
  295. return target_type
  296. def rekey_logger_info_on_node_name_of_model(
  297. results: NSResultsType,
  298. model_name: str,
  299. ) -> NSResultsType:
  300. """
  301. Rekeys the layer name of a results dictionary to use node names
  302. from `model_name`.
  303. For example, transforms
  304. {'base_op_1_0': {'node_output': {'model_a':
  305. [{'ref_node_name': 'linear1', ...}]}}}
  306. into
  307. {'linear1': {'node_output': {'model_a':
  308. [{'ref_node_name': 'linear1', ...}]}}}
  309. Note: we cannot use these node names directly because they are not
  310. guaranteed to be consistent across models. This is why we extract
  311. the results first and rekey afterwards.
  312. """
  313. new_results = {}
  314. for old_layer_name, result_type_to_results in results.items():
  315. new_layer_name = None
  316. for model_name_to_results in result_type_to_results.values():
  317. for cur_model_name, list_of_results in model_name_to_results.items():
  318. if cur_model_name == model_name:
  319. assert len(list_of_results)
  320. new_layer_name = list_of_results[0]["ref_node_name"]
  321. else:
  322. continue
  323. if new_layer_name is not None:
  324. new_results[new_layer_name] = result_type_to_results
  325. else:
  326. new_results[old_layer_name] = result_type_to_results
  327. return new_results
  328. def maybe_add_missing_fqns(results: NSResultsType) -> None:
  329. """
  330. If `fqn` entries are filled in for one of the models in `results`, copies
  331. them over to any models which do not have them filled out.
  332. A common use case benefitting from this is comparing a model prepared by
  333. quantization to a quantized model. In this case, the model prepared by
  334. quantization would have `fqn` entries, and the quantized model would not.
  335. """
  336. # Check in the first result to find any model with fqn entries defined.
  337. model_name_with_fqns = None
  338. for result_type_to_results in results.values():
  339. for model_name_to_results in result_type_to_results.values():
  340. for model_name, model_results in model_name_to_results.items():
  341. if len(model_results) > 0:
  342. if model_results[0]["fqn"] is not None:
  343. model_name_with_fqns = model_name
  344. break
  345. break
  346. break
  347. if model_name_with_fqns:
  348. for result_type_to_results in results.values():
  349. for model_name_to_results in result_type_to_results.values():
  350. ref_model_results = model_name_to_results[model_name_with_fqns]
  351. for model_name, model_results in model_name_to_results.items():
  352. if model_name == model_name_with_fqns:
  353. continue
  354. for i in range(len(model_results)):
  355. fqn = ref_model_results[i]["fqn"]
  356. model_results[i]["fqn"] = fqn
  357. def maybe_dequantize_first_two_tensor_args_and_handle_tuples(f):
  358. def inner(*args, **kwargs):
  359. a0, a1, *a_other = args
  360. if (isinstance(a0, tuple) and isinstance(a1, tuple)) or (
  361. isinstance(a0, list) and isinstance(a1, list)
  362. ):
  363. results = []
  364. for el0, el1 in zip(a0, a1):
  365. new_args = (el0, el1, *a_other)
  366. results.append(inner(*new_args, **kwargs))
  367. return results
  368. elif isinstance(a0, torch.Tensor) and isinstance(a1, torch.Tensor):
  369. if a0.is_quantized:
  370. a0 = a0.dequantize()
  371. if a1.is_quantized:
  372. a1 = a1.dequantize()
  373. # for the purposes of this util, only handle floats
  374. if a0.dtype != torch.float or a1.dtype != torch.float:
  375. return None
  376. new_args = (a0, a1, *a_other)
  377. return f(*new_args, **kwargs)
  378. return inner
  379. @maybe_dequantize_first_two_tensor_args_and_handle_tuples
  380. def compute_sqnr(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
  381. """
  382. Computes the SQNR between `x` and `y`.
  383. Args:
  384. x: Tensor or tuple of tensors
  385. y: Tensor or tuple of tensors
  386. Return:
  387. float or tuple of floats
  388. """
  389. Ps = torch.norm(x)
  390. Pn = torch.norm(x - y)
  391. return 20 * torch.log10(Ps / Pn)
  392. @maybe_dequantize_first_two_tensor_args_and_handle_tuples
  393. def compute_normalized_l2_error(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
  394. """
  395. Computes the normalized L2 error between `x` and `y`.
  396. Args:
  397. x: Tensor or tuple of tensors
  398. y: Tensor or tuple of tensors
  399. Return:
  400. float or tuple of floats
  401. """
  402. return torch.sqrt(((x - y) ** 2).sum() / (x**2).sum())
  403. @maybe_dequantize_first_two_tensor_args_and_handle_tuples
  404. def compute_cosine_similarity(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
  405. """
  406. Computes the cosine similarity between `x` and `y`.
  407. Args:
  408. x: Tensor or tuple of tensors
  409. y: Tensor or tuple of tensors
  410. Return:
  411. float or tuple of floats
  412. """
  413. # For convolutions, the shape of the quantized weight has one additional
  414. # dimension compared to the shape of the fp32 weight. Match the shapes
  415. # to enable cosine similarity comparison.
  416. x = x.reshape(1, -1)
  417. y = y.reshape(1, -1)
  418. return torch.nn.functional.cosine_similarity(x, y)
  419. def op_type_supports_shadowing(node: Node) -> bool:
  420. if node.op == "call_function":
  421. if node.target in (
  422. torch.add,
  423. torch.mul,
  424. operator.add,
  425. operator.mul,
  426. torch.cat,
  427. torch.stack,
  428. ):
  429. # shadowing for ops with multiple tensor inputs is not implemented yet
  430. return False
  431. return True
  432. def get_normalized_nth_input(node: Node, gm: GraphModule, idx: int) -> Node:
  433. """
  434. Given a node, gets the n'th input to that node, normalizing
  435. args and kwargs to the best of its ability.
  436. """
  437. try:
  438. norm_args_and_kwargs = node.normalized_arguments(
  439. gm, normalize_to_only_use_kwargs=True
  440. )
  441. if norm_args_and_kwargs is not None:
  442. norm_args, norm_kwargs = norm_args_and_kwargs
  443. assert len(norm_args) + len(norm_kwargs) > idx
  444. if idx < len(norm_args):
  445. return norm_args[idx]
  446. else:
  447. # note: in Python 3.7+ dicts are ordered
  448. return list(norm_kwargs.values())[idx]
  449. else:
  450. assert len(node.args) + len(node.kwargs) > idx
  451. if idx < len(node.args):
  452. return node.args[idx] # type: ignore[return-value]
  453. else:
  454. kwargs_idx = idx + len(node.args)
  455. return list(node.kwargs.values())[kwargs_idx] # type: ignore[return-value]
  456. except RuntimeError:
  457. # this RuntimeError happens when node argument normalization
  458. # requires typehints to proceed, such as for torch.add where
  459. # either the first, second or both arguments could be tensors
  460. assert len(node.args) + len(node.kwargs) > idx
  461. if idx < len(node.args):
  462. return node.args[idx] # type: ignore[return-value]
  463. else:
  464. kwargs_idx = idx + len(node.args)
  465. return list(node.kwargs.values())[kwargs_idx] # type: ignore[return-value]