utils.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. # mypy: allow-untyped-defs
  2. """
  3. Utils shared by different modes of quantization (eager/graph)
  4. """
  5. import functools
  6. import warnings
  7. from collections import OrderedDict
  8. from collections.abc import Callable
  9. from inspect import getfullargspec, signature
  10. from typing import Any
  11. from typing_extensions import TypeAliasType
  12. import torch
  13. from torch.ao.quantization.quant_type import QuantType
  14. from torch.fx import Node
  15. from torch.nn.utils.parametrize import is_parametrized
  16. NodePattern = TypeAliasType(
  17. "NodePattern", tuple[Node, Node] | tuple[Node, tuple[Node, Node]] | Any
  18. )
  19. # This is the Quantizer class instance from torch/quantization/fx/quantize.py.
  20. # Define separately to prevent circular imports.
  21. # TODO(future PR): improve this.
  22. # make this public once fixed (can't be public as is because setting the module directly
  23. # doesn't work)
  24. QuantizerCls = Any
  25. # Type for fusion patterns, it can be more complicated than the following actually,
  26. # see pattern.md for docs
  27. # TODO: not sure if typing supports recursive data types
  28. Pattern = TypeAliasType(
  29. "Pattern",
  30. Callable
  31. | tuple[Callable, Callable]
  32. | tuple[Callable, tuple[Callable, Callable]]
  33. | Any,
  34. )
  35. # TODO: maybe rename this to MatchInputNode
  36. class MatchAllNode:
  37. """A node pattern that matches all nodes, used in defining
  38. fusion patterns in FX Graph Mode Quantization
  39. """
  40. module_type_list = {
  41. torch.nn.ReLU,
  42. torch.nn.ReLU6,
  43. torch.nn.AdaptiveAvgPool1d,
  44. torch.nn.AdaptiveAvgPool2d,
  45. torch.nn.AdaptiveAvgPool3d,
  46. torch.nn.AvgPool1d,
  47. torch.nn.AvgPool2d,
  48. torch.nn.AvgPool3d,
  49. torch.nn.MaxPool1d,
  50. torch.nn.MaxPool2d,
  51. torch.nn.MaxPool3d,
  52. torch.nn.Identity,
  53. torch.nn.Hardsigmoid,
  54. torch.nn.Sigmoid,
  55. torch.nn.Tanh,
  56. }
  57. func_list = {
  58. torch.nn.functional.adaptive_avg_pool1d,
  59. torch.nn.functional.adaptive_avg_pool2d,
  60. torch.nn.functional.adaptive_avg_pool3d,
  61. torch.nn.functional.elu,
  62. torch.nn.functional.hardswish,
  63. torch.nn.functional.instance_norm,
  64. torch.nn.functional.layer_norm,
  65. torch.nn.functional.leaky_relu,
  66. torch.nn.functional.silu,
  67. torch.nn.functional.mish,
  68. torch.nn.functional.dropout,
  69. torch.nn.functional.max_pool1d,
  70. torch.nn.functional.max_pool2d,
  71. torch.nn.functional.max_pool3d,
  72. torch.nn.functional.relu,
  73. torch.nn.functional.hardtanh,
  74. torch.nn.functional.hardtanh_,
  75. torch.nn.functional.hardsigmoid,
  76. torch.nn.functional.sigmoid,
  77. torch.transpose,
  78. torch.repeat_interleave,
  79. torch.sigmoid,
  80. torch.squeeze,
  81. torch.stack,
  82. torch.sum,
  83. torch.tanh,
  84. torch.unsqueeze,
  85. torch.cat,
  86. }
  87. method_list = {
  88. torch.mean,
  89. "relu",
  90. "relu_",
  91. "contiguous",
  92. "detach",
  93. "detach_",
  94. "hardsigmoid",
  95. "hardsigmoid_",
  96. "permute",
  97. "repeat",
  98. "repeat_interleave",
  99. "reshape",
  100. "resize_",
  101. "shape",
  102. "sigmoid",
  103. "sigmoid_",
  104. "size",
  105. "squeeze",
  106. "squeeze_",
  107. "tanh",
  108. "tanh_",
  109. "transpose",
  110. "unsqueeze",
  111. "unsqueeze_",
  112. "view",
  113. }
  114. # TODO: not used now, remove
  115. def check_node(node, modules):
  116. # TODO: reuse is_fixed_qparam_node after we move this function to _lower_to_native_backend.py
  117. is_call_function = node.op == "call_function" and node.target in func_list
  118. is_call_method = node.op == "call_method" and node.target in method_list
  119. is_call_module = (
  120. node.op == "call_module" and type(modules[str(node.target)]) in module_type_list
  121. )
  122. return is_call_function, is_call_method, is_call_module
  123. def get_combined_dict(default_dict, additional_dict):
  124. """
  125. Combines two dictionaries.
  126. This function takes two dictionaries as input and returns a new dictionary
  127. that contains all the key-value pairs from both input dictionaries.
  128. If there are any duplicate keys in the `additional_dict`, the values
  129. from the `additional_dict` will overwrite those in the `default_dict`.
  130. Args:
  131. default_dict (dict): The main dictionary that will be used as the base
  132. additional_dict (dict): The dictionary used to update `default_dict`
  133. Returns:
  134. dict: The resulting dictionary
  135. Example:
  136. >>> x = dict(a=1, b=1)
  137. >>> y = dict(b=2, c=3)
  138. >>> get_combined_dict(x, y)
  139. {'a': 1, 'b': 2, 'c': 3}
  140. """
  141. d = default_dict.copy()
  142. d.update(additional_dict)
  143. return d
  144. def is_per_tensor(qscheme):
  145. return qscheme == torch.per_tensor_affine or qscheme == torch.per_tensor_symmetric
  146. def is_per_channel(qscheme):
  147. return qscheme in [
  148. torch.per_channel_affine,
  149. torch.per_channel_affine_float_qparams,
  150. torch.per_channel_symmetric,
  151. ]
  152. def getattr_from_fqn(obj: Any, fqn: str) -> Any:
  153. """
  154. Given an obj and a fqn such as "foo.bar.baz", returns gm.foo.bar.baz.
  155. """
  156. return functools.reduce(getattr, fqn.split("."), obj)
  157. def to_underlying_dtype(qdtype):
  158. DTYPE_MAPPING = {
  159. torch.quint8: torch.uint8,
  160. torch.qint8: torch.int8,
  161. torch.qint32: torch.int32,
  162. torch.quint4x2: torch.uint8,
  163. torch.quint2x4: torch.uint8,
  164. torch.uint8: torch.uint8,
  165. torch.int8: torch.int8,
  166. torch.uint16: torch.uint16,
  167. torch.int16: torch.int16,
  168. torch.int32: torch.int32,
  169. torch.float8_e5m2: torch.float8_e5m2,
  170. torch.float8_e4m3fn: torch.float8_e4m3fn,
  171. }
  172. if qdtype not in DTYPE_MAPPING:
  173. raise AssertionError("Unsupported dtype: " + str(qdtype))
  174. return DTYPE_MAPPING[qdtype]
  175. def get_qparam_dict(observer_or_fake_quant):
  176. from torch.ao.quantization.observer import PlaceholderObserver
  177. qscheme = getattr(observer_or_fake_quant, "qscheme", None)
  178. dtype = observer_or_fake_quant.dtype
  179. qparams = {"qscheme": qscheme, "dtype": dtype}
  180. if not qscheme or isinstance(observer_or_fake_quant, PlaceholderObserver):
  181. return {"qscheme": None, "dtype": dtype}
  182. if is_per_tensor(qscheme):
  183. qscheme = torch.per_tensor_affine
  184. elif is_per_channel(qscheme):
  185. # change symmetric to affine since we do not have symmetric
  186. # quantized Tensor
  187. if qscheme == torch.per_channel_symmetric:
  188. qscheme = torch.per_channel_affine
  189. qparams["axis"] = observer_or_fake_quant.ch_axis
  190. else:
  191. raise RuntimeError(f"Unrecognized qscheme: {qscheme}")
  192. # update qscheme, since we don't have symmetric quant qscheme
  193. # in quantized Tensor
  194. qparams["qscheme"] = qscheme
  195. scale, zero_point = observer_or_fake_quant.calculate_qparams()
  196. qparams["scale"] = scale
  197. qparams["zero_point"] = zero_point
  198. if hasattr(observer_or_fake_quant, "quant_min"):
  199. qparams["quant_min"] = observer_or_fake_quant.quant_min
  200. if hasattr(observer_or_fake_quant, "quant_max"):
  201. qparams["quant_max"] = observer_or_fake_quant.quant_max
  202. return qparams
  203. def get_swapped_custom_module_class(
  204. custom_module, custom_module_class_mapping, qconfig
  205. ):
  206. """Get the observed/quantized custom module class that we need
  207. to swap `custom_module` to
  208. Input:
  209. custom_module: input, can be an instance of either a float or observed custom module
  210. custom_module_class_mapping: the float to observed or observed to quantized custom module class mapping
  211. qconfig: qconfig configured for the custom module
  212. Output:
  213. corresponding observed/quantized custom module class for input custom module instance
  214. """
  215. quant_type = get_quant_type(qconfig)
  216. class_mapping = custom_module_class_mapping.get(quant_type, {})
  217. if type(custom_module) not in class_mapping:
  218. raise AssertionError(
  219. "did not find corresponding observed "
  220. f"module class for {type(custom_module)} in mapping: {class_mapping}"
  221. )
  222. return class_mapping[type(custom_module)]
  223. def activation_dtype(qconfig):
  224. if qconfig is None:
  225. raise AssertionError("qconfig must be provided to determine activation dtype")
  226. activation = qconfig.activation()
  227. return activation.dtype
  228. def weight_dtype(qconfig):
  229. if qconfig is None:
  230. raise AssertionError("qconfig must be provided to determine weight dtype")
  231. weight = qconfig.weight()
  232. return weight.dtype
  233. def activation_is_statically_quantized(qconfig):
  234. """Given a qconfig, decide if the activation needs to be
  235. quantized or not, this includes quantizing to quint8, qint8 and qint32 and float16
  236. """
  237. return activation_dtype(qconfig) in [
  238. torch.quint8,
  239. torch.qint8,
  240. torch.qint32,
  241. torch.float16,
  242. torch.uint8,
  243. torch.int8,
  244. torch.int16,
  245. torch.int32,
  246. torch.float8_e5m2,
  247. torch.float8_e4m3fn,
  248. ] and (not activation_is_dynamically_quantized(qconfig))
  249. def activation_is_dynamically_quantized(qconfig):
  250. """Given a qconfig, decide if the activation needs to be
  251. dynamically quantized or not, this includes dynamically quantizing to
  252. quint8, qint8 and float16
  253. """
  254. _activation_dtype, _, activation_is_dynamic = get_qconfig_dtypes(qconfig)
  255. return activation_is_dynamic
  256. def activation_is_int8_quantized(qconfig):
  257. """Given a qconfig, decide if the activation needs to be
  258. quantized to int8 or not, this includes quantizing to quint8, qint8
  259. """
  260. return activation_dtype(qconfig) in [
  261. torch.quint8,
  262. torch.qint8,
  263. torch.uint8,
  264. torch.int8,
  265. ]
  266. def activation_is_int32_quantized(qconfig):
  267. """Given a qconfig, decide if the activation needs to be
  268. quantized to int32 or not
  269. """
  270. return activation_dtype(qconfig) in [torch.qint32, torch.int32]
  271. def weight_is_quantized(qconfig):
  272. """Given a qconfig, decide if the weight needs to be
  273. quantized or not
  274. """
  275. return weight_dtype(qconfig) in [
  276. torch.quint8,
  277. torch.qint8,
  278. torch.float16,
  279. torch.quint4x2,
  280. torch.uint8,
  281. torch.int8,
  282. torch.int16,
  283. torch.int32,
  284. torch.float8_e5m2,
  285. torch.float8_e4m3fn,
  286. ]
  287. def weight_is_statically_quantized(qconfig):
  288. """Given a qconfig, decide if the weight needs to be statically
  289. quantized or not
  290. """
  291. return weight_dtype(qconfig) in [torch.quint8, torch.qint8, torch.uint8, torch.int8]
  292. def op_is_int8_dynamically_quantized(qconfig) -> bool:
  293. """Given a qconfig, returns True if this op is using int8 dynamic
  294. quantization
  295. """
  296. activation_dtype, weight_dtype, activation_is_dynamic = get_qconfig_dtypes(qconfig)
  297. return (
  298. activation_dtype in [torch.quint8, torch.uint8]
  299. and
  300. # for now, the lines below assume fbgemm or qnnpack
  301. weight_dtype in [torch.qint8, torch.int8]
  302. and activation_is_dynamic
  303. )
  304. def get_qconfig_dtypes(qconfig):
  305. r"""returns the qconfig tuple for qconfig:
  306. (activation_dtype, weight_dtype, activation_is_dynamic)
  307. """
  308. if qconfig is None:
  309. raise AssertionError("qconfig must be provided to extract dtypes")
  310. activation = qconfig.activation()
  311. weight = qconfig.weight()
  312. act_is_dynamic = getattr(activation, "is_dynamic", False)
  313. return (activation.dtype, weight.dtype, act_is_dynamic)
  314. def get_quant_type(qconfig):
  315. if qconfig is None:
  316. raise AssertionError("qconfig must be provided to determine quant type")
  317. activation = qconfig.activation()
  318. weight = qconfig.weight()
  319. static_dtypes = [
  320. torch.quint8,
  321. torch.qint8,
  322. torch.quint4x2,
  323. torch.qint32,
  324. torch.uint8,
  325. torch.int8,
  326. torch.int16,
  327. torch.int32,
  328. torch.float8_e5m2,
  329. torch.float8_e4m3fn,
  330. ]
  331. if weight.dtype in static_dtypes:
  332. if hasattr(activation, "is_dynamic") and activation.is_dynamic:
  333. return QuantType.DYNAMIC
  334. elif activation.dtype in static_dtypes:
  335. return QuantType.STATIC
  336. else:
  337. return QuantType.WEIGHT_ONLY
  338. if weight.dtype == torch.float16:
  339. if hasattr(activation, "is_dynamic") and activation.is_dynamic:
  340. return QuantType.DYNAMIC
  341. elif activation.dtype == torch.float16:
  342. return QuantType.STATIC
  343. raise Exception( # noqa: TRY002
  344. f"Unrecognized dtype combination in get_quant_type: activation({activation.dtype}),"
  345. f"weight({weight.dtype})"
  346. )
  347. def check_min_max_valid(min_val: torch.Tensor, max_val: torch.Tensor) -> bool:
  348. """Checks if the given minimum and maximum values are valid, meaning that
  349. they exist and the min value is less than the max value.
  350. """
  351. if min_val.numel() == 0 or max_val.numel() == 0:
  352. warnings.warn(
  353. "must run observer before calling calculate_qparams. "
  354. + "Returning default values.",
  355. stacklevel=2,
  356. )
  357. return False
  358. if min_val.dim() == 0 or max_val.dim() == 0:
  359. if min_val == float("inf") and max_val == float("-inf"):
  360. warnings.warn(
  361. "must run observer before calling calculate_qparams. "
  362. + "Returning default values.",
  363. stacklevel=2,
  364. )
  365. return False
  366. if min_val > max_val:
  367. raise AssertionError(f"min {min_val} should be less than max {max_val}")
  368. else:
  369. if torch.any(min_val > max_val):
  370. raise AssertionError(f"min {min_val} should be less than max {max_val}")
  371. return True
  372. def calculate_qmin_qmax(
  373. quant_min: int,
  374. quant_max: int,
  375. has_customized_qrange: bool,
  376. dtype: torch.dtype,
  377. reduce_range: bool,
  378. ) -> tuple[int, int]:
  379. r"""Calculates actual qmin and qmax based on the quantization range,
  380. observer datatype and if range is reduced.
  381. """
  382. # TODO(jerryzh): Figure out why custom quant_min/quant_max are still adjusted.
  383. if has_customized_qrange:
  384. # This initialization here is to be resolve TorchScript compilation issues and allow
  385. # using of refinement to decouple initial_qmin and initial_qmax from quantization range.
  386. # The actual values of initial_qmin and initial_qmax will be reset below.
  387. if dtype in [torch.qint32, torch.int32]:
  388. initial_quant_min, initial_quant_max = 0, 2**32 - 1
  389. else:
  390. initial_quant_min, initial_quant_max = 0, 255
  391. # The following assignment of self.qmin and self.qmax to the local variables and the if check refine the
  392. # attribute from Optional valid integers for use, based on TorchScript's requirements.
  393. custom_quant_min, custom_quant_max = quant_min, quant_max
  394. if custom_quant_min is not None and custom_quant_max is not None:
  395. initial_quant_min, initial_quant_max = (
  396. custom_quant_min,
  397. custom_quant_max,
  398. )
  399. qrange_len = initial_quant_max - initial_quant_min + 1
  400. if dtype in [torch.qint8, torch.int8]:
  401. if not (0 < qrange_len <= 256):
  402. raise AssertionError(
  403. "quantization range should be positive and not exceed the maximum bit range (=256)."
  404. )
  405. elif dtype in [torch.qint32, torch.int32]:
  406. if not (0 < qrange_len <= 2**32):
  407. raise AssertionError(
  408. "quantization range should be positive and not exceed the maximum bit range (=4294967296)."
  409. )
  410. if reduce_range:
  411. quant_min, quant_max = quant_min // 2, quant_max // 2
  412. else:
  413. # Fallback onto default 8-bit qmin and qmax calculation if dynamic range is not used.
  414. if dtype in [torch.qint8, torch.int8]:
  415. if reduce_range:
  416. quant_min, quant_max = -64, 63
  417. else:
  418. quant_min, quant_max = -128, 127
  419. elif dtype in [torch.quint8, torch.uint8]:
  420. if reduce_range:
  421. quant_min, quant_max = 0, 127
  422. else:
  423. quant_min, quant_max = 0, 255
  424. elif dtype in [torch.qint32, torch.int32]:
  425. quant_min, quant_max = -1 * (2**31), (2**31) - 1
  426. elif dtype == torch.uint16:
  427. quant_min, quant_max = 0, 2**16 - 1
  428. elif dtype == torch.int16:
  429. quant_min, quant_max = -(2**15), 2**15 - 1
  430. else:
  431. quant_min, quant_max = 0, 15
  432. return quant_min, quant_max
  433. def _parent_name(target):
  434. """
  435. Turn 'foo.bar' into ['foo', 'bar']
  436. """
  437. r = target.rsplit(".", 1)
  438. if len(r) == 1:
  439. return "", r[0]
  440. else:
  441. return r[0], r[1]
  442. def has_no_children_ignoring_parametrizations(module):
  443. """
  444. Checks if module._modules is empty or
  445. if module is a parametrization, checks that module._modules only has
  446. the 'parametrizations' module
  447. """
  448. if len(module._modules) == 0:
  449. return True
  450. elif is_parametrized(module):
  451. return len(module._modules) == 1 and "parametrizations" in module._modules
  452. else:
  453. return False
  454. def _get_path_of_module(
  455. root: torch.nn.Module, submodule: torch.nn.Module
  456. ) -> str | None:
  457. """Get the path (fully qualified name) of a submodule
  458. Example::
  459. >> class M(torch.nn.Module):
  460. def __init__(self) -> None:
  461. self.linear = torch.nn.Linear(5, 5)
  462. def forward(self, x):
  463. return self.linear(x)
  464. >> m = M()
  465. >> l = m.linear
  466. >> _get_path_of_module(m, l)
  467. "linear"
  468. """
  469. for n, p in root.named_modules():
  470. if submodule is p:
  471. return n
  472. return None
  473. def _get_signature_locals(f: Callable, loc: dict[str, Any]) -> dict[str, Any]:
  474. """Get local keyword arguments
  475. Example::
  476. >> def f(self, a, b=9):
  477. pass
  478. >> loc = {"a": 6, "c": 7}
  479. >> _get_signature_locals(f, loc)
  480. {"a": 6}
  481. """
  482. return {k: v for k, v in loc.items() if k in signature(f).parameters}
  483. def _get_default_kwargs(f: Callable) -> "OrderedDict[str, Any]":
  484. """Get all default keyword arguments from function signature
  485. Example::
  486. >> def f(self, a, b=9):
  487. pass
  488. >> _get_default_kwargs(f)
  489. {"b": 9}
  490. """
  491. kwargs = {}
  492. for name, param in signature(f).parameters.items():
  493. if param.default is not param.empty:
  494. kwargs[name] = param.default
  495. elif param.kind is param.VAR_POSITIONAL:
  496. kwargs[name] = ()
  497. elif param.kind is param.VAR_KEYWORD:
  498. kwargs[name] = {}
  499. return OrderedDict(kwargs)
  500. def _normalize_kwargs(func: Callable, loc: dict[str, Any]) -> "OrderedDict[str, Any]":
  501. """Given a function and local function arguments, normalize the keyword
  502. arguments by filling in default arguments from function signature
  503. Example::
  504. >> def f(self, key1=3, key2=3):
  505. pass
  506. >> loc = {"key2": 6}
  507. >> _normalize_kwargs(f, loc)
  508. {"key1": 3, "key2": 6}
  509. """
  510. default_kwargs = _get_default_kwargs(func)
  511. local_kwargs = _get_signature_locals(func, loc)
  512. normalized_kwargs = default_kwargs.copy()
  513. for attr, val in local_kwargs.items():
  514. if attr in normalized_kwargs:
  515. # override the default keyword arguments
  516. normalized_kwargs[attr] = val
  517. return normalized_kwargs
  518. def validate_qmin_qmax(quant_min: int, quant_max: int) -> None:
  519. r"""Validates that the user-specified quantization range is properly initialized
  520. and within the given bound supported by the observer dtype.
  521. To accommodate lower-bit quantization with respect to the existing torch.qint8 and
  522. torch.quint8 datatypes, the user can choose to use dynamic quantization range by passing
  523. in a tuple of initial qmin and qmax values. One use case is these customized qmin and qmax
  524. values are used to calculate static estimates of the scale and zero point for aggressive lower-bit
  525. fake quantization. These estimates are compared against parameters learned through backpropagation.
  526. The related literatures for scale and zero point via backpropagation are as follows:
  527. Learned Step Size Quantization: https://openreview.net/pdf?id=rkgO66VKDS
  528. Trained Quantization Thresholds: https://arxiv.org/pdf/1903.08066.pdf
  529. """
  530. # The variable names are prefixed with "initial" because their values (qmin and qmax) might be adjusted
  531. # based on whether quantization range is reduced and the datatype (signed/unsigned) used by the observer.
  532. if not (quant_min <= 0 <= quant_max):
  533. raise AssertionError("Used-specified quantization range must include 0.")
  534. if quant_min >= quant_max:
  535. raise AssertionError(
  536. "qmin must be strictly less than qmax for user-specified quantization range."
  537. )
  538. # Functionally equivalent to '_calculate_qparams' in observer.py. Observers must be torchscriptable however and qscheme
  539. # as far as I can tell is not allowed to passed as a parameter in torchscript functions. This makes refactoring observer
  540. # to use this utility a massive pain and very gross. For now Im opting just to duplicate as this code seems unlikely to change
  541. # (last update over 1 year ago) and when torchscript is fully deprecated we can refactor. TODO(jakeszwe, jerryzh168)
  542. def determine_qparams(
  543. min_val: torch.Tensor,
  544. max_val: torch.Tensor,
  545. quant_min: int,
  546. quant_max: int,
  547. dtype: torch.dtype,
  548. eps: torch.Tensor,
  549. has_customized_qrange: bool,
  550. qscheme: torch.qscheme = torch.per_tensor_affine,
  551. ) -> tuple[torch.Tensor, torch.Tensor]:
  552. r"""Calculates the quantization parameters, given min and max
  553. value tensors. Works for both per tensor and per channel cases
  554. Args:
  555. min_val: Minimum values per channel
  556. max_val: Maximum values per channel
  557. Returns:
  558. scales: Scales tensor of shape (#channels,)
  559. zero_points: Zero points tensor of shape (#channels,)
  560. """
  561. if not check_min_max_valid(min_val, max_val):
  562. return torch.tensor([1.0], device=min_val.device.type), torch.tensor(
  563. [0], device=min_val.device.type
  564. )
  565. min_val_neg = torch.min(min_val, torch.zeros_like(min_val))
  566. max_val_pos = torch.max(max_val, torch.zeros_like(max_val))
  567. device = min_val_neg.device
  568. scale = torch.ones(min_val_neg.size(), dtype=torch.double, device=device)
  569. zero_point = torch.zeros(min_val_neg.size(), dtype=torch.int64, device=device)
  570. eps = eps.to(device)
  571. if qscheme == torch.per_tensor_symmetric or qscheme == torch.per_channel_symmetric:
  572. max_val_pos = torch.max(-min_val_neg, max_val_pos)
  573. scale = max_val_pos / (float(quant_max - quant_min) / 2)
  574. scale = torch.max(scale, eps)
  575. if dtype in [torch.uint8, torch.quint8]:
  576. if has_customized_qrange:
  577. # When customized quantization range is used, down-rounded midpoint of the range is chosen.
  578. zero_point = zero_point.new_full(
  579. zero_point.size(), (quant_min + quant_max) // 2
  580. )
  581. else:
  582. zero_point = zero_point.new_full(zero_point.size(), 128)
  583. elif qscheme == torch.per_channel_affine_float_qparams:
  584. scale = (max_val - min_val) / float(quant_max - quant_min)
  585. scale = torch.where(scale > eps, scale, torch.ones_like(scale))
  586. # We use the quantize function
  587. # xq = Round(Xf * inv_scale + zero_point),
  588. # setting zero_point to (-1 * min *inv_scale) we get
  589. # Xq = Round((Xf - min) * inv_scale)
  590. zero_point = -1 * min_val / scale
  591. else:
  592. scale = (max_val_pos - min_val_neg) / float(quant_max - quant_min)
  593. scale = torch.max(scale, eps)
  594. zero_point = quant_min - torch.round(min_val_neg / scale).to(torch.int)
  595. zero_point = torch.clamp(zero_point, quant_min, quant_max)
  596. # For scalar values, cast them to Tensors of size 1 to keep the shape
  597. # consistent with default values in FakeQuantize.
  598. if len(scale.shape) == 0:
  599. # TODO: switch to scale.item() after adding JIT support
  600. scale = torch.tensor([float(scale)], dtype=scale.dtype, device=device)
  601. if len(zero_point.shape) == 0:
  602. # TODO: switch to zero_point.item() after adding JIT support
  603. zero_point = torch.tensor(
  604. [int(zero_point)], dtype=zero_point.dtype, device=device
  605. )
  606. if qscheme == torch.per_channel_affine_float_qparams:
  607. zero_point = torch.tensor(
  608. [float(zero_point)], dtype=zero_point.dtype, device=device
  609. )
  610. return scale.to(torch.double), zero_point.to(torch.int64)
  611. def _get_num_pos_args(f: Callable) -> int:
  612. """Get number of positional args for a function
  613. Example::
  614. >> def f(self, key1=3, key2=3):
  615. pass
  616. >> _get_num_pos_args(f)
  617. 3
  618. """
  619. return len(getfullargspec(f).args)
  620. def get_fqn_to_example_inputs(
  621. model: torch.nn.Module, example_inputs: tuple[Any, ...]
  622. ) -> dict[str, tuple[Any, ...]]:
  623. """Given a model and its example inputs, return a dictionary from
  624. fully qualified name of submodules to example_inputs for that submodule,
  625. e.g. {"linear1": (tensor1,), "linear2": (tensor2,), "sub": (tensor3,),
  626. "sub.linear1": (tensor4,), ...}
  627. Used to make quantizing submodules easier now that FX Graph Mode Quantization requires
  628. example inputs.
  629. Also works for keyword arguments with default values, we would flatten keyword
  630. arguments as positional arguments and fill in the missing keyword args with default
  631. values, e.g. if we have a forward function:
  632. def forward(self, x, key1=3, key2=3):
  633. ...
  634. and we call it with self.submodule(x, key2=6)
  635. we'll get example_inputs: (x, 3, 6)
  636. user can also override `key1` with positional arguments as well:
  637. for self.submodule(x, 5, key2=6)
  638. we'll get: (x, 5, 6)
  639. variable positional arguments and variable positional keyword arguments in forward
  640. function are not supported currently, so please make sure no submodules is using
  641. them.
  642. """
  643. root = model
  644. fqn_to_example_inputs = {}
  645. def _patched_module_call(self, *args, **kwargs):
  646. submodule_example_inputs = list(args).copy()
  647. normalized_kwargs = _normalize_kwargs(self.forward, kwargs)
  648. # minus 1 to skipping counting `self`
  649. num_args = _get_num_pos_args(self.forward) - 1
  650. num_to_pop = num_args - len(submodule_example_inputs)
  651. while num_to_pop and normalized_kwargs:
  652. normalized_kwargs.popitem(last=False)
  653. num_to_pop -= 1
  654. submodule_example_inputs.extend(normalized_kwargs.values())
  655. submodule_example_inputs_tuple = tuple(submodule_example_inputs)
  656. fqn = _get_path_of_module(root, self)
  657. if fqn is not None:
  658. fqn_to_example_inputs[fqn] = submodule_example_inputs_tuple
  659. return orig_module_call(self, *args, **kwargs)
  660. orig_module_call = torch.nn.Module.__call__
  661. torch.nn.Module.__call__ = _patched_module_call # type: ignore[method-assign]
  662. try:
  663. model(*example_inputs)
  664. finally:
  665. # restore the module call even if there is an exception
  666. torch.nn.Module.__call__ = orig_module_call # type: ignore[method-assign]
  667. return fqn_to_example_inputs
  668. def _assert_and_get_unique_device(module: torch.nn.Module) -> Any:
  669. """
  670. Returns the unique device for a module, or None if no device is found.
  671. Throws an error if multiple devices are detected.
  672. """
  673. devices = {p.device for p in module.parameters()} | {
  674. p.device for p in module.buffers()
  675. }
  676. """
  677. As a temp workaround for AIMP HHC publish we added CPU check.remove it later. T163614564
  678. """
  679. if {torch.device("cpu"), torch.device("meta")} == devices:
  680. warnings.warn(
  681. "Both 'meta' and 'cpu' are present in the list of devices. Module can have one device. We Select 'cpu'.",
  682. stacklevel=2,
  683. )
  684. devices = {torch.device("cpu")}
  685. ""
  686. if len(devices) > 1:
  687. raise AssertionError(
  688. "prepare only works with cpu or single-device CUDA modules, "
  689. f"but got devices {devices}"
  690. )
  691. device = next(iter(devices)) if len(devices) > 0 else None
  692. return device
  693. DEPRECATION_WARNING = (
  694. "torch.ao.quantization is deprecated and will be removed in 2.10. \n"
  695. "For migrations of users: \n"
  696. "1. Eager mode quantization (torch.ao.quantization.quantize, "
  697. "torch.ao.quantization.quantize_dynamic), please migrate to use torchao eager mode "
  698. "quantize_ API instead \n"
  699. "2. FX graph mode quantization (torch.ao.quantization.quantize_fx.prepare_fx,"
  700. "torch.ao.quantization.quantize_fx.convert_fx, please migrate to use torchao pt2e quantization "
  701. "API instead (prepare_pt2e, convert_pt2e) \n"
  702. "3. pt2e quantization has been migrated to torchao (https://github.com/pytorch/ao/tree/main/torchao/quantization/pt2e) \n"
  703. "see https://github.com/pytorch/ao/issues/2259 for more details"
  704. )
  705. __all__ = [
  706. "NodePattern",
  707. "Pattern",
  708. "MatchAllNode",
  709. "check_node",
  710. "get_combined_dict",
  711. "is_per_tensor",
  712. "is_per_channel",
  713. "getattr_from_fqn",
  714. "get_qparam_dict",
  715. "get_swapped_custom_module_class",
  716. "activation_dtype",
  717. "weight_dtype",
  718. "activation_is_statically_quantized",
  719. "activation_is_dynamically_quantized",
  720. "activation_is_int8_quantized",
  721. "activation_is_int32_quantized",
  722. "weight_is_quantized",
  723. "weight_is_statically_quantized",
  724. "op_is_int8_dynamically_quantized",
  725. "get_qconfig_dtypes",
  726. "get_quant_type",
  727. "check_min_max_valid",
  728. "calculate_qmin_qmax",
  729. "has_no_children_ignoring_parametrizations",
  730. "get_fqn_to_example_inputs",
  731. "to_underlying_dtype",
  732. "determine_qparams",
  733. "validate_qmin_qmax",
  734. "DEPRECATION_WARNING",
  735. ]