
    [Th'                       % S r SSKrSSKrSSKJrJr  SSKJr  SSKJ	r	  SSK
JrJr  SSKrSSKJr  SSKJrJrJrJrJr  / SQr " S	 S
5      rS rS r\" S\40 5      r\\S'    " S S\\R:                  5      r " S S\5      r\r  " S S\5      r! " S S\!5      r" " S S\5      r# " S S\#5      r$ " S S\5      r% " S S\5      r& " S S\5      r' " S  S!\5      r( " S" S#\5      r) " S$ S%\5      r* SS&K+J,r,  SS'K-J.r.J/r/   " S( S)\/5      r0 " S* S+\/5      r1 " S, S-\/5      r2\," S.S/9 " S0 S15      5       r3\," S.S/9 " S2 S3\35      5       r4\," S.S/9 " S4 S5\35      5       r5\," S.S/9 " S6 S7\35      5       r6\," S.S/9 " S8 S9\35      5       r7 " S: S;\35      r8 " S< S=\35      r9S>\:\;S?4   S@\3SA\:\;S?4   4SB jr< " SC SD\\R                  R:                  5      r=SE r>SF r?SG r@SH rASI rB\!R                  SSJSK9rD \'rE \(rF \!R                  \R                  \R                  SL9rI \!R                  \R                  \R                  SMSJSNSO9rJ \%R                  SSJSK9rK \#R                  \R                  \R                  SL9rM \#R                  \R                  \R                  SMSJSNSO9rN \'R                  \R                  SSPS.SQ9rP \#R                  \R                  \R                  SSR9rR \#R                  \R                  \R                  SSR9rT \&R                  SSST\R                  SSPSU9rU\&R                  SVS\R                  SSPSU9rV\UrW\VrX \*rYg)Wz
This module implements observers which are used to collect statistics about
the values observed during calibration (PTQ) or training (QAT).
    N)ABCMetaabstractmethod)OrderedDict)partial)AnyOptional)calculate_qmin_qmaxcheck_min_max_validis_per_channelis_per_tensorvalidate_qmin_qmax)*%default_affine_fixed_qparams_observerdefault_debug_observerdefault_dynamic_quant_observer)default_fixed_qparams_range_0to1_observer,default_fixed_qparams_range_neg1to1_observerdefault_float_qparams_observer#default_float_qparams_observer_4bitdefault_histogram_observerdefault_observer#default_per_channel_weight_observerdefault_placeholder_observerdefault_reuse_input_observer(default_symmetric_fixed_qparams_observerdefault_weight_observerget_observer_state_dictload_observer_state_dict0per_channel_weight_observer_range_neg_127_to_127$weight_observer_range_neg_127_to_127FixedQParamsObserverHistogramObserverMinMaxObserverMovingAverageMinMaxObserver%MovingAveragePerChannelMinMaxObserverNoopObserverObserverBasePerChannelMinMaxObserverPlaceholderObserverRecordingObserverReuseInputObserverUniformQuantizationObserverBaseAffineQuantizedObserverBaseGranularityMappingTypePerAxisPerBlockPerGroupPerRow	PerTensorPerTokenTorchAODTypeZeroPointDomainget_block_sizec                   2    \ rS rSrS rS rS rS rS rSr	g)	_PartialWrapperK   c                     Xl         0 U l        g N)pcallable_args)selfr=   s     V/var/www/auris/envauris/lib/python3.13/site-packages/torch/ao/quantization/observer.py__init___PartialWrapper.__init__L   s        c                     U R                    H#  nX2;  d  M
  0 UEX0R                   U   " 5       0EnM%     U R                  " U0 UD6$ r<   r>   r=   )r?   argskeywordsarg_names       r@   __call___PartialWrapper.__call__P   sM     **H'QhQ2D2DX2N2PQ + vvt(x((rC   c                 l    U R                   R                  5       U R                  R                  5       -   $ r<   )r=   __repr__r>   r?   s    r@   rL   _PartialWrapper.__repr__X   s'    vv 4#5#5#>#>#@@@rC   c                     [        U 40 UD6$ r<   )
_with_argsr?   kwargss     r@   	with_args_PartialWrapper.with_args[   s    $)&))rC   c                 V    [        U R                  S9n0 U R                  EUEUl        U$ )N)r=   )r9   r=   r>   )r?   rR   results      r@   with_callable_args"_PartialWrapper.with_callable_args^   s-     466*?$"4"4??rC   rE   N)
__name__
__module____qualname____firstlineno__rA   rI   rL   rS   rW   __static_attributes__ rC   r@   r9   r9   K   s     )A*rC   r9   c                 0    [        [        U 40 UD65      nU$ )a	  Wrapper that allows creation of class factories.

This can be useful when there is a need to create classes with the same
constructor arguments, but different instances. Can be used in conjunction with
_callable_args

Example::

    >>> # xdoctest: +SKIP("Undefined vars")
    >>> Foo.with_args = classmethod(_with_args)
    >>> foo_builder = Foo.with_args(a=3, b=4).with_args(answer=42)
    >>> foo_instance1 = foo_builder()
    >>> foo_instance2 = foo_builder()
    >>> id(foo_instance1) == id(foo_instance2)
    False
)r9   r   cls_or_selfrR   rs      r@   rP   rP   d   s    " 	6v67AHrC   c                 N    [        [        U 5      5      nUR                  " S0 UD6$ )a  Wrapper that allows creation of class factories args that need to be
called at construction time.

This can be useful when there is a need to create classes with the same
constructor arguments, but different instances and those arguments should only
be calculated at construction time. Can be used in conjunction with _with_args

Example::

    >>> # xdoctest: +SKIP("Undefined vars")
    >>> Foo.with_callable_args = classmethod(_with_callable_args)
    >>> Foo.with_args = classmethod(_with_args)
    >>> foo_builder = Foo.with_callable_args(cur_time=get_time_func).with_args(name="dan")
    >>> foo_instance1 = foo_builder()
    >>> # wait 50
    >>> foo_instance2 = foo_builder()
    >>> id(foo_instance1.creation_time) == id(foo_instance2.creation_time)
    False
