qconfig.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. # mypy: allow-untyped-defs
  2. import copy
  3. import sys
  4. import warnings
  5. from collections import namedtuple
  6. from typing import Any, Optional, Union
  7. from typing_extensions import deprecated
  8. import torch
  9. import torch.nn as nn
  10. from torch.ao.quantization.fake_quantize import (
  11. default_dynamic_fake_quant,
  12. default_embedding_fake_quant,
  13. default_embedding_fake_quant_4bit,
  14. default_fake_quant,
  15. default_fused_act_fake_quant,
  16. default_fused_per_channel_wt_fake_quant,
  17. default_fused_wt_fake_quant,
  18. default_per_channel_weight_fake_quant,
  19. default_weight_fake_quant,
  20. FakeQuantize,
  21. FakeQuantizeBase,
  22. fused_per_channel_wt_fake_quant_range_neg_127_to_127,
  23. fused_wt_fake_quant_range_neg_127_to_127,
  24. FusedMovingAvgObsFakeQuantize,
  25. )
  26. from .observer import (
  27. _PartialWrapper,
  28. default_debug_observer,
  29. default_dynamic_quant_observer,
  30. default_float_qparams_observer,
  31. default_float_qparams_observer_4bit,
  32. default_observer,
  33. default_per_channel_weight_observer,
  34. default_placeholder_observer,
  35. default_reuse_input_observer,
  36. default_weight_observer,
  37. HistogramObserver,
  38. MinMaxObserver,
  39. MovingAverageMinMaxObserver,
  40. NoopObserver,
  41. ObserverBase,
  42. per_channel_weight_observer_range_neg_127_to_127,
  43. PlaceholderObserver,
  44. ReuseInputObserver,
  45. weight_observer_range_neg_127_to_127,
  46. )
  47. __all__ = [
  48. "QConfig",
  49. # TODO: deprecated, remove
  50. "QConfigDynamic",
  51. "default_qconfig",
  52. "default_debug_qconfig",
  53. "default_per_channel_qconfig",
  54. "default_dynamic_qconfig",
  55. "float16_dynamic_qconfig",
  56. "float16_static_qconfig",
  57. "per_channel_dynamic_qconfig",
  58. "float_qparams_weight_only_qconfig",
  59. "float_qparams_weight_only_qconfig_4bit",
  60. "default_quint8_weight_qconfig",
  61. "default_qat_qconfig",
  62. "default_dynamic_qat_qconfig",
  63. "default_weight_only_qconfig",
  64. "default_activation_only_qconfig",
  65. "default_qat_qconfig_v2",
  66. "default_reuse_input_qconfig",
  67. "default_symmetric_qnnpack_qconfig",
  68. "default_per_channel_symmetric_qnnpack_qconfig",
  69. "default_symmetric_qnnpack_qat_qconfig",
  70. "default_per_channel_symmetric_qnnpack_qat_qconfig",
  71. "default_embedding_qat_qconfig",
  72. "default_embedding_qat_qconfig_4bit",
  73. "get_default_qconfig",
  74. "get_default_qat_qconfig",
  75. "get_default_qconfig_dict",
  76. "get_default_qat_qconfig_dict",
  77. "QConfigAny",
  78. "qconfig_equals",
  79. ]
  80. # pyrefly: ignore [invalid-inheritance]
  81. class QConfig(namedtuple("QConfig", ["activation", "weight"])):
  82. """
  83. Describes how to quantize a layer or a part of the network by providing
  84. settings (observer classes) for activations and weights respectively.
  85. Note that QConfig needs to contain observer **classes** (like MinMaxObserver) or a callable that returns
  86. instances on invocation, not the concrete observer instances themselves.
  87. Quantization preparation function will instantiate observers multiple times for each of the layers.
  88. Observer classes have usually reasonable default arguments, but they can be overwritten with `with_args`
  89. method (that behaves like functools.partial)::
  90. my_qconfig = QConfig(
  91. activation=MinMaxObserver.with_args(dtype=torch.qint8),
  92. weight=default_observer.with_args(dtype=torch.qint8),
  93. )
  94. """
  95. __slots__ = ()
  96. def __new__(cls, activation, weight):
  97. # catch common mistakes
  98. if isinstance(activation, nn.Module) or isinstance(weight, nn.Module):
  99. raise ValueError(
  100. "QConfig received observer instance, please pass observer class instead. "
  101. + "Use MyObserver.with_args(x=1) to override arguments to constructor if needed"
  102. )
  103. return super().__new__(cls, activation, weight)
  104. @deprecated(
  105. "`QConfigDynamic` is going to be deprecated in PyTorch 1.12, please use `QConfig` instead",
  106. category=FutureWarning,
  107. )
  108. # pyrefly: ignore [invalid-inheritance]
  109. class QConfigDynamic(namedtuple("QConfigDynamic", ["activation", "weight"])):
  110. """
  111. Describes how to dynamically quantize a layer or a part of the network by providing
  112. settings (observer classes) for weights.
  113. It's like QConfig, but for dynamic quantization.
  114. Note that QConfigDynamic needs to contain observer **classes** (like MinMaxObserver) or a callable that returns
  115. instances on invocation, not the concrete observer instances themselves.
  116. Quantization function will instantiate observers multiple times for each of the layers.
  117. Observer classes have usually reasonable default arguments, but they can be overwritten with `with_args`
  118. method (that behaves like functools.partial)::
  119. my_qconfig = QConfigDynamic(weight=default_observer.with_args(dtype=torch.qint8))
  120. """
  121. __slots__ = ()
  122. def __new__(cls, activation=torch.nn.Identity, weight=torch.nn.Identity):
  123. # catch common mistakes
  124. if isinstance(weight, nn.Module):
  125. raise ValueError(
  126. "QConfigDynamic received observer instance, please pass observer class instead. "
  127. + "Use MyObserver.with_args(x=1) to override arguments to constructor if needed"
  128. )
  129. return super().__new__(cls, activation, weight)
  130. default_qconfig = QConfig(activation=default_observer, weight=default_weight_observer)
  131. """
  132. Default qconfig configuration.
  133. """
  134. default_debug_qconfig = QConfig(
  135. weight=default_weight_observer, activation=default_debug_observer
  136. )
  137. """
  138. Default qconfig configuration for debugging.
  139. """
  140. default_per_channel_qconfig = QConfig(
  141. activation=default_observer, weight=default_per_channel_weight_observer
  142. )
  143. """
  144. Default qconfig configuration for per channel weight quantization.
  145. """
  146. default_dynamic_qconfig = QConfig(
  147. activation=default_dynamic_quant_observer, weight=default_weight_observer
  148. )
  149. """
  150. Default dynamic qconfig.
  151. """
  152. float16_dynamic_qconfig = QConfig(
  153. activation=PlaceholderObserver.with_args(dtype=torch.float16, is_dynamic=True),
  154. weight=PlaceholderObserver.with_args(dtype=torch.float16),
  155. )
  156. """
  157. Dynamic qconfig with weights quantized to `torch.float16`.
  158. """
  159. float16_static_qconfig = QConfig(
  160. activation=PlaceholderObserver.with_args(dtype=torch.float16),
  161. weight=PlaceholderObserver.with_args(dtype=torch.float16),
  162. )
  163. """
  164. Dynamic qconfig with both activations and weights quantized to `torch.float16`.
  165. """
  166. per_channel_dynamic_qconfig = QConfig(
  167. activation=default_dynamic_quant_observer,
  168. weight=default_per_channel_weight_observer,
  169. )
  170. """
  171. Dynamic qconfig with weights quantized per channel.
  172. """
  173. float_qparams_weight_only_qconfig = QConfig(
  174. activation=default_placeholder_observer, weight=default_float_qparams_observer
  175. )
  176. """
  177. Dynamic qconfig with weights quantized with a floating point zero_point.
  178. """
  179. float_qparams_weight_only_qconfig_4bit = QConfig(
  180. activation=default_placeholder_observer, weight=default_float_qparams_observer_4bit
  181. )
  182. default_qat_qconfig = QConfig(
  183. activation=default_fake_quant, weight=default_weight_fake_quant
  184. )
  185. """
  186. Default qconfig for QAT.
  187. """
  188. default_dynamic_qat_qconfig = QConfig(
  189. activation=default_dynamic_fake_quant, weight=default_weight_fake_quant
  190. )
  191. """
  192. Default qconfig for dynamic QAT.
  193. """
  194. default_weight_only_qconfig = QConfig(
  195. activation=torch.nn.Identity, weight=default_weight_fake_quant
  196. )
  197. """
  198. Default qconfig for quantizing weights only.
  199. """
  200. default_activation_only_qconfig = QConfig(
  201. activation=default_fake_quant, weight=torch.nn.Identity
  202. )
  203. """
  204. Default qconfig for quantizing activations only.
  205. """
  206. # QAT config that uses a fused observer + fake quant modules for optimized training performance.
  207. # to modify the activation/weight observers, the default entries in fake_quantize.py can be modified.
  208. default_qat_qconfig_v2 = QConfig(
  209. activation=default_fused_act_fake_quant, weight=default_fused_wt_fake_quant
  210. )
  211. """
  212. Fused version of `default_qat_config`, has performance benefits.
  213. """
  214. default_reuse_input_qconfig = QConfig(
  215. activation=default_reuse_input_observer, weight=NoopObserver
  216. )
  217. """
  218. Default qconfig for operators that reuse the observers from input Tensor, e.g. reshape
  219. """
  220. def get_default_qconfig(backend="x86", version=0):
  221. """
  222. Returns the default PTQ qconfig for the specified backend.
  223. Args:
  224. * `backend` (str): a string representing the target backend. Currently supports
  225. `x86` (default), `fbgemm`, `qnnpack` and `onednn`.
  226. Return:
  227. qconfig
  228. """
  229. supported_backends = ["fbgemm", "x86", "qnnpack", "onednn"]
  230. if backend not in supported_backends:
  231. raise AssertionError(
  232. "backend: "
  233. + str(backend)
  234. + f" not supported. backend must be one of {supported_backends}"
  235. )
  236. if version == 0:
  237. if backend == "fbgemm":
  238. qconfig = QConfig(
  239. activation=HistogramObserver.with_args(reduce_range=True),
  240. weight=default_per_channel_weight_observer,
  241. )
  242. elif backend == "qnnpack":
  243. # TODO: make this compatible with xnnpack constraints
  244. qconfig = QConfig(
  245. activation=HistogramObserver.with_args(reduce_range=False),
  246. weight=default_weight_observer,
  247. )
  248. elif backend == "onednn":
  249. if not torch.cpu._is_vnni_supported():
  250. warnings.warn(
  251. "Default qconfig of oneDNN backend with reduce_range of false may have accuracy issues "
  252. "on CPU without Vector Neural Network Instruction support.",
  253. stacklevel=2,
  254. )
  255. qconfig = QConfig(
  256. activation=HistogramObserver.with_args(reduce_range=False),
  257. weight=default_per_channel_weight_observer,
  258. )
  259. elif backend == "x86":
  260. qconfig = QConfig(
  261. activation=HistogramObserver.with_args(reduce_range=True),
  262. weight=default_per_channel_weight_observer,
  263. )
  264. else:
  265. # won't reach
  266. qconfig = default_qconfig
  267. else:
  268. raise AssertionError(
  269. "Version number: "
  270. + str(version)
  271. + " in get_default_qconfig is not supported. Version number must be 0"
  272. )
  273. return qconfig
  274. """
  275. Default, symmetric PTQ qconfig for the specified backend. And a per_channel
  276. variant of the same.
  277. Symmetric here applies to signed weights with zero point = 0, and additional
  278. value restrictions. The activations are also signed 8-bit integers with this
  279. qconfig.
  280. * Once this change is merged [as of 3/17/22], with backend or qengine =
  281. 'qnnpack', some quantized operators with this symmetric qconfig may use
  282. operators from xnnpack library.
  283. ** Support to use xnnpack ops with `qnnpack` backed for asymmetric
  284. qconfig (returned by get_default_qconfig()) is not available yet.
  285. * This qconfig uses signed activations and weights. Weights have added
  286. restrictions such as zero point is forced to be 0, making the weights
  287. symmetric, hence the name. And the 8-bit quantized values are
  288. restricting to to [-127, +127], excluding -128.
  289. * xnnpack has a requantization scale value restriction, 0x1p-32 <=
  290. requantization_scale < 256.0 where, `requantization_scale = (input_scale
  291. * kernel_scale) / (output_scale)`. Using this eps (w/ assumed max value
  292. of 256) is to prevent requantization_scale to go below xnnpack lower
  293. threshold.
  294. """
  295. default_symmetric_qnnpack_qconfig = QConfig(
  296. activation=HistogramObserver.with_args(
  297. dtype=torch.qint8, reduce_range=False, eps=2**-12
  298. ),
  299. weight=weight_observer_range_neg_127_to_127,
  300. )
  301. default_per_channel_symmetric_qnnpack_qconfig = QConfig(
  302. activation=HistogramObserver.with_args(
  303. dtype=torch.qint8, reduce_range=False, eps=2**-12
  304. ),
  305. weight=per_channel_weight_observer_range_neg_127_to_127,
  306. )
  307. default_embedding_qat_qconfig = QConfig(
  308. activation=NoopObserver.with_args(dtype=torch.float32),
  309. weight=default_embedding_fake_quant,
  310. )
  311. default_embedding_qat_qconfig_4bit = QConfig(
  312. activation=NoopObserver.with_args(dtype=torch.float32),
  313. weight=default_embedding_fake_quant_4bit,
  314. )
  315. default_quint8_weight_qconfig = QConfig(
  316. activation=HistogramObserver, weight=MinMaxObserver
  317. )
  318. def get_default_qat_qconfig(backend="x86", version=1):
  319. """
  320. Returns the default QAT qconfig for the specified backend.
  321. Args:
  322. * `backend` (str): a string representing the target backend. Currently supports
  323. `x86` (default), `fbgemm`, `qnnpack` and `onednn`.
  324. * `version`: version, for backwards compatibility. Can be `None` or `1`.
  325. Return:
  326. qconfig
  327. """
  328. supported_backends = ["fbgemm", "x86", "qnnpack", "onednn"]
  329. if backend not in supported_backends:
  330. raise AssertionError(
  331. "backend: "
  332. + str(backend)
  333. + f" not supported. backend must be one of {supported_backends}"
  334. )
  335. # Histogram observer is too slow for quantization aware training
  336. if version == 0:
  337. if backend == "fbgemm":
  338. qconfig = QConfig(
  339. activation=FakeQuantize.with_args(
  340. observer=MovingAverageMinMaxObserver,
  341. quant_min=0,
  342. quant_max=255,
  343. reduce_range=True,
  344. ),
  345. weight=default_per_channel_weight_fake_quant,
  346. )
  347. elif backend == "qnnpack":
  348. qconfig = QConfig(
  349. activation=FakeQuantize.with_args(
  350. observer=MovingAverageMinMaxObserver,
  351. quant_min=0,
  352. quant_max=255,
  353. reduce_range=False,
  354. ),
  355. weight=default_weight_fake_quant,
  356. )
  357. elif backend == "onednn":
  358. qconfig = QConfig(
  359. activation=FakeQuantize.with_args(
  360. observer=MovingAverageMinMaxObserver, quant_min=0, quant_max=255
  361. ),
  362. weight=default_per_channel_weight_fake_quant,
  363. )
  364. elif backend == "x86":
  365. qconfig = QConfig(
  366. activation=FakeQuantize.with_args(
  367. observer=MovingAverageMinMaxObserver,
  368. quant_min=0,
  369. quant_max=255,
  370. reduce_range=True,
  371. ),
  372. weight=default_per_channel_weight_fake_quant,
  373. )
  374. else:
  375. qconfig = default_qat_qconfig
  376. # Use the fused observe + fake_quant modules for doing QAT.
  377. elif version == 1:
  378. if backend == "fbgemm":
  379. qconfig = QConfig(
  380. activation=FusedMovingAvgObsFakeQuantize.with_args(
  381. observer=MovingAverageMinMaxObserver,
  382. quant_min=0,
  383. quant_max=255,
  384. reduce_range=True,
  385. ),
  386. weight=default_fused_per_channel_wt_fake_quant,
  387. )
  388. elif backend == "qnnpack":
  389. # TODO: make this compatible with xnnpack constraints
  390. qconfig = QConfig(
  391. activation=FusedMovingAvgObsFakeQuantize.with_args(
  392. observer=MovingAverageMinMaxObserver,
  393. quant_min=0,
  394. quant_max=255,
  395. reduce_range=False,
  396. ),
  397. weight=default_fused_wt_fake_quant,
  398. )
  399. elif backend == "onednn":
  400. qconfig = QConfig(
  401. activation=FusedMovingAvgObsFakeQuantize.with_args(
  402. observer=MovingAverageMinMaxObserver, quant_min=0, quant_max=255
  403. ),
  404. weight=default_fused_per_channel_wt_fake_quant,
  405. )
  406. elif backend == "x86":
  407. qconfig = QConfig(
  408. activation=FusedMovingAvgObsFakeQuantize.with_args(
  409. observer=MovingAverageMinMaxObserver,
  410. quant_min=0,
  411. quant_max=255,
  412. reduce_range=True,
  413. ),
  414. weight=default_fused_per_channel_wt_fake_quant,
  415. )
  416. else:
  417. qconfig = default_qat_qconfig_v2
  418. else:
  419. raise AssertionError(
  420. "Version number: "
  421. + str(version)
  422. + "in get_default_qat_qconfig is not supported. Version number must be 0 or 1"
  423. )
  424. return qconfig
  425. """
  426. Default symmetric QAT qconfig for qnnpack. And its per channel weight variant.
  427. """
  428. default_symmetric_qnnpack_qat_qconfig = QConfig(
  429. activation=FusedMovingAvgObsFakeQuantize.with_args(
  430. observer=MovingAverageMinMaxObserver,
  431. quant_min=-128,
  432. quant_max=127,
  433. dtype=torch.qint8,
  434. reduce_range=False,
  435. eps=2**-12,
  436. ),
  437. weight=fused_wt_fake_quant_range_neg_127_to_127,
  438. )
  439. default_per_channel_symmetric_qnnpack_qat_qconfig = QConfig(
  440. activation=FusedMovingAvgObsFakeQuantize.with_args(
  441. observer=MovingAverageMinMaxObserver,
  442. quant_min=-128,
  443. quant_max=127,
  444. dtype=torch.qint8,
  445. reduce_range=False,
  446. eps=2**-12,
  447. ),
  448. weight=fused_per_channel_wt_fake_quant_range_neg_127_to_127,
  449. )
  450. _default_fp32_placeholder_qconfig = QConfig(
  451. activation=PlaceholderObserver.with_args(dtype=torch.float32),
  452. weight=PlaceholderObserver.with_args(dtype=torch.float32),
  453. )
  454. _default_quint8_placeholder_qconfig = QConfig(
  455. activation=PlaceholderObserver.with_args(dtype=torch.quint8),
  456. # operators using this qconfig doesn't have weights
  457. weight=None,
  458. )
  459. @deprecated(
  460. "`torch.ao.quantization.get_default_qconfig_dict` is deprecated and will be removed in "
  461. "a future version. Please use `torch.ao.quantization.get_default_qconfig_mapping` instead.",
  462. category=FutureWarning,
  463. )
  464. def get_default_qconfig_dict(backend="x86", version=0):
  465. return torch.ao.quantization.get_default_qconfig_mapping(backend, version).to_dict()
  466. @deprecated(
  467. "`torch.ao.quantization.get_default_qat_qconfig_dict` is deprecated and will be removed in "
  468. "a future version. Please use `torch.ao.quantization.get_default_qat_qconfig_mapping` instead.",
  469. category=FutureWarning,
  470. )
  471. def get_default_qat_qconfig_dict(backend="x86", version=1):
  472. return torch.ao.quantization.get_default_qat_qconfig_mapping(
  473. backend, version
  474. ).to_dict()
  475. def _assert_valid_qconfig(qconfig: QConfig | None, mod: torch.nn.Module) -> None:
  476. """
  477. Verifies that this `qconfig` is valid.
  478. """
  479. if qconfig is None:
  480. return
  481. is_conv_transpose_mod = isinstance(
  482. mod,
  483. (torch.nn.ConvTranspose1d, torch.nn.ConvTranspose2d, torch.nn.ConvTranspose3d),
  484. )
  485. if is_conv_transpose_mod:
  486. if qconfig.weight is None:
  487. # for now, we assume that any qconfig for ConvTranspose without a weight is valid
  488. return
  489. example_observer = qconfig.weight()
  490. is_per_channel = isinstance(
  491. example_observer,
  492. (
  493. torch.ao.quantization.PerChannelMinMaxObserver,
  494. torch.ao.quantization.MovingAveragePerChannelMinMaxObserver,
  495. ),
  496. )
  497. if is_per_channel:
  498. raise AssertionError(
  499. "Per channel weight observer is not supported yet for ConvTranspose{n}d."
  500. )
  501. if sys.version_info < (3, 12):
  502. QConfigAny = Optional[QConfig]
  503. QConfigAny.__module__ = "torch.ao.quantization.qconfig"
  504. else:
  505. from typing import TypeAliasType
  506. QConfigAny = TypeAliasType("QConfigAny", QConfig | None)
  507. def _add_module_to_qconfig_obs_ctr(
  508. qconfig: QConfigAny, module: nn.Module | None
  509. ) -> Any:
  510. r"""This is a helper function for use in quantization prepare that updates a qconfig so that
  511. the constructors stored in the qconfig will create observers on the same device that
  512. 'module' is on. This is intended to be used when the qconfigs are propagated to each
  513. module in order to avoid potential device alignment issues.
  514. Args:
  515. qconfig: QConfig with obs constructors stored in activation and weight
  516. module: module which the qconfig is related to
  517. Return:
  518. qconfig: configured so that obs constructors set to construct on the same device as module
  519. """
  520. if module is None or qconfig is None or qconfig._fields != ("activation", "weight"):
  521. return qconfig
  522. def get_factory_kwargs_based_on_module_device():
  523. if not isinstance(module, torch.nn.Module):
  524. raise AssertionError("module must be an instance of torch.nn.Module")
  525. devices = {p.device for p in module.parameters()} | {
  526. p.device for p in module.buffers()
  527. }
  528. device = next(iter(devices)) if len(devices) > 0 else None
  529. return None if device is None else {"device": device}
  530. def configure_constructor_to_put_obs_on_module_device(original_constructor):
  531. try:
  532. # check if constructor can accept factory_kwargs
  533. check = original_constructor.with_args(factory_kwargs=None)
  534. check()
  535. return original_constructor.with_callable_args(
  536. factory_kwargs=get_factory_kwargs_based_on_module_device
  537. )
  538. except AttributeError: # qconfig doesn't have activation or weight
  539. return original_constructor
  540. except TypeError: # the class doesn't accept factory_kwargs argument
  541. return original_constructor
  542. activation = configure_constructor_to_put_obs_on_module_device(qconfig.activation)
  543. weight = configure_constructor_to_put_obs_on_module_device(qconfig.weight)
  544. return QConfig(activation, weight)
  545. _ObserverOrFakeQuantizeConstructor = Union[
  546. _PartialWrapper, type[ObserverBase], type[FakeQuantizeBase]
  547. ]
  548. def _obs_or_fq_ctr_equals(
  549. obs_or_fq1: _ObserverOrFakeQuantizeConstructor,
  550. obs_or_fq2: _ObserverOrFakeQuantizeConstructor,
  551. ):
  552. if isinstance(obs_or_fq1, _PartialWrapper) and isinstance(
  553. obs_or_fq2, _PartialWrapper
  554. ):
  555. return _partial_wrapper_equals(obs_or_fq1, obs_or_fq2)
  556. return obs_or_fq1 == obs_or_fq2
  557. def _partial_wrapper_equals(obs_or_fq1: _PartialWrapper, obs_or_fq2: _PartialWrapper):
  558. """
  559. Return whether the two partial wrappers are equal,
  560. """
  561. # functools.partial has no __eq__ operator defined so '==' defaults to 'is'
  562. obs_or_fq1_keywords = copy.copy(obs_or_fq1.p.keywords)
  563. obs_or_fq2_keywords = copy.copy(obs_or_fq2.p.keywords)
  564. keywords_equal = True
  565. # compare observer constructor with _obs_or_fq_ctr_equals since direct compare would fail
  566. if "observer" in obs_or_fq1_keywords and "observer" in obs_or_fq2_keywords:
  567. keywords_equal = keywords_equal and _obs_or_fq_ctr_equals(
  568. obs_or_fq1_keywords["observer"], obs_or_fq2_keywords["observer"]
  569. )
  570. obs_or_fq1_keywords.pop("observer")
  571. obs_or_fq2_keywords.pop("observer")
  572. keywords_equal = keywords_equal and obs_or_fq1_keywords == obs_or_fq2_keywords
  573. return (
  574. obs_or_fq1.p.func == obs_or_fq2.p.func
  575. and obs_or_fq1.p.args == obs_or_fq2.p.args
  576. and keywords_equal
  577. )
  578. def qconfig_equals(q1: QConfigAny, q2: QConfigAny):
  579. """
  580. Returns `True` if `q1` equals `q2`, and `False` otherwise.
  581. """
  582. if q1 is None or q2 is None:
  583. return q1 == q2
  584. else:
  585. if q1 is None or q2 is None:
  586. raise AssertionError(
  587. "Both q1 and q2 must be non-None for qconfig comparison"
  588. )
  589. try:
  590. # Qconfig weight and activation can be either a partial wrapper,
  591. # or an observer class. Special handling is required (above) for
  592. # comparing partial wrappers.
  593. activation_same = _obs_or_fq_ctr_equals(q1.activation, q2.activation)
  594. weight_same = _obs_or_fq_ctr_equals(q1.weight, q2.weight)
  595. return activation_same and weight_same
  596. except AttributeError:
  597. return q1 == q2
  598. def _activation_is_memoryless(qconfig: QConfig):
  599. """
  600. Return whether the observer for activations defined in the given QConfig is memoryless.
  601. This means a MovingAverage observer with averaging constant equal to 1.
  602. """
  603. def _is_memoryless(observer):
  604. return (
  605. hasattr(observer, "averaging_constant") and observer.averaging_constant == 1
  606. )
  607. act = qconfig.activation()
  608. if isinstance(act, FakeQuantizeBase) and hasattr(act, "activation_post_process"):
  609. return _is_memoryless(act.activation_post_process)
  610. else:
  611. return _is_memoryless(act)
  612. def _is_reuse_input_qconfig(qconfig: QConfig | None):
  613. return (
  614. qconfig is not None
  615. and isinstance(qconfig.activation(), ReuseInputObserver)
  616. and isinstance(qconfig.weight(), NoopObserver)
  617. )