observer.py 78 KB

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