qconfig.py 24 KB

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