r^   )r9   r   rW   r`   s      r@   _with_callable_argsrd   y   s'    ( 	,-A)&))rC   ABCc                   x   ^  \ rS rSrSrSS\4U 4S jjjr\S 5       r\S 5       r	\
" \5      r\
" \5      rSrU =r$ )	r&      a/  Base observer Module.
Any observer implementation should derive from this class.

Concrete observers should follow the same API. In forward, they will update
the statistics of the observed Tensor. And they should provide a
`calculate_qparams` function that computes the quantization parameters given
the collected statistics.

Args:
    dtype: dtype argument to the `quantize` node needed to implement the
           reference model spec.
    is_dynamic: indicator for whether the observer is a placeholder for dynamic quantization
    or static quantization

is_dynamicc                 :   > [         TU ]  5         Xl        X l        g r<   )superrA   dtyperh   )r?   rk   rh   	__class__s      r@   rA   ObserverBase.__init__   s    
$rC   c                     g r<   r^   r?   xs     r@   forwardObserverBase.forward       rC   c                     g r<   r^   rQ   s     r@   calculate_qparamsObserverBase.calculate_qparams   rs   rC   rk   rh   )F)rY   rZ   r[   r\   __doc__boolrA   r   rq   ru   classmethodrP   rS   rd   rW   r]   __classcell__rl   s   @r@   r&   r&      sY    %$ % %
     J'I$%89rC   r&   c            	         ^  \ rS rSr% SrSr\R                  \S'   \R                  \R                  SSSS\R                  " \R                  5      R                  S4 SU 4S jjjrU 4S	 jr\R                   R"                  S
\S\SS4S j5       r\R                   R"                  S\R                  S\R                  S\\R                  \R                  4   4S j5       r\R                   R"                  S 5       rSrU =r$ )r+      a  Common base for all observers using uniform quantization to calculate
scale and zero_point.

Args:
    dtype: dtype argument to the `quantize` node needed to implement the
           reference model spec.
    qscheme: Quantization scheme to be used.
    reduce_range: Reduces the range of the quantized data type by 1 bit.
                  This is sometimes required to avoid instruction overflow.
    quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
    quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
    eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.

.. warning::

    :attr:`dtype` can only take ``torch.qint8`` or ``torch.quint8``.
           or `torch.int8` or `torch.uint8`

.. warning::

    :attr:`qscheme` can only take one of the following options:

    - ``torch.per_tensor_affine``
    - ``torch.per_tensor_symmetric``
    - ``torch.per_channel_affine``
    - ``torch.per_channel_symmetric``
   epsFNreturnc	                 &  > [         R                  R                  U5      n[        TU ]  " SXS.U	D6  X l        U(       a  [        R                  " S5        X0l        U R                  S[         R                  " U/40 UD65        U R
                  [         R                  [         R                  [         R                  [         R                  [         R                  4;   d   S5       e[         R                   [         R"                  [         R$                  [         R&                  [         R(                  [         R*                  [         R,                  [         R.                  [         R0                  [         R2                  [         R4                  4n
U R6                  U
;   d   SU
 S35       eUS L=(       a    US LU l        U R8                  (       a  [;        XE5        [=        UUU R8                  U R6                  U R                  5      u  U l        U l         g )Nrw   zPlease use quant_min and quant_max to specify the range for observers.                     reduce_range will be deprecated in a future release of PyTorch.r   zDefault Observer only works for per_tensor_affine,                 per_tensor_symmetric, per_channel_affine,                 per_channel_symmetric and per_channel_float_qparams quantization schemez Default Observer only works for z
 data typer^   )!torchnnfactory_kwargsrj   rA   qschemewarningswarnreduce_rangeregister_buffertensorper_tensor_affineper_tensor_symmetricper_channel_affineper_channel_symmetric per_channel_affine_float_qparamsqint8quint8quint4x2qint32int8uint8int16int32float8_e5m2float8_e4m3fnuint16rk   has_customized_qranger   r	   	quant_min	quant_max)r?   rk   r   r   r   r   r   r   rh   rR   _ALLOWED_DTYPESrl   s              r@   rA   (UniformQuantizationObserverBase.__init__   s    00@FuFvFMMU )UELL#$I.$IJ||##&&$$''22 
 
 	YY	Y 
 KKLLNNLLJJKKKKKKLL
 JJ/)	J-o->jI	J)&/t&;%X)SWBW"%%y4)<&&JJ*
&rC   c           	         > UR                  SS 5      nUb  US:X  aJ  [        R                  " [        R                  " [        R                  5      R
                  /5      n	XUS-   '   [        T
U ]  UUUUUUU5        g )Nversion   r   )getr   r   finfofloat32r   rj   _load_from_state_dict)r?   
state_dictprefixlocal_metadatastrictmissing_keysunexpected_keys
error_msgsr   r   rl   s             r@   r   5UniformQuantizationObserverBase._load_from_state_dict   st     !$$Y5?gl,,EMM : > >?@C),v~&%	
rC   r   r   c                 V    USs=::  a  U::  d    S5       e   S5       eX:  d   S5       eg)a=  Validates that the user-specified quantization range is properly initialized
and within the given bound supported by the observer dtype.

To accommodate lower-bit quantization with respect to the existing torch.qint8 and
torch.quint8 datatypes, the user can choose to use dynamic quantization range by passing
in a tuple of initial qmin and qmax values. One use case is these customized qmin and qmax
values are used to calculate static estimates of the scale and zero point for aggressive lower-bit
fake quantization. These estimates are compared against parameters learned through backpropagation.
The related literatures for scale and zero point via backpropagation are as follows:

Learned Step Size Quantization: https://openreview.net/pdf?id=rkgO66VKDS
Trained Quantization Thresholds: https://arxiv.org/pdf/1903.08066.pdf
r   z1Used-specified quantization range must include 0.zKqmin must be strictly less than qmax for user-specified quantization range.Nr^   )r?   r   r   s      r@   _validate_qmin_qmax3UniformQuantizationObserverBase._validate_qmin_qmax;  sK    $ 'i'	?>	?'	?>	?' !	YX	Y!rC   min_valmax_valc                    [        X5      (       dT  [        R                  " S/UR                  R                  S9[        R                  " S/UR                  R                  S94$ U R
                  U R                  pC[        R                  " U[        R                  " U5      5      n[        R                  " U[        R                  " U5      5      nUR                  n[        R                  " UR                  5       [        R                  US9n[        R                  " UR                  5       [        R                  US9n	U R                  [        R                   :X  d  U R                  [        R"                  :X  Ga  [        R                  " U* U5      nU[%        XC-
  5      S-  -  n[        R                  " XR&                  5      nU R(                  [        R*                  [        R,                  4;   aZ  U R.                  (       a'  U	R1                  U	R                  5       X4-   S-  5      n	GOTU	R1                  U	R                  5       S5      n	GO2U R(                  [        R2                  4;   a   U	R1                  U	R                  5       S5      n	OU R                  [        R4                  :X  aS  X!-
  [%        XC-
  5      -  n[        R6                  " XR&                  :  U[        R8                  " U5      5      nSU-  U-  n	OXe-
  [%        XC-
  5      -  n[        R                  " XR&                  5      nU[        R:                  " XX-  5      R=                  [        R>                  5      -
  n	[        R@                  " XU5      n	[C        URD                  5      S:X  a*  [        R                  " [%        U5      /UR(                  US9n[C        U	RD                  5      S:X  ar  [        R                  " [?        U	5      /U	R(                  US9n	U R                  [        R4                  :X  a*  [        R                  " [%        U	5      /U	R(                  US9n	X4$ )	aD  Calculates the quantization parameters, given min and max
value tensors. Works for both per tensor and per channel cases

Args:
    min_val: Minimum values per channel
    max_val: Maximum values per channel

Returns:
    scales: Scales tensor of shape (#channels,)
    zero_points: Zero points tensor of shape (#channels,)
      ?devicer   )rk   r         i   )#r
   r   r   r   typer   r   min
zeros_likemaxonessizer   zerosint64r   r   r   floatr   rk   r   r   r   new_fullr   r   where	ones_likeroundtointclamplenshape)
r?   r   r   r   r   min_val_negmax_val_posr   scale
zero_points
             r@   _calculate_qparams2UniformQuantizationObserverBase._calculate_qparamsS  s)   ( #744<<gnn.A.ABELLGNN//E    $~~t~~9ii)9)9')BCii)9)9')BC##

;++-U]]6R[[!1!1!35;;vV
 LLE666||u:::))[L+>K5)>#?!#CDEIIeXX.EzzellEKK88--!+!4!4")I,Aa+G"J ",!4!4Z__5F!LJ~-'001BEJ
\\UCCC&%	0E*FFEKK 0%9OPE
 g-J .%	8M2NNEIIeXX.E"U[[1D%E%H%H%SSJZIFJ u{{q LL%,u{{6REz A%Z!)9)9&J ||uEEE"\\:&'z/?/?
   rC   c                     [        S5      e)Nz2Cannot reset min/max values in the given observer.)NotImplementedErrorrM   s    r@   reset_min_max_vals2UniformQuantizationObserverBase.reset_min_max_vals  s    !"VWWrC   )r   r   r   r   r   r   N)rY   rZ   r[   r\   rx   _versionr   Tensor__annotations__r   r   r   r   r   rA   r   jitexportr   r   tupler   r   r]   r{   r|   s   @r@   r+   r+      s   T H	 ll''KK&**:
 
:
 :
x
6 YYYS YS YT Y Y. YYN!||N!.3llN!	u||U\\)	*N! N!` YYX XrC   r+   c            	         ^  \ rS rSr% Sr\R                  \S'   \R                  \S'   \R                  \R                  SSSS\R                  " \R                  5      R                  S4 SU 4S jjjrS r\R                  R                   S	 5       r\R                  R                   S
 5       r\R                  R                   S 5       rSrU =r$ )r"   i  aK	  Observer module for computing the quantization parameters based on the
running min and max values.

This observer uses the tensor min/max statistics to compute the quantization
parameters. The module records the running minimum and maximum of incoming
tensors, and uses this statistic to compute the quantization parameters.

Args:
    dtype: dtype argument to the `quantize` node needed to implement the
           reference model spec.
    qscheme: Quantization scheme to be used
    reduce_range: Reduces the range of the quantized data type by 1 bit
    quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
    quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
    eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.

Given running min/max as :math:`x_\text{min}` and :math:`x_\text{max}`,
scale :math:`s` and zero point :math:`z` are computed as:

The running minimum/maximum :math:`x_\text{min/max}` is computed as:

.. math::

    \begin{array}{ll}
    x_\text{min} &= \begin{cases}
        \min(X) & \text{if~}x_\text{min} = \text{None} \\
        \min\left(x_\text{min}, \min(X)\right) & \text{otherwise}
    \end{cases}\\
    x_\text{max} &= \begin{cases}
        \max(X) & \text{if~}x_\text{max} = \text{None} \\
        \max\left(x_\text{max}, \max(X)\right) & \text{otherwise}
    \end{cases}\\
    \end{array}

