qconfig.py 24 KB

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