_numeric_suite.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. import torch
  2. import torch.nn as nn
  3. import torch.ao.nn.quantized as nnq
  4. import torch.ao.nn.quantized.dynamic as nnqd
  5. from torch.ao.quantization import prepare
  6. from typing import Dict, List, Optional, Any, Union, Callable, Set
  7. from torch.ao.quantization.quantization_mappings import (
  8. get_default_compare_output_module_list,
  9. )
  10. NON_LEAF_MODULE_TO_ADD_OBSERVER_ALLOW_LIST = {
  11. nnqd.Linear,
  12. nnq.Linear,
  13. nnqd.LSTM,
  14. nn.LSTM,
  15. }
  16. def _find_match(
  17. str_list: Union[Dict[str, Any], List[str]], key_str: str,
  18. postfix: str,
  19. ) -> Optional[str]:
  20. split_str = key_str.split(".")
  21. if split_str[-1] == postfix:
  22. match_string = "".join(key_str.split(".")[0:-1])
  23. for s2 in str_list:
  24. pattern1 = "".join(s2.split(".")[0:-1])
  25. pattern2 = "".join(s2.split(".")[0:-2])
  26. if match_string == pattern1:
  27. return s2
  28. if match_string == pattern2:
  29. return s2
  30. # For matching "fc.weight" and "fc._packed_params._packed_params"
  31. if postfix == "_packed_params":
  32. match_string = "".join(key_str.split(".")[0:-2])
  33. if len(match_string) == 0:
  34. return None
  35. for s2 in str_list:
  36. pattern1 = "".join(s2.split(".")[0:-1])
  37. pattern2 = "".join(s2.split(".")[0:-2])
  38. if match_string == pattern1:
  39. return s2
  40. if match_string == pattern2:
  41. return s2
  42. return None
  43. else:
  44. return None
  45. def compare_weights(
  46. float_dict: Dict[str, Any], quantized_dict: Dict[str, Any]
  47. ) -> Dict[str, Dict[str, torch.Tensor]]:
  48. r"""Compare the weights of the float module with its corresponding quantized
  49. module. Return a dict with key corresponding to module names and each entry being
  50. a dictionary with two keys 'float' and 'quantized', containing the float and
  51. quantized weights. This dict can be used to compare and compute the quantization
  52. error of the weights of float and quantized models.
  53. Example usage::
  54. wt_compare_dict = compare_weights(
  55. float_model.state_dict(), qmodel.state_dict())
  56. for key in wt_compare_dict:
  57. print(
  58. key,
  59. compute_error(
  60. wt_compare_dict[key]['float'],
  61. wt_compare_dict[key]['quantized'].dequantize()
  62. )
  63. )
  64. Args:
  65. float_dict: state dict of the float model
  66. quantized_dict: state dict of the quantized model
  67. Return:
  68. weight_dict: dict with key corresponding to module names and each entry being
  69. a dictionary with two keys 'float' and 'quantized', containing the float and
  70. quantized weights
  71. """
  72. torch._C._log_api_usage_once("quantization_api._numeric_suite.compare_weights")
  73. weight_dict: Dict[str, Dict] = {}
  74. for key in quantized_dict:
  75. match_key = _find_match(float_dict, key, "weight")
  76. if match_key is not None:
  77. weight_dict[key] = {}
  78. weight_dict[key]["float"] = float_dict[match_key]
  79. weight_dict[key]["quantized"] = quantized_dict[key]
  80. continue
  81. # For matching "fc.weight" and "fc._packed_params._packed_params"
  82. match_key = _find_match(float_dict, key, "_packed_params")
  83. if match_key is not None:
  84. weight_dict[key] = {}
  85. weight_dict[key]["float"] = float_dict[match_key]
  86. weight_dict[key]["quantized"] = quantized_dict[key][0]
  87. # For LSTM
  88. split_str = key.split(".")
  89. if split_str[-1] == "param" and split_str[-3] == "_all_weight_values":
  90. layer = split_str[-2]
  91. module_name = ".".join(split_str[:-3])
  92. float_weight_ih_key = module_name + ".weight_ih_l" + layer
  93. float_weight_hh_key = module_name + ".weight_hh_l" + layer
  94. if float_weight_ih_key in float_dict and float_weight_hh_key in float_dict:
  95. weight_dict[key] = {}
  96. weight_dict[key]["float"] = float_dict[float_weight_ih_key]
  97. weight_dict[key]["quantized"] = (
  98. quantized_dict[key].__getstate__()[0][4][0].__getstate__()[0][0]
  99. )
  100. weight_dict[key]["float"] = float_dict[float_weight_hh_key]
  101. weight_dict[key]["quantized"] = (
  102. quantized_dict[key].__getstate__()[0][4][1].__getstate__()[0][0]
  103. )
  104. return weight_dict
  105. def _get_logger_dict_helper(
  106. mod: nn.Module, target_dict: Dict[str, Any],
  107. prefix: str = "",
  108. ) -> None:
  109. r"""This is the helper function for get_logger_dict
  110. Args:
  111. mod: module we want to save all logger stats
  112. prefix: prefix for the current module
  113. target_dict: the dictionary used to save all logger stats
  114. """
  115. def get_prefix(prefix):
  116. return prefix if prefix == "" else prefix + "."
  117. for name, child in mod.named_children():
  118. if isinstance(child, Logger):
  119. target_dict[get_prefix(prefix) + "stats"] = child.stats
  120. break
  121. for name, child in mod.named_children():
  122. module_prefix = get_prefix(prefix) + name if prefix else name
  123. _get_logger_dict_helper(child, target_dict, module_prefix)
  124. def get_logger_dict(mod: nn.Module, prefix: str = "") -> Dict[str, Dict]:
  125. r"""Traverse the modules and save all logger stats into target dict.
  126. This is mainly used for quantization accuracy debug.
  127. Type of loggers supported:
  128. ShadowLogger: used to log the outputs of the quantized module and its matching float shadow module,
  129. OutputLogger: used to log the outputs of the modules
  130. Args:
  131. mod: module we want to save all logger stats
  132. prefix: prefix for the current module
  133. Return:
  134. target_dict: the dictionary used to save all logger stats
  135. """
  136. torch._C._log_api_usage_once("quantization_api._numeric_suite.get_logger_dict")
  137. target_dict: Dict[str, Dict] = {}
  138. _get_logger_dict_helper(mod, target_dict, prefix)
  139. return target_dict
  140. class Logger(nn.Module):
  141. r"""Base class for stats logging
  142. """
  143. def __init__(self):
  144. super().__init__()
  145. self.stats = {}
  146. # We only insert observer if the op is quantized with static quantization,
  147. # which is identified by activation_observer.dtype == quint8. This is needed
  148. # when attaching Logger as observer for FX mode
  149. self.dtype = torch.quint8
  150. def forward(self, x):
  151. """
  152. """ # blank docblock to make autodoc happy
  153. pass
  154. class ShadowLogger(Logger):
  155. r"""Class used in Shadow module to record the outputs of the original and
  156. shadow modules.
  157. """
  158. def __init__(self):
  159. super().__init__()
  160. self.stats["float"] = []
  161. self.stats["quantized"] = []
  162. def forward(self, x, y):
  163. """
  164. """ # blank docblock to make autodoc happy
  165. if len(x) > 1:
  166. x = x[0]
  167. if len(y) > 1:
  168. y = y[0]
  169. self.stats["quantized"].append(x.detach())
  170. self.stats["float"].append(y.detach())
  171. class OutputLogger(Logger):
  172. r"""Class used to log the outputs of the module
  173. """
  174. def __init__(self):
  175. super().__init__()
  176. self.stats["tensor_val"] = []
  177. def forward(self, x):
  178. """
  179. """ # blank docblock to make autodoc happy
  180. self.stats["tensor_val"].append(x)
  181. return x
  182. def _convert_tuple_to_list(t: Any) -> Any:
  183. return [_convert_tuple_to_list(x) for x in t] if type(t) is tuple else t
  184. def _dequantize_tensor_list(t: Any) -> Any:
  185. return (
  186. [_dequantize_tensor_list(x) for x in t]
  187. if type(t) is list
  188. else t.dequantize()
  189. if t.is_quantized
  190. else t
  191. )
  192. class Shadow(nn.Module):
  193. r"""Shadow module attaches the float module to its matching quantized module
  194. as the shadow. Then it uses Logger module to process the outputs of both
  195. modules.
  196. Args:
  197. q_module: module quantized from float_module that we want to shadow
  198. float_module: float module used to shadow q_module
  199. logger_cls: type of logger used to process the outputs of q_module and
  200. float_module. ShadowLogger or custom loggers can be used.
  201. """
  202. def __init__(self, q_module, float_module, logger_cls):
  203. super().__init__()
  204. self.orig_module = q_module
  205. self.shadow_module = float_module
  206. self.dequant = nnq.DeQuantize()
  207. self.logger = logger_cls()
  208. def forward(self, *x) -> torch.Tensor:
  209. """
  210. """ # blank docblock to make autodoc happy
  211. xl = _convert_tuple_to_list(x)
  212. output = self.orig_module(*xl)
  213. xl_float = _dequantize_tensor_list(xl)
  214. shadow_output = self.shadow_module(*xl_float)
  215. self.logger(output, shadow_output)
  216. return output
  217. def add(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
  218. """
  219. """ # blank docblock to make autodoc happy
  220. output = self.orig_module.add(x, y)
  221. x = x.dequantize()
  222. y = y.dequantize()
  223. shadow_output = self.shadow_module.add(x, y)
  224. self.logger(output, shadow_output)
  225. return output
  226. def add_scalar(self, x: torch.Tensor, y: float) -> torch.Tensor:
  227. """
  228. """ # blank docblock to make autodoc happy
  229. output = self.orig_module.add_scalar(x, y)
  230. x = x.dequantize()
  231. shadow_output = self.shadow_module.add_scalar(x, y)
  232. self.logger(output, shadow_output)
  233. return output
  234. def mul(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
  235. """
  236. """ # blank docblock to make autodoc happy
  237. output = self.orig_module.mul(x, y)
  238. x = x.dequantize()
  239. y = y.dequantize()
  240. shadow_output = self.shadow_module.mul(x, y)
  241. self.logger(output, shadow_output)
  242. return output
  243. def mul_scalar(self, x: torch.Tensor, y: float) -> torch.Tensor:
  244. """
  245. """ # blank docblock to make autodoc happy
  246. output = self.orig_module.mul_scalar(x, y)
  247. x = x.dequantize()
  248. shadow_output = self.shadow_module.mul_scalar(x, y)
  249. self.logger(output, shadow_output)
  250. return output
  251. def cat(self, x: List[torch.Tensor], dim: int = 0) -> torch.Tensor:
  252. """
  253. """ # blank docblock to make autodoc happy
  254. output = self.orig_module.cat(x, dim)
  255. x = [y.dequantize() for y in x]
  256. shadow_output = self.shadow_module.cat(x, dim)
  257. self.logger(output, shadow_output)
  258. return output
  259. def add_relu(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
  260. """
  261. """ # blank docblock to make autodoc happy
  262. output = self.orig_module.add_relu(x, y)
  263. x = x.dequantize()
  264. y = y.dequantize()
  265. shadow_output = self.shadow_module.add_relu(x, y)
  266. self.logger(output, shadow_output)
  267. return output
  268. def prepare_model_with_stubs(
  269. float_module: nn.Module, q_module: nn.Module,
  270. module_swap_list: Set[type], logger_cls: Callable,
  271. ) -> None:
  272. r"""Prepare the model by attaching the float module to its matching quantized
  273. module as the shadow if the float module type is in module_swap_list.
  274. Example usage::
  275. prepare_model_with_stubs(float_model, q_model, module_swap_list, Logger)
  276. q_model(data)
  277. ob_dict = get_logger_dict(q_model)
  278. Args:
  279. float_module: float module used to generate the q_module
  280. q_module: module quantized from float_module
  281. module_swap_list: list of float module types to attach the shadow
  282. logger_cls: type of logger to be used in shadow module to process the outputs of
  283. quantized module and its float shadow module
  284. """
  285. torch._C._log_api_usage_once("quantization_api._numeric_suite.prepare_model_with_stubs")
  286. float_module_children = {}
  287. for name, mod in float_module.named_children():
  288. float_module_children[name] = mod
  289. reassign = {}
  290. for name, mod in q_module.named_children():
  291. if name not in float_module_children:
  292. continue
  293. float_mod = float_module_children[name]
  294. if type(float_mod) not in module_swap_list:
  295. prepare_model_with_stubs(float_mod, mod, module_swap_list, logger_cls)
  296. # Insert shadow module only if the module is not of the same type as
  297. # the floating point module
  298. if type(float_mod) in module_swap_list and not _is_identical_module_type(mod, float_mod):
  299. reassign[name] = Shadow(mod, float_mod, logger_cls)
  300. for key, value in reassign.items():
  301. q_module._modules[key] = value
  302. def _is_identical_module_type(mod1, mod2):
  303. # Compare if two modules have the same dtype
  304. mod1_module_types = [type(mod) for mod in mod1.modules()]
  305. mod2_module_types = [type(mod) for mod in mod2.modules()]
  306. return mod1_module_types == mod2_module_types
  307. def compare_model_stub(
  308. float_model: nn.Module, q_model: nn.Module, module_swap_list: Set[type],
  309. *data, logger_cls=ShadowLogger
  310. ) -> Dict[str, Dict]:
  311. r"""Compare quantized module in a model with its floating point counterpart,
  312. feeding both of them the same input. Return a dict with key corresponding to
  313. module names and each entry being a dictionary with two keys 'float' and
  314. 'quantized', containing the output tensors of quantized and its matching
  315. float shadow module. This dict can be used to compare and compute the module
  316. level quantization error.
  317. This function first call prepare_model_with_stubs() to swap the quantized
  318. module that we want to compare with the Shadow module, which takes quantized
  319. module, corresponding float module and logger as input, and creates a forward
  320. path inside to make the float module to shadow quantized module sharing the
  321. same input. The logger can be customizable, default logger is ShadowLogger
  322. and it will save the outputs of the quantized module and float module that
  323. can be used to compute the module level quantization error.
  324. Example usage::
  325. module_swap_list = [torchvision.models.quantization.resnet.QuantizableBasicBlock]
  326. ob_dict = compare_model_stub(float_model,qmodel,module_swap_list, data)
  327. for key in ob_dict:
  328. print(key, compute_error(ob_dict[key]['float'], ob_dict[key]['quantized'].dequantize()))
  329. Args:
  330. float_model: float model used to generate the q_model
  331. q_model: model quantized from float_model
  332. module_swap_list: list of float module types at which shadow modules will
  333. be attached.
  334. data: input data used to run the prepared q_model
  335. logger_cls: type of logger to be used in shadow module to process the outputs of
  336. quantized module and its float shadow module
  337. """
  338. torch._C._log_api_usage_once("quantization_api._numeric_suite.compare_model_stub")
  339. prepare_model_with_stubs(float_model, q_model, module_swap_list, logger_cls)
  340. q_model(*data)
  341. ob_dict = get_logger_dict(q_model)
  342. return ob_dict
  343. def get_matching_activations(
  344. float_module: nn.Module, q_module: nn.Module,
  345. ) -> Dict[str, Dict[str, torch.Tensor]]:
  346. r"""Find the matching activation between float and quantized modules.
  347. Args:
  348. float_module: float module used to generate the q_module
  349. q_module: module quantized from float_module
  350. Return:
  351. act_dict: dict with key corresponding to quantized module names and each
  352. entry being a dictionary with two keys 'float' and 'quantized', containing
  353. the matching float and quantized activations
  354. """
  355. torch._C._log_api_usage_once("quantization_api._numeric_suite.get_matching_activations")
  356. float_dict = get_logger_dict(float_module)
  357. quantized_dict = get_logger_dict(q_module)
  358. act_dict: Dict[str, Dict] = {}
  359. for key in quantized_dict:
  360. if len(quantized_dict[key]["tensor_val"]) == 0:
  361. continue
  362. match_key = _find_match(sorted(float_dict, reverse=True), key, "stats")
  363. if match_key is not None:
  364. act_dict[key] = {}
  365. act_dict[key]["float"] = float_dict[match_key]["tensor_val"]
  366. act_dict[key]["quantized"] = quantized_dict[key]["tensor_val"]
  367. return act_dict
  368. def prepare_model_outputs(
  369. float_module: nn.Module,
  370. q_module: nn.Module,
  371. logger_cls=OutputLogger,
  372. allow_list=None
  373. ) -> None:
  374. r"""Prepare the model by attaching the logger to both float module
  375. and quantized module if they are in the allow_list.
  376. Args:
  377. float_module: float module used to generate the q_module
  378. q_module: module quantized from float_module
  379. logger_cls: type of logger to be attached to float_module and q_module
  380. allow_list: list of module types to attach logger
  381. """
  382. torch._C._log_api_usage_once("quantization_api._numeric_suite.prepare_model_outputs")
  383. if allow_list is None:
  384. allow_list = get_default_compare_output_module_list()
  385. qconfig_debug = torch.ao.quantization.QConfig(activation=logger_cls, weight=None)
  386. float_module.qconfig = qconfig_debug # type: ignore[assignment]
  387. prepare(float_module, inplace=True, allow_list=allow_list, prepare_custom_config_dict={})
  388. q_module.qconfig = qconfig_debug # type: ignore[assignment]
  389. prepare(
  390. q_module,
  391. inplace=True,
  392. allow_list=allow_list,
  393. observer_non_leaf_module_list=NON_LEAF_MODULE_TO_ADD_OBSERVER_ALLOW_LIST,
  394. prepare_custom_config_dict={}
  395. )
  396. def compare_model_outputs(
  397. float_model: nn.Module,
  398. q_model: nn.Module,
  399. *data,
  400. logger_cls=OutputLogger,
  401. allow_list=None
  402. ) -> Dict[str, Dict[str, torch.Tensor]]:
  403. r"""Compare output activations between float and quantized models at
  404. corresponding locations for the same input. Return a dict with key corresponding
  405. to quantized module names and each entry being a dictionary with two keys
  406. 'float' and 'quantized', containing the activations of quantized model and
  407. float model at matching locations. This dict can be used to compare and
  408. compute the propagation quantization error.
  409. Example usage::
  410. act_compare_dict = compare_model_outputs(float_model, qmodel, data)
  411. for key in act_compare_dict:
  412. print(
  413. key,
  414. compute_error(
  415. act_compare_dict[key]['float'],
  416. act_compare_dict[key]['quantized'].dequantize()
  417. )
  418. )
  419. Args:
  420. float_model: float model used to generate the q_model
  421. q_model: model quantized from float_model
  422. data: input data used to run the prepared float_model and q_model
  423. logger_cls: type of logger to be attached to float_module and q_module
  424. allow_list: list of module types to attach logger
  425. Return:
  426. act_compare_dict: dict with key corresponding to quantized module names
  427. and each entry being a dictionary with two keys 'float' and 'quantized',
  428. containing the matching float and quantized activations
  429. """
  430. torch._C._log_api_usage_once("quantization_api._numeric_suite.compare_model_outputs")
  431. if allow_list is None:
  432. allow_list = get_default_compare_output_module_list()
  433. prepare_model_outputs(float_model, q_model, logger_cls, allow_list)
  434. float_model(*data)
  435. q_model(*data)
  436. act_compare_dict = get_matching_activations(float_model, q_model)
  437. return act_compare_dict