utils.py 29 KB

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