utils.py 29 KB

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