observer.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155
  1. # mypy: allow-untyped-decorators
  2. # mypy: allow-untyped-defs
  3. # temporarily skip RUF for this file for now, we can re-enable
  4. # after move the affine quantization related things to torchao
  5. # noqa: RUF
  6. """
  7. This module implements observers which are used to collect statistics about
  8. the values observed during calibration (PTQ) or training (QAT).
  9. """
  10. import operator
  11. import re
  12. import warnings
  13. from abc import ABCMeta, abstractmethod
  14. from collections import OrderedDict
  15. from functools import partial
  16. from typing import Any
  17. import torch
  18. import torch.nn as nn
  19. from torch.ao.quantization.utils import (
  20. calculate_qmin_qmax,
  21. check_min_max_valid,
  22. is_per_channel,
  23. is_per_tensor,
  24. validate_qmin_qmax,
  25. )
  26. from torch.fx import Node
  27. __all__ = [
  28. "default_affine_fixed_qparams_observer",
  29. "default_debug_observer",
  30. "default_dynamic_quant_observer",
  31. "default_fixed_qparams_range_0to1_observer",
  32. "default_fixed_qparams_range_neg1to1_observer",
  33. "default_float_qparams_observer",
  34. "default_float_qparams_observer_4bit",
  35. "default_histogram_observer",
  36. "default_observer",
  37. "default_per_channel_weight_observer",
  38. "default_placeholder_observer",
  39. "default_reuse_input_observer",
  40. "default_symmetric_fixed_qparams_observer",
  41. "default_weight_observer",
  42. "get_observer_state_dict",
  43. "load_observer_state_dict",
  44. "per_channel_weight_observer_range_neg_127_to_127",
  45. "weight_observer_range_neg_127_to_127",
  46. "FixedQParamsObserver",
  47. "HistogramObserver",
  48. "MinMaxObserver",
  49. "MovingAverageMinMaxObserver",
  50. "MovingAveragePerChannelMinMaxObserver",
  51. "NoopObserver",
  52. "ObserverBase",
  53. "PerChannelMinMaxObserver",
  54. "PlaceholderObserver",
  55. "RecordingObserver",
  56. "ReuseInputObserver",
  57. "UniformQuantizationObserverBase",
  58. "AffineQuantizedObserverBase",
  59. "Granularity",
  60. "MappingType",
  61. "PerAxis",
  62. "PerBlock",
  63. "PerGroup",
  64. "PerRow",
  65. "PerTensor",
  66. "PerToken",
  67. "TorchAODType",
  68. "ZeroPointDomain",
  69. "get_block_size",
  70. ]
  71. class _PartialWrapper:
  72. def __init__(self, p):
  73. self.p = p
  74. self.callable_args = {}
  75. def __call__(self, *args, **keywords):
  76. # call each arg in callable_args and add them partial, then run with keywords
  77. # skip if arg_name in keywords so its possible to overwrite
  78. for arg_name in self.callable_args:
  79. if arg_name not in keywords:
  80. keywords = {**keywords, arg_name: self.callable_args[arg_name]()}
  81. return self.p(*args, **keywords)
  82. def __repr__(self):
  83. return self.p.__repr__() + self.callable_args.__repr__()
  84. def with_args(self, **kwargs):
  85. return _with_args(self, **kwargs)
  86. def with_callable_args(self, **kwargs):
  87. result = _PartialWrapper(p=self.p)
  88. result.callable_args = {**self.callable_args, **kwargs}
  89. return result
  90. def _with_args(cls_or_self, **kwargs):
  91. r"""Wrapper that allows creation of class factories.
  92. This can be useful when there is a need to create classes with the same
  93. constructor arguments, but different instances. Can be used in conjunction with
  94. _callable_args
  95. Example::
  96. >>> # xdoctest: +SKIP("Undefined vars")
  97. >>> Foo.with_args = classmethod(_with_args)
  98. >>> foo_builder = Foo.with_args(a=3, b=4).with_args(answer=42)
  99. >>> foo_instance1 = foo_builder()
  100. >>> foo_instance2 = foo_builder()
  101. >>> id(foo_instance1) == id(foo_instance2)
  102. False
  103. """
  104. r = _PartialWrapper(partial(cls_or_self, **kwargs))
  105. return r
  106. def _with_callable_args(cls_or_self, **kwargs):
  107. r"""Wrapper that allows creation of class factories args that need to be
  108. called at construction time.
  109. This can be useful when there is a need to create classes with the same
  110. constructor arguments, but different instances and those arguments should only
  111. be calculated at construction time. Can be used in conjunction with _with_args
  112. Example::
  113. >>> # xdoctest: +SKIP("Undefined vars")
  114. >>> Foo.with_callable_args = classmethod(_with_callable_args)
  115. >>> Foo.with_args = classmethod(_with_args)
  116. >>> foo_builder = Foo.with_callable_args(cur_time=get_time_func).with_args(name="dan")
  117. >>> foo_instance1 = foo_builder()
  118. >>> # wait 50
  119. >>> foo_instance2 = foo_builder()
  120. >>> id(foo_instance1.creation_time) == id(foo_instance2.creation_time)
  121. False
  122. """
  123. r = _PartialWrapper(partial(cls_or_self))
  124. return r.with_callable_args(**kwargs)
  125. ABC: Any = ABCMeta("ABC", (object,), {}) # compatible with Python 2 *and* 3:
  126. class ObserverBase(ABC, nn.Module):
  127. r"""Base observer Module.
  128. Any observer implementation should derive from this class.
  129. Concrete observers should follow the same API. In forward, they will update
  130. the statistics of the observed Tensor. And they should provide a
  131. `calculate_qparams` function that computes the quantization parameters given
  132. the collected statistics.
  133. Args:
  134. dtype: dtype argument to the `quantize` node needed to implement the
  135. reference model spec.
  136. is_dynamic: indicator for whether the observer is a placeholder for dynamic quantization
  137. or static quantization
  138. """
  139. def __init__(self, dtype, is_dynamic: bool = False):
  140. super().__init__()
  141. self.dtype = dtype
  142. self.is_dynamic = is_dynamic
  143. @abstractmethod
  144. def forward(self, x):
  145. pass
  146. @abstractmethod
  147. def calculate_qparams(self, **kwargs):
  148. pass
  149. with_args = classmethod(_with_args)
  150. with_callable_args = classmethod(_with_callable_args)
  151. class UniformQuantizationObserverBase(ObserverBase):
  152. r"""Common base for all observers using uniform quantization to calculate
  153. scale and zero_point.
  154. Args:
  155. dtype: dtype argument to the `quantize` node needed to implement the
  156. reference model spec.
  157. qscheme: Quantization scheme to be used.
  158. reduce_range: Reduces the range of the quantized data type by 1 bit.
  159. This is sometimes required to avoid instruction overflow.
  160. quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
  161. quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
  162. eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.
  163. .. warning::
  164. :attr:`dtype` can only take ``torch.qint8`` or ``torch.quint8``.
  165. or `torch.int8` or `torch.uint8`
  166. .. warning::
  167. :attr:`qscheme` can only take one of the following options:
  168. - ``torch.per_tensor_affine``
  169. - ``torch.per_tensor_symmetric``
  170. - ``torch.per_channel_affine``
  171. - ``torch.per_channel_symmetric``
  172. """
  173. # Note: the version is shared by all observer types
  174. #
  175. # Version 1/None
  176. # self
  177. #
  178. # Version 2 (base class only, does not include child class buffers)
  179. # self
  180. # |--- eps : Tensor
  181. #
  182. # Version 3
  183. # for HistogramObserver only, changed the shape of uninitialized
  184. # min_val and max_val buffers from torch.Size([0]) to torch.Size([])
  185. # for PerChannelObservers, changed the name of the buffers from min_vals
  186. # to min_val and from max_vals to max_val.
  187. _version = 3
  188. eps: torch.Tensor
  189. def __init__(
  190. self,
  191. dtype=torch.quint8,
  192. qscheme=torch.per_tensor_affine,
  193. reduce_range=False,
  194. quant_min=None,
  195. quant_max=None,
  196. factory_kwargs=None,
  197. eps=torch.finfo(torch.float32).eps,
  198. is_dynamic=False,
  199. **kwargs,
  200. ) -> None:
  201. factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
  202. super().__init__(dtype=dtype, is_dynamic=is_dynamic, **kwargs)
  203. self.qscheme = qscheme
  204. if reduce_range:
  205. warnings.warn(
  206. "Please use quant_min and quant_max to specify the range for observers. \
  207. reduce_range will be deprecated in a future release of PyTorch.",
  208. stacklevel=2,
  209. )
  210. self.reduce_range = reduce_range
  211. self.register_buffer("eps", torch.tensor([eps], **factory_kwargs))
  212. if self.qscheme not in (
  213. torch.per_tensor_affine,
  214. torch.per_tensor_symmetric,
  215. torch.per_channel_affine,
  216. torch.per_channel_symmetric,
  217. torch.per_channel_affine_float_qparams,
  218. ):
  219. raise AssertionError(
  220. "Default Observer only works for per_tensor_affine, per_tensor_symmetric, "
  221. "per_channel_affine, per_channel_symmetric and per_channel_float_qparams quantization scheme"
  222. )
  223. _ALLOWED_DTYPES = (
  224. torch.qint8,
  225. torch.quint8,
  226. torch.quint4x2,
  227. torch.qint32,
  228. torch.int8,
  229. torch.uint8,
  230. torch.int16,
  231. torch.int32,
  232. torch.float8_e5m2,
  233. torch.float8_e4m3fn,
  234. torch.uint16,
  235. )
  236. if self.dtype not in _ALLOWED_DTYPES:
  237. raise AssertionError(
  238. f"Default Observer only works for {_ALLOWED_DTYPES} data type"
  239. )
  240. self.has_customized_qrange = (quant_min is not None) and (quant_max is not None)
  241. if self.has_customized_qrange:
  242. # pyrefly: ignore [bad-argument-type]
  243. validate_qmin_qmax(quant_min, quant_max)
  244. self.quant_min, self.quant_max = calculate_qmin_qmax(
  245. # pyrefly: ignore [bad-argument-type]
  246. quant_min,
  247. # pyrefly: ignore [bad-argument-type]
  248. quant_max,
  249. self.has_customized_qrange,
  250. self.dtype,
  251. self.reduce_range,
  252. )
  253. def _load_from_state_dict(
  254. self,
  255. state_dict,
  256. prefix,
  257. local_metadata,
  258. strict,
  259. missing_keys,
  260. unexpected_keys,
  261. error_msgs,
  262. ):
  263. version = local_metadata.get("version", None)
  264. if version is None or version == 1:
  265. # eps was moved to a buffer in version 2
  266. eps = torch.tensor([torch.finfo(torch.float32).eps])
  267. state_dict[prefix + "eps"] = eps
  268. super()._load_from_state_dict(
  269. state_dict,
  270. prefix,
  271. local_metadata,
  272. strict,
  273. missing_keys,
  274. unexpected_keys,
  275. error_msgs,
  276. )
  277. @torch.jit.export
  278. def _validate_qmin_qmax(self, quant_min: int, quant_max: int) -> None:
  279. r"""Validates that the user-specified quantization range is properly initialized
  280. and within the given bound supported by the observer dtype.
  281. To accommodate lower-bit quantization with respect to the existing torch.qint8 and
  282. torch.quint8 datatypes, the user can choose to use dynamic quantization range by passing
  283. in a tuple of initial qmin and qmax values. One use case is these customized qmin and qmax
  284. values are used to calculate static estimates of the scale and zero point for aggressive lower-bit
  285. fake quantization. These estimates are compared against parameters learned through backpropagation.
  286. The related literatures for scale and zero point via backpropagation are as follows:
  287. Learned Step Size Quantization: https://openreview.net/pdf?id=rkgO66VKDS
  288. Trained Quantization Thresholds: https://arxiv.org/pdf/1903.08066.pdf
  289. """
  290. # The variable names are prefixed with "initial" because their values (qmin and qmax) might be adjusted
  291. # based on whether quantization range is reduced and the datatype (signed/unsigned) used by the observer.
  292. if not quant_min <= 0 <= quant_max:
  293. raise AssertionError("Used-specified quantization range must include 0.")
  294. if quant_min >= quant_max:
  295. raise AssertionError(
  296. "qmin must be strictly less than qmax for user-specified quantization range."
  297. )
  298. @torch.jit.export
  299. def _calculate_qparams(
  300. self, min_val: torch.Tensor, max_val: torch.Tensor
  301. ) -> tuple[torch.Tensor, torch.Tensor]:
  302. r"""Calculates the quantization parameters, given min and max
  303. value tensors. Works for both per tensor and per channel cases
  304. Args:
  305. min_val: Minimum values per channel
  306. max_val: Maximum values per channel
  307. Returns:
  308. scales: Scales tensor of shape (#channels,)
  309. zero_points: Zero points tensor of shape (#channels,)
  310. """
  311. # Functionally equivalent to 'determine_qparams' in utils.py. Observers must be torchscriptable however and qscheme
  312. # as far as I can tell is not allowed to passed as a parameter in torchscript functions. This makes refactoring observer
  313. # to use this utility a massive pain and very gross. For now Im opting just to duplicate as this code
  314. # seems unlikely to change (last update over 1 year ago) and when torchscript is fully deprecated we can refactor.
  315. # TODO(jakeszwe, jerryzh168)
  316. if not check_min_max_valid(min_val, max_val):
  317. return torch.tensor([1.0], device=min_val.device.type), torch.tensor(
  318. [0], device=min_val.device.type
  319. )
  320. quant_min, quant_max = self.quant_min, self.quant_max
  321. min_val_neg = torch.min(min_val, torch.zeros_like(min_val))
  322. max_val_pos = torch.max(max_val, torch.zeros_like(max_val))
  323. device = min_val_neg.device
  324. scale = torch.ones(min_val_neg.size(), dtype=torch.float32, device=device)
  325. zero_point = torch.zeros(min_val_neg.size(), dtype=torch.int64, device=device)
  326. if (
  327. self.qscheme == torch.per_tensor_symmetric
  328. or self.qscheme == torch.per_channel_symmetric
  329. ):
  330. max_val_pos = torch.max(-min_val_neg, max_val_pos)
  331. scale = max_val_pos / (float(quant_max - quant_min) / 2)
  332. scale = torch.max(scale, self.eps)
  333. if self.dtype in [torch.quint8, torch.uint8]:
  334. if self.has_customized_qrange:
  335. # When customized quantization range is used, down-rounded midpoint of the range is chosen.
  336. zero_point = zero_point.new_full(
  337. zero_point.size(), (quant_min + quant_max) // 2
  338. )
  339. else:
  340. zero_point = zero_point.new_full(zero_point.size(), 128)
  341. elif self.dtype == torch.uint16:
  342. zero_point = zero_point.new_full(zero_point.size(), 2**15)
  343. elif self.qscheme == torch.per_channel_affine_float_qparams:
  344. scale = (max_val - min_val) / float(quant_max - quant_min)
  345. scale = torch.where(scale > self.eps, scale, torch.ones_like(scale))
  346. # We use the quantize function
  347. # xq = Round(Xf * inv_scale + zero_point),
  348. # setting zero_point to (-1 * min *inv_scale) we get
  349. # Xq = Round((Xf - min) * inv_scale)
  350. zero_point = -1 * min_val / scale
  351. else:
  352. scale = (max_val_pos - min_val_neg) / float(quant_max - quant_min)
  353. scale = torch.max(scale, self.eps)
  354. zero_point = quant_min - torch.round(min_val_neg / scale).to(torch.int)
  355. zero_point = torch.clamp(zero_point, quant_min, quant_max)
  356. # For scalar values, cast them to Tensors of size 1 to keep the shape
  357. # consistent with default values in FakeQuantize.
  358. if len(scale.shape) == 0:
  359. # TODO: switch to scale.item() after adding JIT support
  360. scale = torch.tensor([float(scale)], dtype=scale.dtype, device=device)
  361. if len(zero_point.shape) == 0:
  362. # TODO: switch to zero_point.item() after adding JIT support
  363. zero_point = torch.tensor(
  364. [int(zero_point)], dtype=zero_point.dtype, device=device
  365. )
  366. if self.qscheme == torch.per_channel_affine_float_qparams:
  367. zero_point = torch.tensor(
  368. [float(zero_point)], dtype=zero_point.dtype, device=device
  369. )
  370. return scale, zero_point
  371. @torch.jit.export
  372. def reset_min_max_vals(self):
  373. raise NotImplementedError("Cannot reset min/max values in the given observer.")
  374. # Originally, this class was called `_ObserverBase`. Keeping the old name around
  375. # for backwards compatibility.
  376. # TODO(after v1.13): delete this
  377. _ObserverBase = UniformQuantizationObserverBase
  378. class MinMaxObserver(UniformQuantizationObserverBase):
  379. r"""Observer module for computing the quantization parameters based on the
  380. running min and max values.
  381. This observer uses the tensor min/max statistics to compute the quantization
  382. parameters. The module records the running minimum and maximum of incoming
  383. tensors, and uses this statistic to compute the quantization parameters.
  384. Args:
  385. dtype: dtype argument to the `quantize` node needed to implement the
  386. reference model spec.
  387. qscheme: Quantization scheme to be used
  388. reduce_range: Reduces the range of the quantized data type by 1 bit
  389. quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
  390. quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
  391. eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.
  392. Given running min/max as :math:`x_\text{min}` and :math:`x_\text{max}`,
  393. scale :math:`s` and zero point :math:`z` are computed as:
  394. The running minimum/maximum :math:`x_\text{min/max}` is computed as:
  395. .. math::
  396. \begin{array}{ll}
  397. x_\text{min} &= \begin{cases}
  398. \min(X) & \text{if~}x_\text{min} = \text{None} \\
  399. \min\left(x_\text{min}, \min(X)\right) & \text{otherwise}
  400. \end{cases}\\
  401. x_\text{max} &= \begin{cases}
  402. \max(X) & \text{if~}x_\text{max} = \text{None} \\
  403. \max\left(x_\text{max}, \max(X)\right) & \text{otherwise}
  404. \end{cases}\\
  405. \end{array}
  406. where :math:`X` is the observed tensor.
  407. The scale :math:`s` and zero point :math:`z` are then computed as:
  408. .. math::
  409. \begin{aligned}
  410. \text{if Symmetric:}&\\
  411. &s = 2 \max(|x_\text{min}|, x_\text{max}) /
  412. \left( Q_\text{max} - Q_\text{min} \right) \\
  413. &z = \begin{cases}
  414. 0 & \text{if dtype is qint8} \\
  415. 128 & \text{otherwise}
  416. \end{cases}\\
  417. \text{Otherwise:}&\\
  418. &s = \left( x_\text{max} - x_\text{min} \right ) /
  419. \left( Q_\text{max} - Q_\text{min} \right ) \\
  420. &z = Q_\text{min} - \text{round}(x_\text{min} / s)
  421. \end{aligned}
  422. where :math:`Q_\text{min}` and :math:`Q_\text{max}` are the minimum and
  423. maximum of the quantized data type.
  424. .. warning:: :attr:`dtype` can only take ``torch.qint8`` or ``torch.quint8``.
  425. .. note:: If the running minimum equals to the running maximum, the scale
  426. and zero_point are set to 1.0 and 0.
  427. """
  428. min_val: torch.Tensor
  429. max_val: torch.Tensor
  430. def __init__(
  431. self,
  432. dtype=torch.quint8,
  433. qscheme=torch.per_tensor_affine,
  434. reduce_range=False,
  435. quant_min=None,
  436. quant_max=None,
  437. factory_kwargs=None,
  438. eps=torch.finfo(torch.float32).eps,
  439. is_dynamic=False,
  440. **kwargs,
  441. ) -> None:
  442. if not is_per_tensor(qscheme):
  443. raise NotImplementedError(
  444. "MinMaxObserver's qscheme only support torch.per_tensor_symmetric \
  445. and torch.per_tensor_affine."
  446. )
  447. # TODO: MinMaxObserver by itself doesn't support dynamic quantization, but
  448. # if it's inherited by MovingAverageObserver, and averaging_constant is 1, it
  449. # supports dynamic quantization, we may need to better error checking here
  450. # For x86 quantized kernels, we need to ensure that the vpmaddubsw
  451. # instruction does not overflow. We allow for a reduce_range argument to
  452. # observers that reduces the quantized range to (0,127) or (-64, 63).
  453. # For more details see aten/src/ATen/native/quantized/cpu/qconv.cpp
  454. # This is not an optimal choice for non x86 backends as it loses a bit
  455. # of precision for activations.
  456. super().__init__(
  457. dtype=dtype,
  458. qscheme=qscheme,
  459. reduce_range=reduce_range,
  460. quant_min=quant_min,
  461. quant_max=quant_max,
  462. factory_kwargs=factory_kwargs,
  463. eps=eps,
  464. is_dynamic=is_dynamic,
  465. **kwargs,
  466. )
  467. factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
  468. self.register_buffer("min_val", torch.tensor(float("inf"), **factory_kwargs))
  469. self.register_buffer("max_val", torch.tensor(float("-inf"), **factory_kwargs))
  470. if (
  471. self.qscheme == torch.per_tensor_symmetric
  472. and self.reduce_range
  473. and self.dtype == torch.quint8
  474. ):
  475. raise NotImplementedError(
  476. "Cannot reduce range for symmetric \
  477. quantization for quint8"
  478. )
  479. def forward(self, x_orig):
  480. r"""Records the running minimum and maximum of ``x``."""
  481. if x_orig.numel() == 0:
  482. return x_orig
  483. x = x_orig.detach() # avoid keeping autograd tape
  484. x = x.to(self.min_val.dtype)
  485. min_val_cur, max_val_cur = torch.aminmax(x)
  486. min_val = torch.min(min_val_cur, self.min_val)
  487. max_val = torch.max(max_val_cur, self.max_val)
  488. self.min_val.copy_(min_val)
  489. self.max_val.copy_(max_val)
  490. return x_orig
  491. @torch.jit.export
  492. def calculate_qparams(self): # type: ignore[override]
  493. r"""Calculates the quantization parameters."""
  494. return self._calculate_qparams(self.min_val, self.max_val)
  495. @torch.jit.export
  496. def extra_repr(self):
  497. return f"min_val={self.min_val}, max_val={self.max_val}"
  498. @torch.jit.export
  499. def reset_min_max_vals(self):
  500. """Resets the min/max values."""
  501. self.min_val.copy_(torch.tensor(float("inf")))
  502. self.max_val.copy_(torch.tensor(float("-inf")))
  503. class MovingAverageMinMaxObserver(MinMaxObserver):
  504. r"""Observer module for computing the quantization parameters based on the
  505. moving average of the min and max values.
  506. This observer computes the quantization parameters based on the moving
  507. averages of minimums and maximums of the incoming tensors. The module
  508. records the average minimum and maximum of incoming tensors, and uses this
  509. statistic to compute the quantization parameters.
  510. Args:
  511. averaging_constant: Averaging constant for min/max.
  512. dtype: dtype argument to the `quantize` node needed to implement the
  513. reference model spec.
  514. qscheme: Quantization scheme to be used
  515. reduce_range: Reduces the range of the quantized data type by 1 bit
  516. quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
  517. quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
  518. eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.
  519. The moving average min/max is computed as follows
  520. .. math::
  521. \begin{array}{ll}
  522. x_\text{min} = \begin{cases}
  523. \min(X) & \text{if~}x_\text{min} = \text{None} \\
  524. (1 - c) x_\text{min} + c \min(X) & \text{otherwise}
  525. \end{cases}\\
  526. x_\text{max} = \begin{cases}
  527. \max(X) & \text{if~}x_\text{max} = \text{None} \\
  528. (1 - c) x_\text{max} + c \max(X) & \text{otherwise}
  529. \end{cases}\\
  530. \end{array}
  531. where :math:`x_\text{min/max}` is the running average min/max, :math:`X` is
  532. is the incoming tensor, and :math:`c` is the ``averaging_constant``.
  533. The scale and zero point are then computed as in
  534. :class:`~torch.ao.quantization.observer.MinMaxObserver`.
  535. .. note:: Only works with ``torch.per_tensor_affine`` quantization scheme.
  536. .. note:: If the running minimum equals to the running maximum, the scale
  537. and zero_point are set to 1.0 and 0.
  538. """
  539. def __init__(
  540. self,
  541. averaging_constant=0.01,
  542. dtype=torch.quint8,
  543. qscheme=torch.per_tensor_affine,
  544. reduce_range=False,
  545. quant_min=None,
  546. quant_max=None,
  547. eps=torch.finfo(torch.float32).eps,
  548. is_dynamic=False,
  549. **kwargs,
  550. ) -> None:
  551. if not is_per_tensor(qscheme):
  552. raise NotImplementedError(
  553. f"MovingAverageMinMaxObserver's qscheme only support \
  554. torch.per_tensor_symmetric and torch.per_tensor_affine. \
  555. but got: {qscheme}"
  556. )
  557. self.averaging_constant = averaging_constant
  558. if is_dynamic and self.averaging_constant != 1:
  559. raise NotImplementedError(
  560. "MovingAverageMinMaxObserver doesn't support dynamic quantization for "
  561. f"averaging constant of {self.averaging_constant}"
  562. )
  563. super().__init__(
  564. dtype=dtype,
  565. qscheme=qscheme,
  566. reduce_range=reduce_range,
  567. quant_min=quant_min,
  568. quant_max=quant_max,
  569. eps=eps,
  570. is_dynamic=is_dynamic,
  571. **kwargs,
  572. )
  573. def forward(self, x_orig):
  574. if x_orig.numel() == 0:
  575. return x_orig
  576. x = x_orig.detach() # avoid keeping autograd tape
  577. x = x.to(self.min_val.dtype)
  578. min_val = self.min_val
  579. max_val = self.max_val
  580. if min_val == float("inf") and max_val == float("-inf"):
  581. min_val, max_val = torch.aminmax(x)
  582. else:
  583. min_val_cur, max_val_cur = torch.aminmax(x)
  584. min_val = min_val + self.averaging_constant * (min_val_cur - min_val)
  585. max_val = max_val + self.averaging_constant * (max_val_cur - max_val)
  586. self.min_val.copy_(min_val)
  587. self.max_val.copy_(max_val)
  588. return x_orig
  589. class PerChannelMinMaxObserver(UniformQuantizationObserverBase):
  590. r"""Observer module for computing the quantization parameters based on the
  591. running per channel min and max values.
  592. This observer uses the tensor min/max statistics to compute the per channel
  593. quantization parameters. The module records the running minimum and maximum
  594. of incoming tensors, and uses this statistic to compute the quantization
  595. parameters.
  596. Args:
  597. ch_axis: Channel axis
  598. dtype: dtype argument to the `quantize` node needed to implement the
  599. reference model spec.
  600. qscheme: Quantization scheme to be used
  601. reduce_range: Reduces the range of the quantized data type by 1 bit
  602. quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
  603. quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
  604. eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.
  605. The quantization parameters are computed the same way as in
  606. :class:`~torch.ao.quantization.observer.MinMaxObserver`, with the difference
  607. that the running min/max values are stored per channel.
  608. Scales and zero points are thus computed per channel as well.
  609. .. note:: If the running minimum equals to the running maximum, the scales
  610. and zero_points are set to 1.0 and 0.
  611. """
  612. min_val: torch.Tensor
  613. max_val: torch.Tensor
  614. def __init__(
  615. self,
  616. ch_axis=0,
  617. dtype=torch.quint8,
  618. qscheme=torch.per_channel_affine,
  619. reduce_range=False,
  620. quant_min=None,
  621. quant_max=None,
  622. factory_kwargs=None,
  623. eps=torch.finfo(torch.float32).eps,
  624. is_dynamic=False,
  625. **kwargs,
  626. ) -> None:
  627. if not is_per_channel(qscheme):
  628. raise NotImplementedError(
  629. "PerChannelMinMaxObserver's qscheme only support \
  630. torch.per_channel_symmetric, torch.per_channel_affine and torch.per_channel_affine_float_qparams."
  631. )
  632. if is_dynamic:
  633. raise NotImplementedError(
  634. "PerChannelMinMaxObserver doesn't support dynamic quantization"
  635. )
  636. super().__init__(
  637. dtype=dtype,
  638. qscheme=qscheme,
  639. reduce_range=reduce_range,
  640. quant_min=quant_min,
  641. quant_max=quant_max,
  642. factory_kwargs=factory_kwargs,
  643. eps=eps,
  644. is_dynamic=is_dynamic,
  645. **kwargs,
  646. )
  647. factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
  648. self.ch_axis = ch_axis
  649. self.register_buffer("min_val", torch.tensor([], **factory_kwargs))
  650. self.register_buffer("max_val", torch.tensor([], **factory_kwargs))
  651. if (
  652. self.qscheme == torch.per_channel_symmetric
  653. and self.reduce_range
  654. and self.dtype == torch.quint8
  655. ):
  656. raise NotImplementedError(
  657. "Cannot reduce range for symmetric quantization for quint8"
  658. )
  659. def forward(self, x_orig):
  660. return self._forward(x_orig)
  661. def _forward(self, x_orig):
  662. if x_orig.numel() == 0:
  663. return x_orig
  664. x = x_orig.detach() # avoid keeping autograd tape
  665. min_val = self.min_val
  666. max_val = self.max_val
  667. x_dim = x.size()
  668. new_axis_list = [i for i in range(len(x_dim))] # noqa: C416
  669. new_axis_list[self.ch_axis] = 0
  670. new_axis_list[0] = self.ch_axis
  671. y = x.permute(new_axis_list)
  672. # Need to match dtype of min/max because the updates to buffers
  673. # are done in place and types need to match for comparisons
  674. y = y.to(self.min_val.dtype)
  675. y = torch.flatten(y, start_dim=1)
  676. if min_val.numel() == 0 or max_val.numel() == 0:
  677. min_val, max_val = torch.aminmax(y, dim=1)
  678. else:
  679. min_val_cur, max_val_cur = torch.aminmax(y, dim=1)
  680. min_val = torch.min(min_val_cur, min_val)
  681. max_val = torch.max(max_val_cur, max_val)
  682. self.min_val.resize_(min_val.shape)
  683. self.max_val.resize_(max_val.shape)
  684. self.min_val.copy_(min_val)
  685. self.max_val.copy_(max_val)
  686. return x_orig
  687. @torch.jit.export
  688. def calculate_qparams(self): # type: ignore[override]
  689. return self._calculate_qparams(self.min_val, self.max_val)
  690. def extra_repr(self):
  691. return f"min_val={self.min_val}, max_val={self.max_val}"
  692. def _load_from_state_dict(
  693. self,
  694. state_dict: dict[str, Any],
  695. prefix: str,
  696. local_metadata: dict[str, torch.Tensor],
  697. strict: bool,
  698. missing_keys: list[str],
  699. unexpected_keys: list[str],
  700. error_msgs: list[str],
  701. ):
  702. version = local_metadata.get("version")
  703. if version is not None and version < 3:
  704. local_state = ["min_vals", "max_vals"]
  705. expected_min_name = "min_vals"
  706. expected_max_name = "max_vals"
  707. else:
  708. local_state = ["min_val", "max_val"]
  709. expected_min_name = "min_val"
  710. expected_max_name = "max_val"
  711. for name in local_state:
  712. key = prefix + name
  713. if key in state_dict:
  714. val = state_dict[key]
  715. # Custom handling to allow loading min_val or max_val
  716. # of size N into uninitialized buffers of size 0. The
  717. # buffers are resized here, and the values are copied in
  718. # the default state_dict loading code of the parent.
  719. if name == expected_min_name:
  720. self.min_val.resize_(val.shape)
  721. elif name == expected_max_name:
  722. self.max_val.resize_(val.shape)
  723. else:
  724. warnings.warn(
  725. f"Observer load_from_state_dict got unexpected name {name}",
  726. stacklevel=2,
  727. )
  728. # For torchscript module we need to update the attributes here since we do not
  729. # call the `_load_from_state_dict` function defined module.py
  730. if torch.jit.is_scripting():
  731. if name == expected_min_name:
  732. self.min_val.copy_(val)
  733. elif name == expected_max_name:
  734. self.max_val.copy_(val)
  735. else:
  736. warnings.warn(
  737. f"Observer load_from_state_dict got unexpected name {name}",
  738. stacklevel=2,
  739. )
  740. elif strict:
  741. missing_keys.append(key)
  742. if not torch.jit.is_scripting():
  743. super()._load_from_state_dict(
  744. state_dict,
  745. prefix,
  746. local_metadata,
  747. False,
  748. missing_keys,
  749. unexpected_keys,
  750. error_msgs,
  751. )
  752. def _load_from_state_dict_script(
  753. self,
  754. state_dict: dict[str, Any],
  755. prefix: str,
  756. local_metadata: dict[str, torch.Tensor],
  757. strict: bool,
  758. missing_keys: list[str],
  759. unexpected_keys: list[str],
  760. error_msgs: list[str],
  761. ):
  762. self._load_from_state_dict(
  763. state_dict,
  764. prefix,
  765. local_metadata,
  766. strict,
  767. missing_keys,
  768. unexpected_keys,
  769. error_msgs,
  770. )
  771. @torch.jit.export
  772. def reset_min_max_vals(self):
  773. """Resets the min/max values."""
  774. # This used to be torch.ones but that does not work because
  775. # JIT compiler can optimize it via common subexpression elimination
  776. # in which case both min_val and max_val point to the same tensor.
  777. self.min_val = torch.rand(
  778. 0,
  779. )
  780. self.max_val = torch.rand(
  781. 0,
  782. )
  783. class MovingAveragePerChannelMinMaxObserver(PerChannelMinMaxObserver):
  784. r"""Observer module for computing the quantization parameters based on the
  785. running per channel min and max values.
  786. This observer uses the tensor min/max statistics to compute the per channel
  787. quantization parameters. The module records the running minimum and maximum
  788. of incoming tensors, and uses this statistic to compute the quantization
  789. parameters.
  790. Args:
  791. averaging_constant: Averaging constant for min/max.
  792. ch_axis: Channel axis
  793. dtype: Quantized data type
  794. qscheme: Quantization scheme to be used
  795. reduce_range: Reduces the range of the quantized data type by 1 bit
  796. quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
  797. quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
  798. eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.
  799. The quantization parameters are computed the same way as in
  800. :class:`~torch.ao.quantization.observer.MovingAverageMinMaxObserver`, with the
  801. difference that the running min/max values are stored per channel.
  802. Scales and zero points are thus computed per channel as well.
  803. .. note:: If the running minimum equals to the running maximum, the scales
  804. and zero_points are set to 1.0 and 0.
  805. """
  806. def __init__(
  807. self,
  808. averaging_constant=0.01,
  809. ch_axis=0,
  810. dtype=torch.quint8,
  811. qscheme=torch.per_channel_affine,
  812. reduce_range=False,
  813. quant_min=None,
  814. quant_max=None,
  815. eps=torch.finfo(torch.float32).eps,
  816. is_dynamic=False,
  817. **kwargs,
  818. ) -> None:
  819. if not is_per_channel(qscheme):
  820. raise NotImplementedError(
  821. "MovingAveragePerChannelMinMaxObserver's qscheme only support \
  822. torch.per_channel_symmetric, torch.per_channel_affine and torch.per_channel_affine_float_qparams."
  823. )
  824. if is_dynamic:
  825. raise NotImplementedError(
  826. "MovingAveragePerChannelMinMaxObserver doesn't support dynamic quantization"
  827. )
  828. super().__init__(
  829. ch_axis=ch_axis,
  830. dtype=dtype,
  831. qscheme=qscheme,
  832. reduce_range=reduce_range,
  833. quant_min=quant_min,
  834. quant_max=quant_max,
  835. eps=eps,
  836. is_dynamic=is_dynamic,
  837. **kwargs,
  838. )
  839. self.averaging_constant = averaging_constant
  840. def forward(self, x_orig):
  841. if x_orig.numel() == 0:
  842. return x_orig
  843. x = x_orig.detach() # avoid keeping autograd tape
  844. x = x.to(self.min_val.dtype)
  845. min_val = self.min_val
  846. max_val = self.max_val
  847. x_dim = x.size()
  848. new_axis_list = [i for i in range(len(x_dim))] # noqa: C416
  849. new_axis_list[self.ch_axis] = 0
  850. new_axis_list[0] = self.ch_axis
  851. y = x.permute(new_axis_list)
  852. y = torch.flatten(y, start_dim=1)
  853. if min_val.numel() == 0 or max_val.numel() == 0:
  854. min_val, max_val = torch.aminmax(y, dim=1)
  855. else:
  856. min_val_cur, max_val_cur = torch.aminmax(y, dim=1)
  857. min_val = min_val + self.averaging_constant * (min_val_cur - min_val)
  858. max_val = max_val + self.averaging_constant * (max_val_cur - max_val)
  859. self.min_val.resize_(min_val.shape)
  860. self.max_val.resize_(max_val.shape)
  861. self.min_val.copy_(min_val)
  862. self.max_val.copy_(max_val)
  863. return x_orig
  864. class HistogramObserver(UniformQuantizationObserverBase):
  865. r"""
  866. The module records the running histogram of tensor values along with
  867. min/max values. ``calculate_qparams`` will calculate scale and zero_point.
  868. Args:
  869. bins: Number of bins to use for the histogram
  870. dtype: dtype argument to the `quantize` node needed to implement the
  871. reference model spec
  872. qscheme: Quantization scheme to be used
  873. reduce_range: Reduces the range of the quantized data type by 1 bit
  874. eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.
  875. The scale and zero point are computed as follows:
  876. 1. Create the histogram of the incoming inputs.
  877. The histogram is computed continuously, and the ranges per bin change
  878. with every new tensor observed.
  879. 2. Search the distribution in the histogram for optimal min/max values.
  880. The search for the min/max values ensures the minimization of the
  881. quantization error with respect to the floating point model.
  882. 3. Compute the scale and zero point the same way as in the
  883. :class:`~torch.ao.quantization.MinMaxObserver`
  884. """
  885. histogram: torch.Tensor
  886. min_val: torch.Tensor
  887. max_val: torch.Tensor
  888. def __init__(
  889. self,
  890. bins: int = 2048,
  891. dtype: torch.dtype = torch.quint8,
  892. qscheme=torch.per_tensor_affine,
  893. reduce_range=False,
  894. quant_min=None,
  895. quant_max=None,
  896. factory_kwargs=None,
  897. eps=torch.finfo(torch.float32).eps,
  898. is_dynamic=False,
  899. **kwargs,
  900. ) -> None:
  901. if not is_per_tensor(qscheme):
  902. raise NotImplementedError(
  903. "HistogramObserver's qscheme only support torch.per_tensor_symmetric \
  904. and torch.per_tensor_affine."
  905. )
  906. if is_dynamic:
  907. raise NotImplementedError(
  908. "HistogramObserver doesn't support dynamic quantization"
  909. )
  910. # bins: The number of bins used for histogram calculation.
  911. super().__init__(
  912. dtype=dtype,
  913. qscheme=qscheme,
  914. reduce_range=reduce_range,
  915. quant_min=quant_min,
  916. quant_max=quant_max,
  917. factory_kwargs=factory_kwargs,
  918. eps=eps,
  919. is_dynamic=is_dynamic,
  920. **kwargs,
  921. )
  922. factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
  923. self.bins = bins
  924. self.register_buffer("histogram", torch.zeros(self.bins, **factory_kwargs))
  925. self.register_buffer("min_val", torch.tensor(float("inf"), **factory_kwargs))
  926. self.register_buffer("max_val", torch.tensor(float("-inf"), **factory_kwargs))
  927. self.dst_nbins = 2 ** torch.iinfo(self.dtype).bits
  928. self.upsample_rate = (
  929. 16 # used to reduce quantization errors when upscaling histogram
  930. )
  931. def _get_norm(
  932. self, delta_begin: torch.Tensor, delta_end: torch.Tensor, density: torch.Tensor
  933. ) -> torch.Tensor:
  934. r"""
  935. Compute the norm of the values uniformaly distributed between
  936. delta_begin and delta_end.
  937. Currently only L2 norm is supported.
  938. norm = density * (integral_{begin, end} x^2)
  939. = density * (end^3 - begin^3) / 3
  940. """
  941. norm = (
  942. delta_end * delta_end * delta_end - delta_begin * delta_begin * delta_begin
  943. ) / 3
  944. return density * norm
  945. def _compute_quantization_error(self, next_start_bin: int, next_end_bin: int):
  946. r"""
  947. Compute the quantization error if we use start_bin to end_bin as the
  948. min and max to do the quantization.
  949. """
  950. bin_width = (self.max_val.item() - self.min_val.item()) / self.bins
  951. dst_bin_width = bin_width * (next_end_bin - next_start_bin + 1) / self.dst_nbins
  952. if dst_bin_width == 0.0:
  953. return 0.0
  954. src_bin = torch.arange(self.bins, device=self.histogram.device)
  955. # distances from the beginning of first dst_bin to the beginning and
  956. # end of src_bin
  957. src_bin_begin = (src_bin - next_start_bin) * bin_width
  958. src_bin_end = src_bin_begin + bin_width
  959. # which dst_bins the beginning and end of src_bin belong to?
  960. dst_bin_of_begin = torch.clamp(
  961. torch.div(src_bin_begin, dst_bin_width, rounding_mode="floor"),
  962. 0,
  963. self.dst_nbins - 1,
  964. )
  965. dst_bin_of_begin_center = (dst_bin_of_begin + 0.5) * dst_bin_width
  966. dst_bin_of_end = torch.clamp(
  967. torch.div(src_bin_end, dst_bin_width, rounding_mode="floor"),
  968. 0,
  969. self.dst_nbins - 1,
  970. )
  971. density = self.histogram / bin_width
  972. norm = torch.zeros(self.bins, device=self.histogram.device)
  973. delta_begin = src_bin_begin - dst_bin_of_begin_center
  974. delta_end = dst_bin_width / 2
  975. norm += self._get_norm(
  976. delta_begin,
  977. torch.ones(self.bins, device=self.histogram.device) * delta_end,
  978. density,
  979. )
  980. norm += (dst_bin_of_end - dst_bin_of_begin - 1) * self._get_norm(
  981. torch.tensor(-dst_bin_width / 2), torch.tensor(dst_bin_width / 2), density
  982. )
  983. dst_bin_of_end_center = dst_bin_of_end * dst_bin_width + dst_bin_width / 2
  984. delta_begin = -dst_bin_width / 2
  985. delta_end = src_bin_end - dst_bin_of_end_center
  986. norm += self._get_norm(torch.tensor(delta_begin), delta_end, density)
  987. return norm.sum().item()
  988. def _non_linear_param_search(self) -> tuple[torch.Tensor, torch.Tensor]:
  989. r"""Non-linear parameter search.
  990. An approximation for L2 error minimization for selecting min/max.
  991. By selecting new min/max, we filter out outliers in input distribution.
  992. This follows the implementation of NormMinimization::NonlinearQuantizationParamsSearch in
  993. caffe2/quantization/server/norm_minimization.cc
  994. """
  995. if self.histogram.size()[0] != self.bins:
  996. raise AssertionError("bins mismatch")
  997. bin_width = (self.max_val - self.min_val) / self.bins
  998. # cumulative sum
  999. total = torch.sum(self.histogram).item()
  1000. cSum = torch.cumsum(self.histogram, dim=0)
  1001. stepsize = 1e-5 # granularity
  1002. alpha = 0.0 # lower bound
  1003. beta = 1.0 # upper bound
  1004. start_bin = 0
  1005. end_bin = self.bins - 1
  1006. norm_min = float("inf")
  1007. while alpha < beta:
  1008. # Find the next step
  1009. next_alpha = alpha + stepsize
  1010. next_beta = beta - stepsize
  1011. # find the left and right bins between the quantile bounds
  1012. l = start_bin
  1013. r = end_bin
  1014. while l < end_bin and cSum[l] < next_alpha * total:
  1015. l = l + 1
  1016. while r > start_bin and cSum[r] > next_beta * total:
  1017. r = r - 1
  1018. # decide the next move
  1019. next_start_bin = start_bin
  1020. next_end_bin = end_bin
  1021. if (l - start_bin) > (end_bin - r):
  1022. # move the start bin
  1023. next_start_bin = l
  1024. alpha = next_alpha
  1025. else:
  1026. # move the end bin
  1027. next_end_bin = r
  1028. beta = next_beta
  1029. if next_start_bin == start_bin and next_end_bin == end_bin:
  1030. continue
  1031. # calculate the quantization error using next_start_bin and next_end_bin
  1032. norm = self._compute_quantization_error(next_start_bin, next_end_bin)
  1033. if norm > norm_min:
  1034. break
  1035. norm_min = norm
  1036. start_bin = next_start_bin
  1037. end_bin = next_end_bin
  1038. new_min = self.min_val + bin_width * start_bin
  1039. new_max = self.min_val + bin_width * (end_bin + 1)
  1040. return new_min, new_max
  1041. def _upscale_histogram(
  1042. self,
  1043. histogram: torch.Tensor,
  1044. orig_min: torch.Tensor,
  1045. orig_max: torch.Tensor,
  1046. update_min: torch.Tensor,
  1047. update_max: torch.Tensor,
  1048. ):
  1049. # this turns the histogram into a more fine-coarsed histogram to reduce
  1050. # bin quantization errors
  1051. histogram = histogram.repeat_interleave(self.upsample_rate) / self.upsample_rate
  1052. bin_size = (orig_max - orig_min) / (self.bins * self.upsample_rate)
  1053. mid_points_histogram = (
  1054. torch.linspace(
  1055. orig_min,
  1056. orig_max,
  1057. self.bins * self.upsample_rate + 1,
  1058. device=orig_min.device,
  1059. )[:-1].to(histogram.device)
  1060. + 0.5 * bin_size
  1061. )
  1062. boundaries_new_histogram = torch.linspace(
  1063. update_min, update_max, self.bins + 1, device=update_min.device
  1064. ).to(histogram.device)
  1065. # this maps the mid-points of the histogram to the new histogram's space
  1066. bucket_assignments = (
  1067. torch.bucketize(mid_points_histogram, boundaries_new_histogram, right=True)
  1068. - 1
  1069. )
  1070. # this then maps the histogram mid-points in the new space, weighted by the original histogram's values
  1071. # this is just the old histogram in the new histogram's space
  1072. # In case due to numerical issues the values land higher/lower than the maximum/minimum
  1073. bucket_assignments[bucket_assignments >= self.bins] = self.bins - 1
  1074. bucket_assignments[bucket_assignments < 0] = 0
  1075. update_histogram = torch.bincount(
  1076. bucket_assignments, weights=histogram, minlength=self.bins
  1077. )
  1078. return update_histogram
  1079. def _combine_histograms(
  1080. self,
  1081. orig_hist: torch.Tensor,
  1082. orig_min: torch.Tensor,
  1083. orig_max: torch.Tensor,
  1084. update_hist: torch.Tensor,
  1085. update_min: torch.Tensor,
  1086. update_max: torch.Tensor,
  1087. ) -> torch.Tensor:
  1088. # If the new min and max are the same as the current min and max,
  1089. # we can just add the new histogram to the original histogram
  1090. if update_min == orig_min and update_max == orig_max:
  1091. return orig_hist + update_hist
  1092. # If the orig hist only has one value (i.e., the min and max are the same)
  1093. # we can just add it into new histogram
  1094. if orig_min == orig_max:
  1095. bin_value = torch.sum(orig_hist)
  1096. transformed_orig_hist = (
  1097. torch.histc(orig_min, bins=self.bins, min=update_min, max=update_max) # type: ignore[arg-type]
  1098. * bin_value
  1099. )
  1100. return transformed_orig_hist + update_hist
  1101. # We assume the update_hist is already in the target range, we will map the orig_max to it
  1102. if update_min > orig_min:
  1103. raise AssertionError("update_min must be <= orig_min")
  1104. if update_max < orig_max:
  1105. raise AssertionError("update_max must be >= orig_max")
  1106. # Now we need to turn the old_histogram, into the range of the new histogram
  1107. transformed_orig_hist = self._upscale_histogram(
  1108. orig_hist,
  1109. orig_min,
  1110. orig_max,
  1111. update_min,
  1112. update_max,
  1113. )
  1114. return update_hist + transformed_orig_hist
  1115. def reset_histogram(
  1116. self, x: torch.Tensor, min_val: torch.Tensor, max_val: torch.Tensor
  1117. ) -> None:
  1118. self.min_val.resize_(min_val.shape)
  1119. self.min_val.copy_(min_val)
  1120. self.max_val.resize_(max_val.shape)
  1121. self.max_val.copy_(max_val)
  1122. if min_val.numel() != 1 or max_val.numel() != 1:
  1123. raise AssertionError("histogram min/max values must be scalar.")
  1124. new_histogram = torch.histc(x, self.bins, min=min_val, max=max_val) # type: ignore[arg-type]
  1125. self.histogram.detach_().resize_(new_histogram.shape)
  1126. self.histogram.copy_(new_histogram)
  1127. def forward(self, x_orig: torch.Tensor) -> torch.Tensor: # pyre-ignore[14]
  1128. if x_orig.numel() == 0:
  1129. return x_orig
  1130. x = x_orig.detach()
  1131. x_min, x_max = torch.aminmax(x)
  1132. # want to ignore torch.inf since we don't actually
  1133. # want to make our quantization range infinite
  1134. # and in practice those values will be clamped
  1135. if x_min == -torch.inf or x_max == torch.inf:
  1136. warnings.warn(
  1137. "torch.inf detected in input tensor, ignoring input", stacklevel=2
  1138. )
  1139. x = x[x.abs() != torch.inf]
  1140. if x.numel() == 0:
  1141. return x_orig
  1142. x_min, x_max = torch.aminmax(x)
  1143. current_min = self.min_val
  1144. current_max = self.max_val
  1145. is_uninitialized = self.min_val == float("inf") or self.max_val == float("-inf")
  1146. if is_uninitialized:
  1147. self.reset_histogram(x, x_min, x_max)
  1148. else:
  1149. update_min, update_max = x_min, x_max
  1150. new_min = torch.min(current_min, update_min)
  1151. new_max = torch.max(current_max, update_max)
  1152. # TODO: For some reason, this is required for it to pass torchscript test
  1153. # new_min and new_max should already have requires_grad set to False
  1154. new_min, new_max = new_min.detach(), new_max.detach()
  1155. update_histogram = torch.histc(
  1156. x,
  1157. self.bins,
  1158. min=new_min, # type: ignore[arg-type]
  1159. max=new_max, # type: ignore[arg-type]
  1160. ).to(self.histogram.device)
  1161. if new_min == current_min and new_max == current_max:
  1162. combined_histogram = self.histogram + update_histogram
  1163. self.histogram.detach_().resize_(combined_histogram.shape)
  1164. self.histogram.copy_(combined_histogram)
  1165. else:
  1166. combined_histogram = self._combine_histograms(
  1167. self.histogram,
  1168. current_min,
  1169. current_max,
  1170. update_histogram,
  1171. new_min,
  1172. new_max,
  1173. )
  1174. self.histogram.detach_().resize_(combined_histogram.shape)
  1175. self.histogram.copy_(combined_histogram)
  1176. self.min_val.detach_().resize_(new_min.shape)
  1177. self.min_val.copy_(new_min)
  1178. self.max_val.detach_().resize_(new_max.shape)
  1179. self.max_val.copy_(new_max)
  1180. return x_orig
  1181. @torch.jit.export
  1182. def calculate_qparams(self): # type: ignore[override]
  1183. is_uninitialized = self.min_val == float("inf") and self.max_val == float(
  1184. "-inf"
  1185. )
  1186. if is_uninitialized:
  1187. warnings.warn(
  1188. "must run observer before calling calculate_qparams.\
  1189. Returning default scale and zero point ",
  1190. stacklevel=2,
  1191. )
  1192. return torch.tensor([1.0], device=self.min_val.device.type), torch.tensor(
  1193. [0], device=self.min_val.device.type
  1194. )
  1195. if self.bins != len(self.histogram):
  1196. raise AssertionError(
  1197. "The number of bins in histogram should be equal to the number of bins "
  1198. "supplied while making this observer"
  1199. )
  1200. new_min, new_max = self._non_linear_param_search()
  1201. return self._calculate_qparams(new_min, new_max)
  1202. def _save_to_state_dict(self, destination, prefix, keep_vars):
  1203. super()._save_to_state_dict(destination, prefix, keep_vars)
  1204. destination[prefix + "min_val"] = self.min_val
  1205. destination[prefix + "max_val"] = self.max_val
  1206. def _load_from_state_dict(
  1207. self,
  1208. state_dict,
  1209. prefix,
  1210. local_metadata,
  1211. strict,
  1212. missing_keys,
  1213. unexpected_keys,
  1214. error_msgs,
  1215. ):
  1216. version = local_metadata.get("version", None)
  1217. if version is None or version < 3:
  1218. # if min_val and max_val are not initialized, update their shape
  1219. # to account for the differences between v2 and v3
  1220. min_val_name, max_val_name = prefix + "min_val", prefix + "max_val"
  1221. if min_val_name in state_dict:
  1222. if state_dict[min_val_name].shape == torch.Size([0]):
  1223. state_dict[min_val_name] = torch.tensor(float("inf"))
  1224. if max_val_name in state_dict:
  1225. if state_dict[max_val_name].shape == torch.Size([0]):
  1226. state_dict[max_val_name] = torch.tensor(float("-inf"))
  1227. local_state = ["min_val", "max_val"]
  1228. for name in local_state:
  1229. key = prefix + name
  1230. if key in state_dict:
  1231. val = state_dict[key]
  1232. setattr(self, name, val)
  1233. elif strict:
  1234. missing_keys.append(key)
  1235. super()._load_from_state_dict(
  1236. state_dict,
  1237. prefix,
  1238. local_metadata,
  1239. strict,
  1240. missing_keys,
  1241. unexpected_keys,
  1242. error_msgs,
  1243. )
  1244. def extra_repr(self):
  1245. return f"min_val={self.min_val}, max_val={self.max_val}"
  1246. class FixedQParamsObserver(ObserverBase):
  1247. r"""
  1248. Observer that simulates quantize and dequantize with fixed
  1249. quantization parameters in training time. Only per tensor
  1250. quantization is supported.
  1251. Args:
  1252. `scale` (float): fixed scale for the observer
  1253. `zero_point` (int): fixed zero point for the observer
  1254. `dtype`, `qscheme`, `quant_min`, `quant_max`
  1255. """
  1256. scale: torch.Tensor
  1257. zero_point: torch.Tensor
  1258. def __init__(
  1259. self,
  1260. scale,
  1261. zero_point,
  1262. dtype=torch.quint8,
  1263. qscheme=torch.per_tensor_affine,
  1264. quant_min=0,
  1265. quant_max=255,
  1266. is_dynamic=False,
  1267. **kwargs,
  1268. ):
  1269. if is_dynamic:
  1270. raise NotImplementedError(
  1271. "FixedQParamsObserver doesn't support dynamic quantization"
  1272. )
  1273. super().__init__(dtype=dtype, is_dynamic=is_dynamic, **kwargs)
  1274. self.quant_min = quant_min
  1275. self.quant_max = quant_max
  1276. self.register_buffer("scale", torch.tensor([scale], dtype=torch.float))
  1277. self.register_buffer("zero_point", torch.tensor([zero_point], dtype=torch.int))
  1278. self.dtype = dtype
  1279. self.qscheme = qscheme
  1280. def forward(self, X):
  1281. return X
  1282. @torch.jit.export
  1283. def calculate_qparams(self): # type: ignore[override]
  1284. return self.scale, self.zero_point
  1285. class PlaceholderObserver(ObserverBase):
  1286. r"""
  1287. Observer that doesn't do anything and just passes its configuration to the
  1288. quantized module's ``.from_float()``.
  1289. Can be used for quantization to float16 which doesn't require determining
  1290. ranges.
  1291. Args:
  1292. dtype: dtype argument to the `quantize` node needed to implement the
  1293. reference model spec.
  1294. quant_min: minimum value in quantized domain (TODO: align behavior with other observers)
  1295. quant_max: maximum value in quantized domain
  1296. custom_op_name: (temporary) specify this observer for an operator that doesn't require any observation
  1297. (Can be used in Graph Mode Passes for special case ops).
  1298. compute_dtype (deprecated): if set, marks the future quantize function to use
  1299. dynamic quantization instead of static quantization.
  1300. This field is deprecated, use `is_dynamic=True` instead.
  1301. is_dynamic: if True, the `quantize` function in the reference model
  1302. representation taking stats from this observer instance will
  1303. use dynamic quantization.
  1304. """
  1305. def __init__(
  1306. self,
  1307. dtype=torch.float32,
  1308. custom_op_name="",
  1309. compute_dtype=None,
  1310. quant_min=None,
  1311. quant_max=None,
  1312. qscheme=None,
  1313. eps=None,
  1314. is_dynamic=False,
  1315. ) -> None:
  1316. super().__init__(dtype=dtype, is_dynamic=is_dynamic)
  1317. if qscheme is None:
  1318. qscheme = torch.per_tensor_affine
  1319. if eps is None:
  1320. eps = torch.finfo(torch.float32).eps
  1321. # dtype of input of the target operator, e.g. for dynamic quantization
  1322. # ops, the dtype will be float32
  1323. self.dtype = dtype
  1324. self.qscheme = qscheme
  1325. self.quant_min = quant_min
  1326. self.quant_max = quant_max
  1327. self.eps = eps
  1328. self.custom_op = custom_op_name
  1329. # used for configuration of computation type for dynamic quantization
  1330. if compute_dtype:
  1331. is_dynamic = True
  1332. warnings.warn(
  1333. "Please use `is_dynamic` instead of `compute_dtype`. \
  1334. `compute_dtype` will be deprecated in a future release \
  1335. of PyTorch.",
  1336. stacklevel=2,
  1337. )
  1338. def forward(self, x):
  1339. return x
  1340. @torch.jit.export
  1341. def extra_repr(self):
  1342. return f"dtype={self.dtype}, is_dynamic={self.is_dynamic}"
  1343. @torch.jit.export
  1344. def calculate_qparams(self): # type: ignore[override]
  1345. raise Exception( # noqa: TRY002
  1346. "calculate_qparams should not be called for PlaceholderObserver"
  1347. )
  1348. class RecordingObserver(ObserverBase):
  1349. r"""
  1350. The module is mainly for debug and records the tensor values during runtime.
  1351. Args:
  1352. dtype: Quantized data type
  1353. qscheme: Quantization scheme to be used
  1354. reduce_range: Reduces the range of the quantized data type by 1 bit
  1355. """
  1356. __annotations__ = {"tensor_val": list[torch.Tensor | None]}
  1357. def __init__(self, dtype=torch.quint8):
  1358. super().__init__(dtype=dtype, is_dynamic=False)
  1359. self.tensor_val = []
  1360. def forward(self, x):
  1361. self.tensor_val.append(x.clone())
  1362. return x
  1363. @torch.jit.export
  1364. def calculate_qparams(self): # type: ignore[override]
  1365. raise Exception( # noqa: TRY002
  1366. "calculate_qparams should not be called for RecordingObserver"
  1367. )
  1368. @torch.jit.export
  1369. def get_tensor_value(self):
  1370. return self.tensor_val
  1371. class NoopObserver(ObserverBase):
  1372. r"""
  1373. Observer that doesn't do anything and just passes its configuration to the
  1374. quantized module's ``.from_float()``.
  1375. Primarily used for quantization to float16 which doesn't require determining
  1376. ranges.
  1377. Args:
  1378. dtype: Quantized data type
  1379. custom_op_name: (temporary) specify this observer for an operator that doesn't require any observation
  1380. (Can be used in Graph Mode Passes for special case ops).
  1381. """
  1382. def __init__(self, dtype=torch.float16, custom_op_name="") -> None:
  1383. super().__init__(dtype=dtype, is_dynamic=False)
  1384. self.dtype = dtype
  1385. self.custom_op = custom_op_name
  1386. def forward(self, x):
  1387. return x
  1388. @torch.jit.export
  1389. def calculate_qparams(self): # type: ignore[override]
  1390. raise Exception( # noqa: TRY002
  1391. "calculate_qparams should not be called for NoopObserver"
  1392. )
  1393. class ReuseInputObserver(ObserverBase):
  1394. r"""This observer is used when we want to reuse the observer from the operator
  1395. that produces the input Tensor, typically used for operators like reshape, e.g.
  1396. ```
  1397. x0 = ...
  1398. x1 = x0.reshape()
  1399. ```
  1400. if we configure x0 to be observed by some observer, let's say MinMaxObserver,
  1401. and reshape is configured with ReuseInputObserver, we'll reuse the observer instance
  1402. for x0 for x1 (output of reshape). If x0 is not observed, we also won't observe x1.
  1403. Note: this is only enabled in FX Graph Mode Quantization
  1404. """
  1405. def __init__(self) -> None:
  1406. super().__init__(torch.quint8, is_dynamic=False)
  1407. def forward(self, x):
  1408. return x
  1409. @torch.jit.export
  1410. def calculate_qparams(self): # type: ignore[override]
  1411. raise Exception( # noqa: TRY002
  1412. "calculate_qparams should not be called for ReuseInputObserver"
  1413. )
  1414. """
  1415. # Experimental Affine Quantization Feature START
  1416. We plan to merge the following with torchao repo after we move pt2e flow to torchao
  1417. copied from https://github.com/pytorch/ao/blob/main/torchao/quantization/observer.py
  1418. """
  1419. from dataclasses import dataclass
  1420. from enum import auto, Enum
  1421. class MappingType(Enum):
  1422. """How floating point number is mapped to integer number
  1423. symmetric mapping means floating point range is symmetrically mapped to integer range
  1424. let's say we have floating point range (-3.5, 10.2) and integer range (-8, 7) (int4)
  1425. we'll use (-10.2, 10.2) as the range for floating point and map that to (-8, 7)
  1426. e.g. scale = (10.2 - (-10.2)) / (7 - (-8))
  1427. SYMMETRIC_NO_CLIPPING_ERR is a variant of symmetric mapping, where the scale is the max of smin
  1428. and smax, where smin = min_val_neg / quant_min, and smax = max_val_pos / quant_max. By calculating
  1429. smin and smax individually, there can be less round error on negative values, and no out-of-range
  1430. of all floating point values.
  1431. asymmetric mapping means we just directly map the floating point range to integer range,
  1432. for the above example, we will map (-3.5, 10.2) to (-8, 7) and calculate quantization parameter
  1433. based on this mapping
  1434. e.g. scale = (10.2 - (-3.5)) / (7 - (-8))
  1435. """
  1436. SYMMETRIC = auto()
  1437. SYMMETRIC_NO_CLIPPING_ERR = auto()
  1438. ASYMMETRIC = auto()
  1439. class ZeroPointDomain(Enum):
  1440. """Enum that indicate whether zero_point is in integer domain or floating point domain
  1441. integer domain: quantized_val = (float_val / scale) (integer) + zero_point (integer)
  1442. float domain: quantized_val = (float_val - (zero_point (float) - scale * mid_point)) / scale
  1443. none domain: quantized_val = (float_val / scale)
  1444. """
  1445. INT = auto()
  1446. FLOAT = auto()
  1447. NONE = auto()
  1448. class TorchAODType(Enum):
  1449. """
  1450. Placeholder for dtypes that do not exist in PyTorch core yet.
  1451. """
  1452. # torch.int1 to torch.int7 will be added to PyTorch 2.6
  1453. # These will remain here for BC with older PyTorch versions
  1454. INT1 = auto()
  1455. INT2 = auto()
  1456. INT3 = auto()
  1457. INT4 = auto()
  1458. INT5 = auto()
  1459. INT6 = auto()
  1460. INT7 = auto()
  1461. @dataclass(frozen=True)
  1462. class Granularity:
  1463. """
  1464. Base class for representing the granularity of quantization.
  1465. This class serves as a parent for specific granularity types used in
  1466. quantization operations, such as per-tensor or per-axis quantization.
  1467. """
  1468. @dataclass(frozen=True)
  1469. class PerBlock(Granularity):
  1470. """
  1471. Represents per-block granularity in quantization. See
  1472. :func:`~torchao.quantization.quant_primitives.quantize_affine` for docs for
  1473. `block_size`
  1474. Attributes:
  1475. block_size (Tuple[int, ...]): The size of each quantization group
  1476. """
  1477. block_size: tuple[int, ...]
  1478. @dataclass(frozen=True)
  1479. class PerTensor(Granularity):
  1480. """
  1481. Represents per-tensor granularity in quantization.
  1482. This granularity type calculates the quantization parameters
  1483. based off the entire tensor.
  1484. """
  1485. @dataclass(frozen=True)
  1486. class PerAxis(Granularity):
  1487. """
  1488. Represents per-axis granularity in quantization.
  1489. This granularity type calculates different quantization parameters
  1490. along a specified axis of the tensor.
  1491. For example if the input tensor is shape [8, 16] and axis=0, then
  1492. the quantization parameters are calculated for each row of the tensor.
  1493. Giving a total of 8 quantization parameters.
  1494. Attributes:
  1495. axis (int): The axis along which reduction is performed.
  1496. """
  1497. axis: int
  1498. @dataclass(frozen=True)
  1499. class PerGroup(Granularity):
  1500. """
  1501. Represents per-channel group granularity in quantization.
  1502. This granularity type calculates different quantization parameters
  1503. for each group of <group_size> elements.
  1504. For example if the input tensor is shape [8, 16], and the group size is 4, then
  1505. the input tensor is reshaped to [64, 4]
  1506. quantization parameters are calculated for each group of 4 elements,
  1507. giving a total of 64 quantization parameters.
  1508. Attributes:
  1509. group_size (int): The size of each quantization group
  1510. """
  1511. group_size: int
  1512. class PerRow(Granularity):
  1513. """
  1514. Represents row-wise granularity in quantization.
  1515. This is a special case of per-axis quantization and is unique to Float8 matmuls
  1516. where the input is quantized with a block_size of (1, ..., input.shape[-1]). And the weight
  1517. is quantized with a block_size of (1, weight.shape[1]).
  1518. """
  1519. class PerToken(Granularity):
  1520. """
  1521. Represents per-token granularity in quantization.
  1522. This granularity type calculates a different set of quantization parameters
  1523. for each token, which is represented as the last dimension of the tensor.
  1524. For example, if the input tensor has shape [2, 3, 4], then there are 6 tokens
  1525. with 4 elements each, and we will calculate 6 sets of quantization parameters,
  1526. one for each token.
  1527. If the input tensor has only two dimensions, e.g. [8, 16], then this is
  1528. equivalent to `PerAxis(axis=0)`, which yields 8 sets of quantization parameters.
  1529. """
  1530. def get_block_size(
  1531. input_shape: tuple[int, ...], granularity: Granularity
  1532. ) -> tuple[int, ...]:
  1533. """Get the block size based on the input shape and granularity type.
  1534. Args:
  1535. input_shape: The input tensor shape possibly more than 2 dimensions
  1536. granularity: The granularity type of the quantization
  1537. """
  1538. if not isinstance(granularity, Granularity):
  1539. raise AssertionError(
  1540. "Please provide an instance of Granularity, not subclass of it"
  1541. )
  1542. if isinstance(granularity, PerTensor):
  1543. return input_shape
  1544. elif isinstance(granularity, PerAxis):
  1545. block_size = list(input_shape)
  1546. block_size[granularity.axis] = 1
  1547. return tuple(block_size)
  1548. elif isinstance(granularity, PerRow):
  1549. return (1,) * (len(input_shape) - 1) + (input_shape[-1],)
  1550. elif isinstance(granularity, PerGroup):
  1551. if len(input_shape) != 2:
  1552. raise AssertionError(
  1553. f"Expecting input shape dim to be 2 for per group quantization, gotinput shape: {input_shape}"
  1554. )
  1555. return (1, granularity.group_size)
  1556. elif isinstance(granularity, PerToken):
  1557. block_size = [1] * len(input_shape)
  1558. block_size[-1] = input_shape[-1]
  1559. return tuple(block_size)
  1560. raise ValueError(f"Unsupported Granularity: {granularity}")
  1561. class AffineQuantizedObserverBase(ABC, torch.nn.Module):
  1562. """Observer module for affine quantization (https://github.com/pytorch/ao/tree/main/torchao/quantization#affine-quantization)
  1563. Args:
  1564. `granularity` and `block_size`: The granularity of the quantization,
  1565. must specify at least one, if both are specified `block_size` takes precedence
  1566. Current supported granularity type are `PerTensor` and `PerAxis`
  1567. other args: please see `:class:torchao.dtypes.AffineQuantizedTensor`
  1568. """
  1569. with_args = classmethod(_with_args)
  1570. def __init__(
  1571. self,
  1572. mapping_type: MappingType,
  1573. target_dtype: torch.dtype,
  1574. granularity: Granularity,
  1575. quant_min: int | None = None,
  1576. quant_max: int | None = None,
  1577. eps: float | None = None,
  1578. scale_dtype: torch.dtype | None = None,
  1579. zero_point_dtype: torch.dtype | None = None,
  1580. preserve_zero: bool = True,
  1581. zero_point_domain: ZeroPointDomain | None = ZeroPointDomain.INT,
  1582. # there could be some extra args that's ignored
  1583. **kwargs,
  1584. ):
  1585. super().__init__()
  1586. if granularity is None:
  1587. raise AssertionError("granularity is None")
  1588. self.mapping_type = mapping_type
  1589. self.target_dtype = target_dtype
  1590. self.granularity = granularity
  1591. self.quant_min = quant_min
  1592. self.quant_max = quant_max
  1593. self.eps = eps
  1594. self.scale_dtype = scale_dtype
  1595. self.zero_point_dtype = zero_point_dtype
  1596. self.preserve_zero = preserve_zero
  1597. self.zero_point_domain = zero_point_domain
  1598. # populatd during forward
  1599. self.block_size = None
  1600. self.original_dtype = None
  1601. @abstractmethod
  1602. def forward(self, input: torch.Tensor) -> torch.Tensor:
  1603. """forward function should take the input tensor
  1604. and updates internal stats and return the original input Tensor
  1605. """
  1606. @abstractmethod
  1607. def calculate_qparams(self) -> tuple[torch.Tensor, torch.Tensor]:
  1608. """Calculate quantization parameter based on the stats attached to the observer module
  1609. and returns a tuple of scale and zero_point Tensor
  1610. """
  1611. def convert(self, model: torch.fx.GraphModule, observer_node: Node):
  1612. """
  1613. Converts the observer node in the graph into its quantized representation
  1614. Args:
  1615. model: graph module to convert the observer node in
  1616. observer_node: the observer node to convert
  1617. """
  1618. from torch.ao.quantization.fx.utils import create_getattr_from_value
  1619. with model.graph.inserting_before(observer_node):
  1620. if self.block_size is None:
  1621. raise AssertionError("Expecting block_size to be populated")
  1622. if self.original_dtype is None:
  1623. raise AssertionError("Expecting original_dtype to be populated")
  1624. if hasattr(self, "is_dynamic") and self.is_dynamic:
  1625. choose_qparams_affine = model.graph.call_function(
  1626. torch.ops.pt2e_quant.choose_qparams_affine,
  1627. (
  1628. observer_node.args[0],
  1629. self.mapping_type.name,
  1630. self.block_size,
  1631. self.target_dtype,
  1632. self.quant_min,
  1633. self.quant_max,
  1634. self.eps,
  1635. self.scale_dtype,
  1636. self.zero_point_dtype,
  1637. self.preserve_zero,
  1638. self.zero_point_domain.name,
  1639. ),
  1640. )
  1641. scale_node = model.graph.call_function(
  1642. operator.getitem, (choose_qparams_affine, 0)
  1643. )
  1644. zero_point_node = model.graph.call_function(
  1645. operator.getitem, (choose_qparams_affine, 1)
  1646. )
  1647. else:
  1648. scale, zero_point = self.calculate_qparams()
  1649. scale_node = create_getattr_from_value(
  1650. model,
  1651. model.graph,
  1652. "_scale",
  1653. scale,
  1654. scale.device if isinstance(scale, torch.Tensor) else None,
  1655. )
  1656. zero_point_node = create_getattr_from_value(
  1657. model,
  1658. model.graph,
  1659. "_zero_point",
  1660. zero_point,
  1661. zero_point.device if isinstance(zero_point, torch.Tensor) else None,
  1662. )
  1663. q_node = model.graph.call_function(
  1664. torch.ops.pt2e_quant.quantize_affine,
  1665. (
  1666. observer_node.args[0],
  1667. self.block_size,
  1668. scale_node,
  1669. zero_point_node,
  1670. self.target_dtype,
  1671. self.quant_min,
  1672. self.quant_max,
  1673. self.zero_point_domain.name,
  1674. ),
  1675. {},
  1676. )
  1677. dq_node = model.graph.call_function(
  1678. torch.ops.pt2e_quant.dequantize_affine,
  1679. (
  1680. q_node,
  1681. self.block_size,
  1682. scale_node,
  1683. zero_point_node,
  1684. self.target_dtype,
  1685. self.quant_min,
  1686. self.quant_max,
  1687. self.zero_point_domain.name,
  1688. ),
  1689. {"output_dtype": self.original_dtype},
  1690. )
  1691. observer_node.replace_all_uses_with(dq_node)
  1692. model.graph.erase_node(observer_node)
  1693. def _is_observer_script_module(mod, obs_type_name):
  1694. """Returns true if given mod is an instance of Observer script module."""
  1695. if isinstance(mod, torch.jit.RecursiveScriptModule):
  1696. # qualified name looks like '__torch__.torch.ao.quantization.observer.___torch_mangle_2.MinMaxObserver'
  1697. suffix = mod._c.qualified_name.split(".", 1)[1]
  1698. name = re.sub(r"\.___torch_mangle_\d+", "", suffix)
  1699. return obs_type_name in name
  1700. return False
  1701. # Experimental Affine Quantization Feature END
  1702. def _is_activation_post_process(module):
  1703. return isinstance(
  1704. module,
  1705. (
  1706. torch.ao.quantization.ObserverBase,
  1707. torch.ao.quantization.FakeQuantizeBase,
  1708. AffineQuantizedObserverBase,
  1709. ),
  1710. ) or _is_observer_script_module(module, "quantization.observer")
  1711. def _is_per_channel_script_obs_instance(module):
  1712. if isinstance(module, torch.jit.RecursiveScriptModule):
  1713. return _is_observer_script_module(
  1714. module, "quantization.observer.PerChannelMinMaxObserver"
  1715. ) or _is_observer_script_module(
  1716. module, "quantization.observer.MovingAveragePerChannelMinMaxObserver"
  1717. )
  1718. return False
  1719. def get_observer_state_dict(mod):
  1720. r"""
  1721. Returns the state dict corresponding to the observer stats.
  1722. Traverse the model state_dict and extract out the stats.
  1723. """
  1724. od = OrderedDict()
  1725. if isinstance(mod, torch.jit.RecursiveScriptModule):
  1726. for k, v in mod.state_dict().items():
  1727. if "observer" in k:
  1728. od[k] = v
  1729. else:
  1730. # path for GraphModule and nn.Module (eager mode)
  1731. for k, v in mod.state_dict().items():
  1732. if "activation_post_process" in k:
  1733. od[k] = v
  1734. od._metadata = mod.state_dict()._metadata # type: ignore[attr-defined]
  1735. return od
  1736. def load_observer_state_dict(mod, obs_dict):
  1737. r"""
  1738. Given input model and a state_dict containing model observer stats,
  1739. load the stats back into the model. The observer state_dict can be saved
  1740. using torch.ao.quantization.get_observer_state_dict
  1741. """
  1742. missing_keys: list[str] = []
  1743. unexpected_keys: list[str] = []
  1744. for name, module in mod.named_modules():
  1745. prefix = name + "."
  1746. if _is_activation_post_process(module):
  1747. if _is_per_channel_script_obs_instance(module):
  1748. # For per-channel observers we need to call a custom load_from_state_dict to resize the tensor.
  1749. # However this is not called when the module is scripted and we end up calling the default one in module.py
  1750. module._load_from_state_dict_script(
  1751. obs_dict, prefix, {}, True, missing_keys, unexpected_keys, []
  1752. )
  1753. else:
  1754. module._load_from_state_dict(
  1755. obs_dict, prefix, {}, False, missing_keys, unexpected_keys, []
  1756. )
  1757. for k in missing_keys:
  1758. if "observer" in k or "activation_post_process" in k:
  1759. raise Exception( # noqa: TRY002
  1760. f"Missing keys for observer {k} in state_dict"
  1761. )
  1762. for k in unexpected_keys:
  1763. if "observer" in k or "activation_post_process" in k:
  1764. raise Exception( # noqa: TRY002
  1765. f"Unexpected keys for observer {k} in state_dict"
  1766. )
  1767. # Restrict activations to be in the range (0,127)
  1768. default_observer = MinMaxObserver.with_args(quant_min=0, quant_max=127)
  1769. """
  1770. Default observer for static quantization, usually used for debugging.
  1771. """
  1772. default_placeholder_observer = PlaceholderObserver
  1773. """
  1774. Default placeholder observer, usually used for quantization to torch.float16.
  1775. """
  1776. default_debug_observer = RecordingObserver
  1777. """
  1778. Default debug-only observer.
  1779. """
  1780. default_weight_observer = MinMaxObserver.with_args(
  1781. dtype=torch.qint8, qscheme=torch.per_tensor_symmetric
  1782. )
  1783. """
  1784. Default weight observer.
  1785. """
  1786. weight_observer_range_neg_127_to_127 = MinMaxObserver.with_args(
  1787. dtype=torch.qint8,
  1788. qscheme=torch.per_tensor_symmetric,
  1789. quant_min=-127,
  1790. quant_max=127,
  1791. eps=2**-12,
  1792. )
  1793. """
  1794. Symmetric weight observer with the 8-bit values restricted to [-127, +127], excluding -128.
  1795. """
  1796. default_histogram_observer = HistogramObserver.with_args(quant_min=0, quant_max=127)
  1797. """
  1798. Default histogram observer, usually used for PTQ.
  1799. """
  1800. default_per_channel_weight_observer = PerChannelMinMaxObserver.with_args(
  1801. dtype=torch.qint8, qscheme=torch.per_channel_symmetric
  1802. )
  1803. """
  1804. Default per-channel weight observer, usually used on backends where per-channel
  1805. weight quantization is supported, such as `fbgemm`.
  1806. """
  1807. per_channel_weight_observer_range_neg_127_to_127 = PerChannelMinMaxObserver.with_args(
  1808. dtype=torch.qint8,
  1809. qscheme=torch.per_channel_symmetric,
  1810. quant_min=-127,
  1811. quant_max=127,
  1812. eps=2**-12,
  1813. )
  1814. """
  1815. Per-channel, symmetric weight observer with the 8-bit values restricted to [-127, +127], excluding -128.
  1816. """
  1817. default_dynamic_quant_observer = PlaceholderObserver.with_args(
  1818. dtype=torch.quint8,
  1819. quant_min=0,
  1820. quant_max=255,
  1821. is_dynamic=True,
  1822. )
  1823. """
  1824. Default observer for dynamic quantization.
  1825. """
  1826. default_float_qparams_observer = PerChannelMinMaxObserver.with_args(
  1827. dtype=torch.quint8, qscheme=torch.per_channel_affine_float_qparams, ch_axis=0
  1828. )
  1829. """
  1830. Default observer for a floating point zero-point.
  1831. """
  1832. default_float_qparams_observer_4bit = PerChannelMinMaxObserver.with_args(
  1833. dtype=torch.quint4x2, qscheme=torch.per_channel_affine_float_qparams, ch_axis=0
  1834. )
  1835. """
  1836. Default observer for a floating point zero-point and 4 bit activations.
  1837. """
  1838. # TODO(future PR): remove these defaults and enforce activation functions
  1839. # to explicitly specify their output range
  1840. default_fixed_qparams_range_neg1to1_observer = FixedQParamsObserver.with_args(
  1841. scale=2.0 / 256.0, zero_point=128, dtype=torch.quint8, quant_min=0, quant_max=255
  1842. )
  1843. default_fixed_qparams_range_0to1_observer = FixedQParamsObserver.with_args(
  1844. scale=1.0 / 256.0, zero_point=0, dtype=torch.quint8, quant_min=0, quant_max=255
  1845. )
  1846. # TODO: the following 2 variables are kept for backwards compatibility; remove after a few releases
  1847. default_symmetric_fixed_qparams_observer = default_fixed_qparams_range_neg1to1_observer
  1848. default_affine_fixed_qparams_observer = default_fixed_qparams_range_0to1_observer
  1849. """
  1850. Default observers for fixed qparams operations.
  1851. """
  1852. default_reuse_input_observer = ReuseInputObserver
  1853. """
  1854. Default observer for operators like reshape that reuses the observer of input to
  1855. the operator
  1856. """