where :math:`X` is the observed tensor.

The scale :math:`s` and zero point :math:`z` are then computed as:

.. math::

    \begin{aligned}
        \text{if Symmetric:}&\\
        &s = 2 \max(|x_\text{min}|, x_\text{max}) /
            \left( Q_\text{max} - Q_\text{min} \right) \\
        &z = \begin{cases}
            0 & \text{if dtype is qint8} \\
            128 & \text{otherwise}
        \end{cases}\\
        \text{Otherwise:}&\\
            &s = \left( x_\text{max} - x_\text{min}  \right ) /
                \left( Q_\text{max} - Q_\text{min} \right ) \\
            &z = Q_\text{min} - \text{round}(x_\text{min} / s)
    \end{aligned}

where :math:`Q_\text{min}` and :math:`Q_\text{max}` are the minimum and
maximum of the quantized data type.

.. warning:: :attr:`dtype` can only take ``torch.qint8`` or ``torch.quint8``.

.. note:: If the running minimum equals to the running maximum, the scale
          and zero_point are set to 1.0 and 0.
r   r   FNc	                    > [        U5      (       d  [        S5      e[        T
U ]  " SUUUUUUUUS.U	D6  [        R
                  R                  U5      nU R                  S[        R                  " [        S5      40 UD65        U R                  S[        R                  " [        S5      40 UD65        U R                  [        R                  :X  a<  U R                  (       a*  U R                  [        R                  :X  a  [        S5      eg g g )	NzqMinMaxObserver's qscheme only support torch.per_tensor_symmetric                     and torch.per_tensor_affine.rk   r   r   r   r   r   r   rh   r   infr   -infz`Cannot reduce range for symmetric                                        quantization for quint8r^   )r   r   rj   rA   r   r   r   r   r   r   r   r   r   rk   r   )r?   rk   r   r   r   r   r   r   rh   rR   rl   s             r@   rA   MinMaxObserver.__init__  s     W%%%2  	 
	
%)!
	
 
	
 00@YU5\(T^(TUYU6](Un(UVLLE666!!

ell*%@  + " 7rC   c                    UR                  5       S:X  a  U$ UR                  5       nUR                  U R                  R                  5      n[
        R                  " U5      u  p4[
        R                  " X0R                  5      n[
        R                  " X@R                  5      nU R                  R                  U5        U R                  R                  U5        U$ )z1Records the running minimum and maximum of ``x``.r   )numeldetachr   r   rk   r   aminmaxr   r   r   copy_)r?   x_origrp   min_val_curmax_val_curr   r   s          r@   rq   MinMaxObserver.forward$  s    <<>QMMMODD##$#(==#3 ))K6))K67#7#rC   c                 N    U R                  U R                  U R                  5      $ )z'Calculates the quantization parameters.r   r   r   rM   s    r@   ru    MinMaxObserver.calculate_qparams1  s     &&t||T\\BBrC   c                 :    SU R                    SU R                   3$ Nzmin_val=z
, max_val=r   r   rM   s    r@   
extra_reprMinMaxObserver.extra_repr6  s    $,,z$,,@@rC   c                     U R                   R                  [        R                  " [	        S5      5      5        U R
                  R                  [        R                  " [	        S5      5      5        g)Resets the min/max values.r   r   N)r   r   r   r   r   r   rM   s    r@   r   !MinMaxObserver.reset_min_max_vals:  sB     	5<<e565<<f67rC   r^   r   )rY   rZ   r[   r\   rx   r   r   r   r   r   r   r   r   rA   rq   r   r   ru   r   r   r]   r{   r|   s   @r@   r"   r"     s    =| \\\\ ll''KK&**1 
1 1f YYC C YYA A YY8 8rC   r"   c            	          ^  \ rS rSrSrS\R                  \R                  SSS\R                  " \R                  5      R                  S4 S	U 4S jjjrS rSrU =r$ )
r#   iA  a[  Observer module for computing the quantization parameters based on the
moving average of the min and max values.

This observer computes the quantization parameters based on the moving
averages of minimums and maximums of the incoming tensors. The module
records the average minimum and maximum of incoming tensors, and uses this
statistic to compute the quantization parameters.

Args:
    averaging_constant: Averaging constant for min/max.
    dtype: dtype argument to the `quantize` node needed to implement the
           reference model spec.
    qscheme: Quantization scheme to be used
    reduce_range: Reduces the range of the quantized data type by 1 bit
    quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
    quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
    eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.

The moving average min/max is computed as follows

.. math::

    \begin{array}{ll}
            x_\text{min} = \begin{cases}
                \min(X) & \text{if~}x_\text{min} = \text{None} \\
                (1 - c) x_\text{min} + c \min(X) & \text{otherwise}
            \end{cases}\\
            x_\text{max} = \begin{cases}
                \max(X) & \text{if~}x_\text{max} = \text{None} \\
                (1 - c) x_\text{max} + c \max(X) & \text{otherwise}
            \end{cases}\\
    \end{array}

where :math:`x_\text{min/max}` is the running average min/max, :math:`X` is
is the incoming tensor, and :math:`c` is the ``averaging_constant``.

The scale and zero point are then computed as in
:class:`~torch.ao.quantization.observer.MinMaxObserver`.

.. note:: Only works with ``torch.per_tensor_affine`` quantization scheme.

.. note:: If the running minimum equals to the running maximum, the scale
          and zero_point are set to 1.0 and 0.
{Gz?FNc	                    > [        U5      (       d  [        SU 35      eXl        U(       a(  U R                  S:w  a  [        SU R                   35      e[        T
U ]  " SUUUUUUUS.U	D6  g )NzMovingAverageMinMaxObserver's qscheme only support                 torch.per_tensor_symmetric and torch.per_tensor_affine.                 but got: r   z[MovingAverageMinMaxObserver doesn't support dynamic quantization for averaging constant of )rk   r   r   r   r   r   rh   r^   )r   r   averaging_constantrj   rA   )r?   r   rk   r   r   r   r   r   rh   rR   rl   s             r@   rA   $MovingAverageMinMaxObserver.__init__o  s     W%%%!$ 
 #5$11Q6%))-)@)@(AC  	 		
%!		
 		
rC   c                 "   UR                  5       S:X  a  U$ UR                  5       nUR                  U R                  R                  5      nU R                  nU R
                  nU[        S5      :X  a(  U[        S5      :X  a  [        R                  " U5      u  p4O>[        R                  " U5      u  pVX0R                  XS-
  -  -   nX@R                  Xd-
  -  -   nU R                  R                  U5        U R
                  R                  U5        U$ )Nr   r   r   )r   r   r   r   rk   r   r   r   r   r   r   )r?   r   rp   r   r   r   r   s          r@   rq   #MovingAverageMinMaxObserver.forward  s    <<>QMMMODD##$,,,,eEl"w%-'?$}}Q/GW',}}Q'7$K 7 7;;P QQG 7 7;;P QQG7#7#rC   r   r   )rY   rZ   r[   r\   rx   r   r   r   r   r   r   rA   rq   r]   r{   r|   s   @r@   r#   r#   A  s_    +^  ll''KK&**!
 
!
 !
F rC   r#   c                   >  ^  \ rS rSr% Sr\R                  \S'   \R                  \S'   S\R                  \R                  SSSS\R                  " \R                  5      R                  S4	 SU 4S jjjrS	 rS
 r\R                   R"                  S 5       rS rS\\\4   S\S\\\R                  4   S\S\\   S\\   S\\   4U 4S jjrS\\\4   S\S\\\R                  4   S\S\\   S\\   S\\   4S jr\R                   R"                  S 5       rSrU =r$ )r'   i  a  Observer module for computing the quantization parameters based on the
running per channel min and max values.

This observer uses the tensor min/max statistics to compute the per channel
quantization parameters. The module records the running minimum and maximum
of incoming tensors, and uses this statistic to compute the quantization
parameters.

Args:
    ch_axis: Channel axis
    dtype: dtype argument to the `quantize` node needed to implement the
           reference model spec.
    qscheme: Quantization scheme to be used
    reduce_range: Reduces the range of the quantized data type by 1 bit
    quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
    quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
    eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.

The quantization parameters are computed the same way as in
:class:`~torch.ao.quantization.observer.MinMaxObserver`, with the difference
that the running min/max values are stored per channel.
Scales and zero points are thus computed per channel as well.

.. note:: If the running minimum equals to the running maximum, the scales
          and zero_points are set to 1.0 and 0.
r   r   r   FNc
                 ,  > [        U5      (       d  [        S5      eU	(       a  [        S5      e[        TU ]  " SUUUUUUUU	S.U
D6  [        R
                  R                  U5      nXl        U R                  S[        R                  " / 40 UD65        U R                  S[        R                  " / 40 UD65        U R                  [        R                  :X  a<  U R                  (       a*  U R                  [        R                  :X  a  [        S5      eg g g )NzPerChannelMinMaxObserver's qscheme only support                     torch.per_channel_symmetric, torch.per_channel_affine and torch.per_channel_affine_float_qparams.z=PerChannelMinMaxObserver doesn't support dynamic quantizationr   r   r   z9Cannot reduce range for symmetric quantization for quint8r^   )r   r   rj   rA   r   r   r   ch_axisr   r   r   r   r   rk   r   )r?   r  rk   r   r   r   r   r   r   rh   rR   rl   s              r@   rA   !PerChannelMinMaxObserver.__init__  s    g&&%w  %O  	 
	
%)!
	
 
	
 00@YR(J>(JKYR(J>(JKLLE777!!

ell*%K  + " 8rC   c                 $    U R                  U5      $ r<   )_forward)r?   r   s     r@   rq    PerChannelMinMaxObserver.forward  s    }}V$$rC   c                    UR                  5       S:X  a  U$ UR                  5       nU R                  nU R                  nUR	                  5       n[        [        U5      5       Vs/ s H  ofPM     nnSXpR                  '   U R                  US'   UR                  U5      nUR                  U R                  R                  5      n[        R                  " USS9nUR                  5       S:X  d  UR                  5       S:X  a  [        R                  " USS9u  p4OC[        R                  " USS9u  p[        R                  " X5      n[        R                  " X5      nU R                  R!                  UR"                  5        U R                  R!                  UR"                  5        U R                  R%                  U5        U R                  R%                  U5        U$ s  snf Nr   r   )	start_dimdim)r   r   r   r   r   ranger   r  permuter   rk   r   flattenr   r   r   resize_r   r   r?   r   rp   r   r   x_diminew_axis_listyr   r   s              r@   r  !PerChannelMinMaxObserver._forward  sg   <<>QMMMO,,,,$)#e*$56$5q$56&'ll#<<aIIm$ DD##$MM!q)==?a7==?a#7$}}QA6GW',}}QA'>$Kii5Gii5GW]]+W]]+7#7#% 7s   %Gc                 N    U R                  U R                  U R                  5      $ r<   r   rM   s    r@   ru   *PerChannelMinMaxObserver.calculate_qparams  s    &&t||T\\BBrC   c                 :    SU R                    SU R                   3$ r   r   rM   s    r@   r   #PerChannelMinMaxObserver.extra_repr      $,,z$,,@@rC   r   r   r   r   r   r   r   c           	         > UR                  SS 5      nUb  US:  a	  SS/n	Sn
SnOSS/n	Sn
SnU	 GH!  nX,-   nX;   a  X   nX:X  a&  U R                  R                  UR                  5        ODX:X  a&  U R                  R                  UR                  5        O[
        R                  " SU 35        [        R                  R                  5       (       a`  X:X  a  U R                  R                  U5        M  X:X  a  U R                  R                  U5        M  [
        R                  " SU 35        GM  GM  U(       d  GM  UR                  U5        GM$     [        R                  R                  5       (       d  [        TU ]5  UUUSUUU5        g g )	Nr   r   min_valsmax_valsr   r   z2Observer load_from_state_dict got unexpected name F)r   r   r  r   r   r   r   r   r   is_scriptingr   appendrj   r   )r?   r   r   r   r   r   r   r   r   local_stateexpected_min_nameexpected_max_namenamekeyvalrl   s                  r@   r   .PerChannelMinMaxObserver._load_from_state_dict  sp    !$$Y57Q;%z2K * *$i0K ) )D-C  o
 ,LL((3.LL((3MMLTFS
 99))++0**3/2**3/ PQUPVW , ##C(9  < yy%%''G) (rC   c           	      2    U R                  UUUUUUU5        g r<   )r   )r?   r   r   r   r   r   r   r   s           r@   _load_from_state_dict_script5PerChannelMinMaxObserver._load_from_state_dict_scriptR  s'     	""	
rC   c                 p    [         R                  " S5      U l        [         R                  " S5      U l        g)r   r   N)r   randr   r   rM   s    r@   r   +PerChannelMinMaxObserver.reset_min_max_valsf  s,     zz
 zz
rC   )r  r   r   r   )rY   rZ   r[   r\   rx   r   r   r   r   r   r   r   r   rA   rq   r  r   r   ru   r   dictstrr   ry   listr   r)  r   r]   r{   r|   s   @r@   r'   r'     s   4 \\\\ ll((KK&**, 
, ,\%8 YYC CA:cN: : S%,,./	:
 : 3i: c: I:x
cN
 
 S%,,./	

 
 3i
 c
 I
( YY

 

rC   r'   c            
          ^  \ rS rSrSrSS\R                  \R                  SSS\R                  " \R                  5      R                  S4	 S
U 4S jjjrS rS	rU =r$ )r$   it  a  Observer module for computing the quantization parameters based on the
running per channel min and max values.

This observer uses the tensor min/max statistics to compute the per channel
quantization parameters. The module records the running minimum and maximum
of incoming tensors, and uses this statistic to compute the quantization
parameters.

Args:
    averaging_constant: Averaging constant for min/max.
    ch_axis: Channel axis
    dtype: Quantized data type
    qscheme: Quantization scheme to be used
    reduce_range: Reduces the range of the quantized data type by 1 bit
    quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
    quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
    eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.

The quantization parameters are computed the same way as in
:class:`~torch.ao.quantization.observer.MovingAverageMinMaxObserver`, with the
difference that the running min/max values are stored per channel.
Scales and zero points are thus computed per channel as well.

.. note:: If the running minimum equals to the running maximum, the scales
          and zero_points are set to 1.0 and 0.
r   r   FNc
                    > [        U5      (       d  [        S5      eU	(       a  [        S5      e[        TU ]  " SUUUUUUUU	S.U
D6  Xl        g )NzMovingAveragePerChannelMinMaxObserver's qscheme only support                     torch.per_channel_symmetric, torch.per_channel_affine and torch.per_channel_affine_float_qparams.zJMovingAveragePerChannelMinMaxObserver doesn't support dynamic quantization)r  rk   r   r   r   r   r   rh   r^   )r   r   rj   rA   r   )r?   r   r  rk   r   r   r   r   r   rh   rR   rl   s              r@   rA   .MovingAveragePerChannelMinMaxObserver.__init__  sv     g&&%w  %\  	 
	
%!
	
 
	
 #5rC   c                    UR                  5       S:X  a  U$ UR                  5       nUR                  U R                  R                  5      nU R                  nU R
                  nUR                  5       n[        [        U5      5       Vs/ s H  ofPM     nnSXpR                  '   U R                  US'   UR                  U5      n[        R                  " USS9nUR                  5       S:X  d  UR                  5       S:X  a  [        R                  " USS9u  p4O=[        R                  " USS9u  pX0R                  X-
  -  -   nX@R                  X-
  -  -   nU R                  R                  UR                   5        U R
                  R                  UR                   5        U R                  R#                  U5        U R
                  R#                  U5        U$ s  snf r	  )r   r   r   r   rk   r   r   r  r   r  r  r   r  r   r   r  r   r   r  s              r@   rq   -MovingAveragePerChannelMinMaxObserver.forward  su   <<>QMMMODD##$,,,,$)#e*$56$5q$56&'ll#<<aIIm$MM!q)==?a7==?a#7$}}QA6GW',}}QA'>$K 7 7;;P QQG 7 7;;P QQGW]]+W]]+7#7# 7s   
Gr   r   )rY   rZ   r[   r\   rx   r   r   r   r   r   r   rA   rq   r]   r{   r|   s   @r@   r$   r$   t  sa    :  ll((KK&**!5 
!5 !5F rC   r$   c                     ^  \ rS rSr% Sr\R                  \S'   \R                  \S'   \R                  \S'   S\R                  \R                  SSSS\R                  " \R                  5      R                  S4	S	\S
\R                  SS4U 4S jjjrS\R                  S\R                  S\R                  S\R                  4S jrS\S\4S jrS\\R                  \R                  4   4S jrS\R                  S\R                  S\R                  S\R                  S\R                  4
S jrS\R                  S\R                  S\R                  S\R                  S\R                  S\R                  S\R                  4S jrS\R                  S\R                  S\R                  SS4S jrS\R                  S\R                  4S  jr\R0                  R2                  S! 5       rU 4S" jrU 4S# jrS$ rS%rU =r$ )&r!   i  a  
The module records the running histogram of tensor values along with
min/max values. ``calculate_qparams`` will calculate scale and zero_point.

Args:
    bins: Number of bins to use for the histogram
    dtype: dtype argument to the `quantize` node needed to implement the
           reference model spec
    qscheme: Quantization scheme to be used
    reduce_range: Reduces the range of the quantized data type by 1 bit
    eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.

The scale and zero point are computed as follows:

1. Create the histogram of the incoming inputs.
    The histogram is computed continuously, and the ranges per bin change
    with every new tensor observed.
2. Search the distribution in the histogram for optimal min/max values.
    The search for the min/max values ensures the minimization of the
    quantization error with respect to the floating point model.
3. Compute the scale and zero point the same way as in the
    :class:`~torch.ao.quantization.MinMaxObserver`
	histogramr   r   i   FNbinsrk   r   c
                 p  > [        U5      (       d  [        S5      eU	(       a  [        S5      e[        TU ]  " SUUUUUUUU	S.U
D6  [        R
                  R                  U5      nXl        U R                  S[        R                  " U R                  40 UD65        U R                  S[        R                  " [        S5      40 UD65        U R                  S[        R                  " [        S5      40 UD65        S	[        R                  " U R                  5      R                  -  U l        S
U l        g )NztHistogramObserver's qscheme only support torch.per_tensor_symmetric                     and torch.per_tensor_affine.z6HistogramObserver doesn't support dynamic quantizationr   r7  r   r   r   r   r      r^   )r   r   rj   rA   r   r   r   r8  r   r   r   r   iinfork   bits	dst_nbinsupsample_rate)r?   r8  rk   r   r   r   r   r   r   rh   rR   rl   s              r@   rA   HistogramObserver.__init__  s    W%%%2  %H  	 
	
%)!
	
 
	
 00@	[%++dii*R>*RSYU5\(T^(TUYU6](Un(UVekk$**5::: 	rC   delta_begin	delta_enddensityc                 .    X"-  U-  X-  U-  -
  S-  nX4-  $ )z
Compute the norm of the values uniformaly distributed between
delta_begin and delta_end.
Currently only L2 norm is supported.

norm = density * (integral_{begin, end} x^2)
     = density * (end^3 - begin^3) / 3
r   r^   )r?   r@  rA  rB  norms        r@   	_get_normHistogramObserver._get_norm  s0     !I-0IK0WW ~rC   next_start_binnext_end_binc           	         U R                   R                  5       U R                  R                  5       -
  U R                  -  nX2U-
  S-   -  U R                  -  nUS:X  a  g[
        R                  " U R                  U R                  R                  S9nXQ-
  U-  nXc-   n[
        R                  " [
        R                  " XdSS9SU R                  S-
  5      nUS-   U-  n	[
        R                  " [
        R                  " XtSS9SU R                  S-
  5      n
U R                  U-  n[
        R                  " U R                  U R                  R                  S9nXi-
  nUS-  nXR                  U[
        R                  " U R                  U R                  R                  S9U-  U5      -  nXU-
  S-
  U R                  [
        R                  " U* S-  5      [
        R                  " US-  5      U5      -  -  nX-  US-  -   nU* S-  nX-
  nXR                  [
        R                  " U5      X5      -  nUR                  5       R                  5       $ )	zj
Compute the quantization error if we use start_bin to end_bin as the
min and max to do the quantization.
r           r   floor)rounding_moder         ?r   )r   itemr   r8  r=  r   aranger7  r   r   divr   rE  r   r   sum)r?   rG  rH  	bin_widthdst_bin_widthsrc_binsrc_bin_beginsrc_bin_enddst_bin_of_begindst_bin_of_begin_centerdst_bin_of_endrB  rD  r@  rA  dst_bin_of_end_centers                   r@   _compute_quantization_error-HistogramObserver._compute_quantization_error&  s   
 \\&&(4<<+<+<+>>$))K	!N%BQ%FG$..XC,,tyy1F1FG !1Y>#/ !;;IIm'JNNQ

 $4c#9]"JIIkHNNQ

 ..9,{{499T^^-B-BC#=!A%	JJtyy)>)>?)K
 	
 	"22Q6$..LL-!+,ell=1;L.Mw;
 
 	
 !/ >QRAR R$nq(7	u||K8)MMxxz  rC   c                 (   U R                   R                  5       S   U R                  :X  d   S5       eU R                  U R                  -
  U R                  -  n[
        R                  " U R                   5      R                  5       n[
        R                  " U R                   SS9nSnSnSnSnU R                  S-
  n[        S5      n	XV:  a  XT-   n
Xd-
  nUnUnX:  a   X<   X-  :  a  US-   nX:  a  X<   X-  :  a  M  X:  a   X=   X-  :  a  US-
  nX:  a  X=   X-  :  a  M  UnUnX-
  X-
  :  a  UnU
nOUnUnX:X  a  X:X  a  M~  U R                  X5      nUU	:  a  OUn	UnUnXV:  a  M  U R                  X-  -   nU R                  XS-   -  -   nUU4$ )	a2  Non-linear parameter search.

An approximation for L2 error minimization for selecting min/max.
By selecting new min/max, we filter out outliers in input distribution.
This follows the implementation of NormMinimization::NonlinearQuantizationParamsSearch in
caffe2/quantization/server/norm_minimization.cc
r   zbins mismatchr  gh㈵>rJ  r   r   r   )r7  r   r8  r   r   r   rQ  rN  cumsumr   r[  )r?   rR  totalcSumstepsizealphabeta	start_binend_binnorm_min
next_alpha	next_betalrb   rG  rH  rD  new_minnew_maxs                      r@   _non_linear_param_search*HistogramObserver._non_linear_param_search\  s    ~~""$Q'4994EoE4\\DLL0DII=	 		$..)..0||DNN2	))a-<l)JI AA+$'J,>">E +$'J,>">-DGi.?$?E -DGi.?$? 'N"L'+.!""  ! *|/F 33NQDhH&I"GG lJ ,,!66,,k!::rC   orig_minorig_max
update_min
update_maxc                    UR                  U R                  5      U R                  -  nX2-
  U R                  U R                  -  -  n[        R                  " UUU R                  U R                  -  S-   UR
                  S9S S R                  UR
                  5      SU-  -   n[        R                  " XEU R                  S-   UR
                  S9R                  UR
                  5      n[        R                  " XxSS9S-
  n	U R                  S-
  XU R                  :  '   SXS:  '   [        R                  " XU R                  S9n
U
$ )	Nr   r   r   rM  T)rightr   )weights	minlength)	repeat_interleaver>  r8  r   linspacer   r   	bucketizebincount)r?   r7  rn  ro  rp  rq  bin_sizemid_points_histogramboundaries_new_histogrambucket_assignmentsupdate_histograms              r@   _upscale_histogram$HistogramObserver._upscale_histogram  sB    //0B0BCdFXFXX	'DII8J8J,JKNN		D...2	
 r
 2i&&'Hn 	 $)>>DIIM*:K:K$

"Y
 	!
 OO0RVW 	 ?Cii!m:;5612 >>TYY
  rC   	orig_histupdate_histc                     XR:X  a	  Xc:X  a  X-   $ X#:X  a<  [         R                  " U5      n[         R                  " X R                  XVS9U-  nX-   $ XR::  d   eXc:  d   eU R	                  UUUUU5      nXH-   $ )N)r8  r   r   )r   rQ  histcr8  r  )	r?   r  rn  ro  r  rp  rq  	bin_valuetransformed_orig_hists	            r@   _combine_histograms%HistogramObserver._combine_histograms  s     !j&<** 		+.IH99*U " )66 %%%%%% !% 7 7!
 22rC   rp   c                 <   U R                   R                  UR                  5        U R                   R                  U5        U R                  R                  UR                  5        U R                  R                  U5        UR                  5       S:X  a  UR                  5       S:X  d   S5       e[        R                  " XR                  X#S9nU R                  R                  5       R                  UR                  5        U R                  R                  U5        g )Nr   z(histogram min/max values must be scalar.r   r   )r   r  r   r   r   r   r   r  r8  r7  detach_)r?   rp   r   r   new_histograms        r@   reset_histogram!HistogramObserver.reset_histogram  s     	W]]+7#W]]+7#MMOq W]]_%9	65	69AyygK (()<)<=]+rC   r   c                 z   UR                  5       S:X  a  U$ UR                  5       n[        R                  " U5      u  p4U[        R                  * :X  d  U[        R                  :X  ag  [
        R                  " S5        X"R                  5       [        R                  :g     nUR                  5       S:X  a  U$ [        R                  " U5      u  p4U R                  nU R                  nU R                  [        S5      :H  =(       d    U R                  [        S5      :H  nU(       a  U R                  X#U5        U$ X4p[        R                  " XX5      n
[        R                  " Xi5      nU
R                  5       UR                  5       p[        R                  " X R                  XS9R!                  U R"                  R$                  5      nX:X  ad  X:X  a_  U R"                  U-   nU R"                  R'                  5       R)                  UR*                  5        U R"                  R-                  U5        U$ U R/                  U R"                  UUUU
U5      nU R"                  R'                  5       R)                  UR*                  5        U R"                  R-                  U5        U R                  R'                  5       R)                  U
R*                  5        U R                  R-                  U
5        U R                  R'                  5       R)                  UR*                  5        U R                  R-                  U5        U$ )Nr   z2torch.inf detected in input tensor, ignoring inputr   r   r  )r   r   r   r   r   r   r   absr   r   r   r  r   r   r  r8  r   r7  r   r  r  r   r   r  )r?   r   rp   x_minx_maxcurrent_mincurrent_maxis_uninitializedrp  rq  rj  rk  r~  combined_histograms                 r@   rq   HistogramObserver.forward  sl   <<>QMMMO}}Q' UYYJ%599"4MMNO%%'UYY&'AwwyA~ ==+LEllll<<5<7X4<<5QW=;X  51@ = &+
ii8Gii8G  '~~/1AW${{99' b&&'  %'*@%)^^6F%F"&&(001C1I1IJ$$%78"  &*%=%=NN$&" &&(001C1I1IJ$$%78$$&..w}}=""7+$$&..w}}=""7+rC   c                    U R                   [        S5      :H  =(       a    U R                  [        S5      :H  nU(       a~  [        R                  " S5        [
        R                  " S/U R                   R                  R                  S9[
        R                  " S/U R                   R                  R                  S94$ U R                  [        U R                  5      :X  d   S5       eU R                  5       u  p#U R                  X#5      $ )Nr   r   z~must run observer before calling calculate_qparams.                                    Returning default scale and zero point r   r   r   ziThe number of bins in histogram should be equal to the number of bins supplied while making this observer)r   r   r   r   r   r   r   r   r   r8  r   r7  rl  r   )r?   r  rj  rk  s       r@   ru   #HistogramObserver.calculate_qparams/  s    <<5<7 
DLLEM
 =
 MMM <<dll.A.A.F.FGDLL//44J   yyC// 	
2	
/
  88:&&w88rC   c                 j   > [         TU ]  XU5        U R                  XS-   '   U R                  XS-   '   g )Nr   r   )rj   _save_to_state_dictr   r   )r?   destinationr   	keep_varsrl   s       r@   r  %HistogramObserver._save_to_state_dictE  s4    #KC*.,,Y&'*.,,Y&'rC   c           	      0  > UR                  SS 5      nUb  US:  a  US-   US-   pX;   aH  X   R                  [        R                  " S/5      :X  a!  [        R                  " [        S5      5      X'   X;   aH  X   R                  [        R                  " S/5      :X  a!  [        R                  " [        S5      5      X'   SS/nU H8  nX,-   nX;   a  X   n[        XU5        M  U(       d  M'  UR                  U5        M:     [        TU ]%  UUUUUUU5        g )Nr   r   r   r   r   r   r   )
r   r   r   Sizer   r   setattrr   rj   r   )r?   r   r   r   r   r   r   r   r   min_val_namemax_val_namer!  r$  r%  r&  rl   s                  r@   r   'HistogramObserver._load_from_state_dictJ  s
    !$$Y5?gk *0));Vi=O,)+11UZZ_D/4||E%L/IJ,)+11UZZ_D/4||E&M/JJ, ),D-C  oC(##C(   	%	
rC   c                 :    SU R                    SU R                   3$ r   r   rM   s    r@   r   HistogramObserver.extra_reprs  r  rC   )r8  r=  r>  ) rY   rZ   r[   r\   rx   r   r   r   r   r   r   r   r   r   rk   rA   rE  r[  r   rl  r  r  r  rq   r   r   ru   r  r   r   r]   r{   r|   s   @r@   r!   r!     s'   . ||\\\\ "\\''KK&***
*
 {{*
 
*
 *
X <<49LLKP<<	 4!# 4!S 4!l= %ell0J*K = ~' <<'  ,,'  ,,	' 
 LL'  LL' R%3<<%3 ,,%3 ,,	%3
 \\%3 LL%3 LL%3 
%3N,,(-,?D||,	,4ell 4u|| 4l YY9 9*7
'
RA ArC   r!   c                      ^  \ rS rSr% Sr\R                  \S'   \R                  \S'   \R                  \R                  SSS4U 4S jjr
S	 r\R                  R                  S
 5       rSrU =r$ )r    iw  a5  
Observer that simulates quantize and dequantize with fixed
quantization parameters in training time. Only per tensor
quantization is supported.

Args:
    `scale` (float): fixed scale for the observer
    `zero_point` (int): fixed zero point for the observer
    `dtype`, `qscheme`, `quant_min`, `quant_max`
r   r   r      Fc                 N  > U(       a  [        S5      e[        T	U ]  " SX7S.UD6  XPl        X`l        U R                  S[        R                  " U/[        R                  S95        U R                  S[        R                  " U/[        R                  S95        X0l
        X@l        g )Nz9FixedQParamsObserver doesn't support dynamic quantizationrw   r   )rk   r   r^   )r   rj   rA   r   r   r   r   r   r   r   rk   r   )
r?   r   r   rk   r   r   r   rh   rR   rl   s
            r@   rA   FixedQParamsObserver.__init__  s     %K  	FuFvF""WellE7%++&NO\5<<EII+VW
rC   c                     U$ r<   r^   )r?   Xs     r@   rq   FixedQParamsObserver.forward      rC   c                 2    U R                   U R                  4$ r<   )r   r   rM   s    r@   ru   &FixedQParamsObserver.calculate_qparams  s    zz4??**rC   )rk   r   r   r   )rY   rZ   r[   r\   rx   r   r   r   r   r   rA   rq   r   r   ru   r]   r{   r|   s   @r@   r    r    w  sa    	 << ll''. YY+ +rC   r    c                      ^  \ rS rSrSr\R                  SSSSSSS4 SU 4S jjjrS r\R                  R                  S 5       r\R                  R                  S	 5       rS
rU =r$ )r(   i  a!  
Observer that doesn't do anything and just passes its configuration to the
quantized module's ``.from_float()``.

Can be used for quantization to float16 which doesn't require determining
ranges.

Args:
    dtype: dtype argument to the `quantize` node needed to implement the
           reference model spec.
    quant_min: minimum value in quantized domain (TODO: align behavior with other observers)
    quant_max: maximum value in quantized domain
    custom_op_name: (temporary) specify this observer for an operator that doesn't require any observation
                    (Can be used in Graph Mode Passes for special case ops).
    compute_dtype (deprecated): if set, marks the future quantize function to use
                   dynamic quantization instead of static quantization.
                   This field is deprecated, use `is_dynamic=True` instead.
    is_dynamic: if True, the `quantize` function in the reference model
                representation taking stats from this observer instance will
                use dynamic quantization.
 NFc	                 0  > [         T	U ]  XS9  Uc  [        R                  nUc.  [        R                  " [        R
                  5      R                  nXl        X`l        X@l	        XPl
        Xpl        X l        U(       a  Sn[        R                  " S5        g g )Nrw   TzPlease use `is_dynamic` instead of `compute_dtype`.                     `compute_dtype` will be deprecated in a future release                     of PyTorch.)rj   rA   r   r   r   r   r   rk   r   r   r   	custom_opr   r   )
r?   rk   custom_op_namecompute_dtyper   r   r   r   rh   rl   s
            r@   rA   PlaceholderObserver.__init__  s     	u<?--G;++emm,00C 
""'JMM! rC   c                     U$ r<   r^   ro   s     r@   rq   PlaceholderObserver.forward  r  rC   c                 :    SU R                    SU R                   3$ )Nzdtype=z, is_dynamic=rw   rM   s    r@   r   PlaceholderObserver.extra_repr  s    

|=0ABBrC   c                     [        S5      e)Nz>calculate_qparams should not be called for PlaceholderObserver	ExceptionrM   s    r@   ru   %PlaceholderObserver.calculate_qparams  s    L
 	
rC   )r  rk   r   r   r   r   r   )rY   rZ   r[   r\   rx   r   r   rA   rq   r   r   r   ru   r]   r{   r|   s   @r@   r(   r(     s~    0 mm  
   D YYC C YY
 
rC   r(   c                      ^  \ rS rSrSrS\\\R                        0r	\R                  4U 4S jjrS r\R                  R                  S 5       r\R                  R                  S 5       rSrU =r$ )	r)   i  z
The module is mainly for debug and records the tensor values during runtime.

Args:
    dtype: Quantized data type
    qscheme: Quantization scheme to be used
    reduce_range: Reduces the range of the quantized data type by 1 bit

tensor_valc                 0   > [         TU ]  USS9  / U l        g NFrw   )rj   rA   r  )r?   rk   rl   s     r@   rA   RecordingObserver.__init__  s    u7rC   c                 X    U R                   R                  UR                  5       5        U$ r<   )r  r   clonero   s     r@   rq   RecordingObserver.forward  s    qwwy)rC   c                     [        S5      e)Nz<calculate_qparams should not be called for RecordingObserverr  rM   s    r@   ru   #RecordingObserver.calculate_qparams  s    J
 	
rC   c                     U R                   $ r<   r  rM   s    r@   get_tensor_value"RecordingObserver.get_tensor_value  s    rC   r  )rY   rZ   r[   r\   rx   r0  r   r   r   r   r   rA   rq   r   r   ru   r  r]   r{   r|   s   @r@   r)   r)     so     $T(5<<*@%ABO"\\  YY
 

 YY rC   r)   c                      ^  \ rS rSrSr\R                  S4SU 4S jjjrS r\R                  R                  S 5       rSrU =r$ )	r%   i
  a  
Observer that doesn't do anything and just passes its configuration to the
quantized module's ``.from_float()``.

Primarily used for quantization to float16 which doesn't require determining
ranges.

Args:
    dtype: Quantized data type
    custom_op_name: (temporary) specify this observer for an operator that doesn't require any observation
                    (Can be used in Graph Mode Passes for special case ops).
r  c                 :   > [         TU ]  USS9  Xl        X l        g r  )rj   rA   rk   r  )r?   rk   r  rl   s      r@   rA   NoopObserver.__init__  s    u7
'rC   c                     U$ r<   r^   ro   s     r@   rq   NoopObserver.forward  r  rC   c                     [        S5      e)Nz7calculate_qparams should not be called for NoopObserverr  rM   s    r@   ru   NoopObserver.calculate_qparams   s    E
 	
rC   )r  rk   r   )rY   rZ   r[   r\   rx   r   float16rA   rq   r   r   ru   r]   r{   r|   s   @r@   r%   r%   
  s@     #]]2 ( (
 YY
 
rC   r%   c                   n   ^  \ rS rSrSrSU 4S jjrS r\R                  R                  S 5       r
SrU =r$ )r*   i'  a  This observer is used when we want to reuse the observer from the operator
that produces the input Tensor, typically used for operators like reshape, e.g.
```
x0 = ...
x1 = x0.reshape()
```
if we configure x0 to be observed by some observer, let's say MinMaxObserver,
and reshape is configured with ReuseInputObserver, we'll reuse the observer instance
for x0 for x1 (output of reshape). If x0 is not observed, we also won't observe x1.

Note: this is only enabled in FX Graph Mode Quantization
c                 >   > [         TU ]  [        R                  SS9  g )NF)rh   )rj   rA   r   r   )r?   rl   s    r@   rA   ReuseInputObserver.__init__5  s    %8rC   c                     U$ r<   r^   ro   s     r@   rq   ReuseInputObserver.forward8  r  rC   c                     [        S5      e)Nz=calculate_qparams should not be called for ReuseInputObserverr  rM   s    r@   ru   $ReuseInputObserver.calculate_qparams;  s    K
 	
rC   r^   r   )rY   rZ   r[   r\   rx   rA   rq   r   r   r   ru   r]   r{   r|   s   @r@   r*   r*   '  s0    9 YY
 
rC   r*   )	dataclass)autoEnumc                   B    \ rS rSrSr\" 5       r\" 5       r\" 5       rSr	g)r.   iK  a  How floating point number is mapped to integer number

symmetric mapping means floating point range is symmetrically mapped to integer range
let's say we have floating point range (-3.5, 10.2) and integer range (-8, 7) (int4)
we'll use (-10.2, 10.2) as the range for floating point and map that to (-8, 7)
e.g. scale = (10.2 - (-10.2)) / (7 - (-8))

SYMMETRIC_NO_CLIPPING_ERR is a variant of symmetric mapping, where the scale is the max of smin
and smax, where smin = min_val_neg / quant_min, and smax = max_val_pos / quant_max. By calculating
smin and smax individually, there can be less round error on negative values, and no out-of-range
of all floating point values.

asymmetric mapping means we just directly map the floating point range to integer range,
for the above example, we will map (-3.5, 10.2) to (-8, 7) and calculate quantization parameter
based on this mapping
e.g. scale = (10.2 - (-3.5)) / (7 - (-8))
r^   N)
rY   rZ   r[   r\   rx   r  	SYMMETRICSYMMETRIC_NO_CLIPPING_ERR
ASYMMETRICr]   r^   rC   r@   r.   r.   K  s    $ I $JrC   r.   c                   B    \ rS rSrSr\" 5       r\" 5       r\" 5       rSr	g)r6   ic  a8  Enum that indicate whether zero_point is in integer domain or floating point domain

integer domain: quantized_val = (float_val / scale) (integer) + zero_point (integer)
float domain: quantized_val = (float_val - (zero_point (float) - scale * mid_point)) / scale
none domain: quantized_val = (float_val / scale)
r^   N)
rY   rZ   r[   r\   rx   r  INTFLOATNONEr]   r^   rC   r@   r6   r6   c  s     &CFE6DrC   r6   c                   z    \ rS rSrSr\" 5       r\" 5       r\" 5       r\" 5       r	\" 5       r
\" 5       r\" 5       rSrg)r5   ip  z?
Placeholder for dtypes that do not exist in PyTorch core yet.
r^   N)rY   rZ   r[   r\   rx   r  INT1INT2INT3INT4INT5INT6INT7r]   r^   rC   r@   r5   r5   p  s:     6D6D6D6D6D6D6DrC   r5   T)frozenc                       \ rS rSrSrSrg)r-   i  z
Base class for representing the granularity of quantization.

This class serves as a parent for specific granularity types used in
quantization operations, such as per-tensor or per-axis quantization.
r^   NrY   rZ   r[   r\   rx   r]   r^   rC   r@   r-   r-     s    rC   r-   c                   .    \ rS rSr% Sr\\S4   \S'   Srg)r0   i  z
Represents per-block granularity in quantization. See
:func:`~torchao.quantization.quant_primitives.quantize_affine` for docs for
`block_size`

Attributes:
    block_size (Tuple[int, ...]): The size of each quantization group
.
block_sizer^   N)	rY   rZ   r[   r\   rx   r   r   r   r]   r^   rC   r@   r0   r0     s     c3hrC   r0   c                       \ rS rSrSrSrg)r3   i  z
Represents per-tensor granularity in quantization.

This granularity type calculates the quantization parameters
based off the entire tensor.

r^   Nr  r^   rC   r@   r3   r3     s    rC   r3   c                   $    \ rS rSr% Sr\\S'   Srg)r/   i  a  
Represents per-axis granularity in quantization.

This granularity type calculates different quantization parameters
along a specified axis of the tensor.

For example if the input tensor is shape [8, 16] and axis=0, then
the quantization parameters are calculated for each row of the tensor.
Giving a total of 8 quantization parameters.

Attributes:
    axis (int): The axis along which reduction is performed.
axisr^   NrY   rZ   r[   r\   rx   r   r   r]   r^   rC   r@   r/   r/     s     IrC   r/   c                   $    \ rS rSr% Sr\\S'   Srg)r1   i  a  
Represents per-channel group granularity in quantization.

This granularity type calculates different quantization parameters
for each group of <group_size> elements.

For example if the input tensor is shape [8, 16], and the group size is 4, then
the input tensor is reshaped to [64, 4]
quantization parameters are calculated for each group of 4 elements,
giving a total of 64 quantization parameters.

Attributes:
    group_size (int): The size of each quantization group


group_sizer^   Nr  r^   rC   r@   r1   r1     s      OrC   r1   c                       \ rS rSrSrSrg)r2   i  a  
Represents row-wise granularity in quantization.

This is a special case of per-axis quantization and is unique to Float8 matmuls
where the input is quantized with a block_size of (1, ..., input.shape[-1]). And the weight
is quantized with a block_size of (1, weight.shape[1]).
r^   Nr  r^   rC   r@   r2   r2     s    rC   r2   c                       \ rS rSrSrSrg)r4   i  a  
Represents per-token granularity in quantization.

This granularity type calculates a different set of quantization parameters
for each token, which is represented as the last dimension of the tensor.

For example, if the input tensor has shape [2, 3, 4], then there are 6 tokens
with 4 elements each, and we will calculate 6 sets of quantization parameters,
one for each token.

If the input tensor has only two dimensions, e.g. [8, 16], then this is
equivalent to `PerAxis(axis=0)`, which yields 8 sets of quantization parameters.
r^   Nr  r^   rC   r@   r4   r4     s    rC   r4   input_shape.granularityr   c                 .   [        U[        5      (       d   S5       e[        U[        5      (       a  U $ [        U[        5      (       a$  [	        U 5      nSX!R
                  '   [        U5      $ [        U[        5      (       a  S[        U 5      S-
  -  U S   4-   $ [        U[        5      (       a'  [        U 5      S:X  d
   SU  35       eSUR                  4$ [        U[        5      (       a  [	        U 5      nU S   US'   [        U5      $ [        SU 35      e)zGet the block size based on the input shape and granularity type.

Args:
    input_shape: The input tensor shape possibly more than 2 dimensions
    granularity: The granularity type of the quantization
z=Please provide an instance of Granularity, not subclass of itr   )r   r   r   zNExpecting input shape dim to be 2 for per group quantization, gotinput shape: zUnsupported Granularity: )
isinstancer-   r3   r/   r0  r  r   r2   r   r1   r  r4   
ValueError)r  r  r  s      r@   r7   r7     s%    [  GFG  +y))	K	)	)+&
'(
##$Z  	K	(	(s;'!+,B/AAA	K	*	*!	j[\g[hi	j!;))**	K	*	*+&
$R
2Z  
0>
??rC   c                   |  ^  \ rS rSrSr\" \5      rSSSSSS\R                  4S\
S\R                  S\S\\   S	\\   S
\\   S\\R                     S\\R                     S\S\\   4U 4S jjjr\S\R(                  S\R(                  4S j5       r\S\\R(                  \R(                  4   4S j5       rSrU =r$ )r,   i  a  Observer module for affine quantization (https://github.com/pytorch/ao/tree/main/torchao/quantization#affine-quantization)

Args:
  `granularity` and `block_size`: The granularity of the quantization,
    must specify at least one, if both are specified `block_size` takes precedence
    Current supported granularity type are `PerTensor` and `PerAxis`
  other args: please see `:class:torchao.dtypes.AffineQuantizedTensor`
NTmapping_typetarget_dtyper  r   r   r   scale_dtypezero_point_dtypepreserve_zerozero_point_domainc                    > [         TU ]  5         Uc   S5       eXl        X l        X0l        X@l        XPl        X`l        Xpl        Xl	        Xl
        Xl        S U l        S U l        g )Nzgranularity is None)rj   rA   r  r  r  r   r   r   r  r  r  r  r  original_dtype)r?   r  r  r  r   r   r   r  r  r  r  rR   rl   s               r@   rA   $AffineQuantizedObserverBase.__init__  sj     	&=(==&((&""& 0*!2"rC   inputr   c                     g)znforward function should take the input tensor
and updates internal stats and return the original input Tensor
Nr^   )r?   r  s     r@   rq   #AffineQuantizedObserverBase.forward1      rC   c                     g)zCalculate quantization parameter based on the stats attached to the observer module
and returns a tuple of scale and zero_point Tensor
Nr^   rM   s    r@   ru   -AffineQuantizedObserverBase.calculate_qparams7  r  rC   )r  r   r  r  r
  r  r   r   r  r  r  r  )rY   rZ   r[   r\   rx   rz   rP   rS   r6   r  r.   r   rk   r-   r   r   r   ry   rA   r   r   rq   r   ru   r]   r{   r|   s   @r@   r,   r,     s    J'I $(#'#-126"7F7J7J#!# kk# !	#
 C=# C=# e_# ekk*# #5;;/# # $O4# #@ U\\ ell  
 5u||)C#D  rC   r,   c                     [        U [        R                  R                  5      (       aE  U R                  R
                  R                  SS5      S   n[        R                  " SSU5      nX;   $ g)zCReturns true if given mod is an instance of Observer script module..r   z\.___torch_mangle_\d+r  F)	r   r   r   RecursiveScriptModule_cqualified_namesplitresub)modobs_type_namesuffixr$  s       r@   _is_observer_script_moduler  >  sY    #uyy6677&&,,S!4Q7vv.F;$$rC   c                     [        U [        R                  R                  R                  [        R                  R                  R
                  [        45      =(       d    [        U S5      $ )Nzquantization.observer)r   r   aoquantizationr&   FakeQuantizeBaser,   r  modules    r@   _is_activation_post_processr$  K  sT    HH!!..HH!!22'	
 E 
$F,C	DErC   c                     [        U [        R                  R                  5      (       a  [	        U S5      =(       d    [	        U S5      $ g)Nz.quantization.observer.PerChannelMinMaxObserverz;quantization.observer.MovingAveragePerChannelMinMaxObserverF)r   r   r   r  r  r"  s    r@   #_is_per_channel_script_obs_instancer&  V  sD    &%))99::)D
 
'Q
	

 rC   c                 x   [        5       n[        U [        R                  R                  5      (       a4  U R                  5       R                  5        H  u  p#SU;   d  M  X1U'   M     O3U R                  5       R                  5        H  u  p#SU;   d  M  X1U'   M     U R                  5       R                  Ul        U$ )zv
Returns the state dict corresponding to the observer stats.
Traverse the model state_dict and extract out the stats.
observeractivation_post_process)r   r   r   r   r  r   items	_metadata)r  odkvs       r@   r   r   `  s    
 
B#uyy6677NN$**,DAQ1 -
 NN$**,DA(A-1 - >>#--BLIrC   c           
      t   / n/ nU R                  5        HX  u  pEUS-   n[        U5      (       d  M  [        U5      (       a  UR                  X0 SX#/ 5        MC  UR	                  X0 SX#/ 5        MZ     U H  nSU;   d  SU;   d  M  [        SU S35      e   U H  nSU;   d  SU;   d  M  [        SU S35      e   g	)
z
Given input model and a state_dict containing model observer stats,
load the stats back into the model. The observer state_dict can be saved
using torch.ao.quantization.get_observer_state_dict
r  TFr(  r)  zMissing keys for observer z in state_dictzUnexpected keys for observer N)named_modulesr$  r&  r)  r   r  )r  obs_dictr   r   r$  r#  r   r-  s           r@   r   r   s  s     !L!#O))+&v..26:: 33b$r ,,b%PR , ?71<,QC~>  
 ?71</s.A  rC      )r   r   )rk   r   ig      0?)rk   r   r   r   r   r  )rk   r   r   rh   )rk   r   r  g      ?r   )r   r   rk   r   r   g      p?)Zrx   r  r   abcr   r   collectionsr   	functoolsr   typingr   r   r   torch.nnr   torch.ao.quantization.utilsr	   r
   r   r   r   __all__r9   rP   rd   objectre   r   Moduler&   r+   _ObserverBaser"   r#   r'   r$   r!   r    r(   r)   r%   r*   dataclassesr  enumr  r  r.   r6   r5   r-   r0   r3   r/   r1   r2   r4   r   r   r7   r,   r  r$  r&  r   r   rS   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r^   rC   r@   <module>r?     s  
 
  ' #      +\ 2**0 56)R(S (:3		 :BqXl qXn 0O84 O8d`. `FM
> M
`W,D WtfA7 fAR++< ++\D
, D
N <
< 
:
 
6
 " $ 0
d 
4   $   $
 { 
  
  $   $k  $ ${  ([ {  @sCx@/:@
38_@@6#uxx 6rE&D "++a3+G   3  +  )22
++u99 3   (6'?'?
++&& (@ ( $ /881PS8T  '?&H&H
++u:: 'I ' #
 4L3U3U
++'' 4V 4 0 "5!>!>
,,	 "? "  ":!C!C
,, F FPQ "D "  '?&H&H
..%"H"HRS 'I ' # 0D/M/M
#U\\QRU 0N 0 , -A,J,J
!5<<1PS -K - ) ,X ((Q %  2 rC   