
    IЦi                       % 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Jr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& r.S' r/S( r0S) r1S* r2\$Rg                  SS+S,9r4 \*r5 \+r6 \$Rg                  \Rn                  \Rp                  S-9r9 \$Rg                  \Rn                  \Rp                  S.S+S/S09r: \(Rg                  SS+S,9r; \&Rg                  \Rn                  \Rx                  S-9r= \&Rg                  \Rn                  \Rx                  S.S+S/S09r> \*Rg                  \R~                  SS1S2S39r@ \&Rg                  \R~                  \R                  SS49rB \&Rg                  \R                  \R                  SS49rD \)Rg                  S5S6\R~                  SS1S79rE\)Rg                  S8S\R~                  SS1S79rF\ErG\FrH \-rIg)9z
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DictListOptionalTuple)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UniformQuantizationObserverBasec                   2    \ rS rSrS rS rS rS rS rSr	g)	_PartialWrapper<   c                     Xl         0 U l        g N)pcallable_args)selfr4   s     ]/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/torch/ao/quantization/observer.py__init___PartialWrapper.__init__=   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$ r3   r5   r4   )r6   argskeywordsarg_names       r7   __call___PartialWrapper.__call__A   sM     **H'QhQ2D2DX2N2PQ + vvt(x((r:   c                 l    U R                   R                  5       U R                  R                  5       -   $ r3   )r4   __repr__r5   r6   s    r7   rC   _PartialWrapper.__repr__I   s'    vv 4#5#5#>#>#@@@r:   c                     [        U 40 UD6$ r3   )
_with_argsr6   kwargss     r7   	with_args_PartialWrapper.with_argsL   s    $)&))r:   c                 V    [        U R                  S9n0 U R                  EUEUl        U$ )N)r4   )r0   r4   r5   )r6   rI   results      r7   with_callable_args"_PartialWrapper.with_callable_argsO   s-     466*?$"4"4??r:   r<   N)
__name__
__module____qualname____firstlineno__r8   r@   rC   rJ   rN   __static_attributes__ r:   r7   r0   r0   <   s     )A*r:   r0   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
)r0   r   cls_or_selfrI   rs      r7   rG   rG   U   s    " 	6v67AHr:   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
rU   )r0   r   rN   rW   s      r7   _with_callable_argsr[   j   s'    ( 	,-A)&))r:   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 r3   )superr8   dtyper_   )r6   rb   r_   	__class__s      r7   r8   ObserverBase.__init__   s    
$r:   c                     g r3   rU   r6   xs     r7   forwardObserverBase.forward       r:   c                     g r3   rU   rH   s     r7   calculate_qparamsObserverBase.calculate_qparams   rj   r:   rb   r_   )F)rP   rQ   rR   rS   __doc__boolr8   r   rh   rl   classmethodrG   rJ   r[   rN   rT   __classcell__rc   s   @r7   r)   r)      sY    %$ % %
     J'I$%89r:   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 )Nrn   zPlease use quant_min and quant_max to specify the range for observers.                     reduce_range will be deprecated in a future release of PyTorch.rw   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 typerU   )!torchnnfactory_kwargsra   r8   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uint16rb   has_customized_qranger   r   	quant_min	quant_max)r6   rb   r}   r   r   r   r|   rw   r_   rI   _ALLOWED_DTYPESrc   s              r7   r8   (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*
&r:   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   rw   )getrz   r   finfofloat32rw   ra   _load_from_state_dict)r6   
state_dictprefixlocal_metadatastrictmissing_keysunexpected_keys
error_msgsr   rw   rc   s             r7   r   5UniformQuantizationObserverBase._load_from_state_dict  st     !$$Y5?gl,,EMM : > >?@C),v~&%	
r:   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.NrU   )r6   r   r   s      r7   _validate_qmin_qmax3UniformQuantizationObserverBase._validate_qmin_qmax,  sK    $ 'i'	?>	?'	?>	?' !	YX	Y!r:   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   )rb   r         i   )#r   rz   r   r   typer   r   min
zeros_likemaxonessizer   zerosint64r}   r   r   floatrw   rb   r   r   r   new_fullr   r   where	ones_likeroundtointclamplenshape)
r6   r   r   r   r   min_val_negmax_val_posr   scale
zero_points
             r7   _calculate_qparams2UniformQuantizationObserverBase._calculate_qparamsD  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/?/?
   r:   c                     [        S5      e)Nz2Cannot reset min/max values in the given observer.)NotImplementedErrorrD   s    r7   reset_min_max_vals2UniformQuantizationObserverBase.reset_min_max_vals  s    !"VWWr:   )r   r}   r   r   r   rx   N)rP   rQ   rR   rS   ro   _versionrz   Tensor__annotations__r   r   r   r   rw   r8   r   jitexportr   r   r   r   r   rT   rr   rs   s   @r7   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r:   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.rb   r}   r   r   r   r|   rw   r_   r   infr   -infz`Cannot reduce range for symmetric                                        quantization for quint8rU   )r   r   ra   r8   rz   r{   r|   r   r   r   r}   r   r   rb   r   )r6   rb   r}   r   r   r   r|   rw   r_   rI   rc   s             r7   r8   MinMaxObserver.__init__  s     W%%%2  	 
	
%)!
	
 
	
 00@YU5\(T^(TUYU6](Un(UVLLE666!!

ell*%@  + " 7r:   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   rb   rz   aminmaxr   r   r   copy_)r6   x_origrg   min_val_curmax_val_curr   r   s          r7   rh   MinMaxObserver.forward  s    <<>QMMMODD##$#(==#3 ))K6))K67#7#r:   c                 N    U R                  U R                  U R                  5      $ )z'Calculates the quantization parameters.r   r   r   rD   s    r7   rl    MinMaxObserver.calculate_qparams"  s     &&t||T\\BBr:   c                 :    SU R                    SU R                   3$ Nzmin_val=z
, max_val=r   r   rD   s    r7   
extra_reprMinMaxObserver.extra_repr'  s    $,,z$,,@@r:   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   rz   r   r   r   rD   s    r7   r   !MinMaxObserver.reset_min_max_vals+  sB     	5<<e565<<f67r:   rU   r   )rP   rQ   rR   rS   ro   rz   r   r   r   r   r   r   rw   r8   rh   r   r   rl   r   r   rT   rr   rs   s   @r7   r%   r%     s    =| \\\\ ll''KK&**1 
1 1f YYC C YYA A YY8 8r:   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&   i2  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 )rb   r}   r   r   r   rw   r_   rU   )r   r   averaging_constantra   r8   )r6   r   rb   r}   r   r   r   rw   r_   rI   rc   s             r7   r8   $MovingAverageMinMaxObserver.__init__`  s     W%%%!$ 
 #5$11Q6%))-)@)@(AC  	 		
%!		
 		
r:   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   rb   r   r   rz   r   r   r   )r6   r   rg   r   r   r   r   s          r7   rh   #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#r:   r   r   )rP   rQ   rR   rS   ro   rz   r   r   r   r   rw   r8   rh   rT   rr   rs   s   @r7   r&   r&   2  s_    +^  ll''KK&**!
 
!
 !
F r:   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 quint8rU   )r   r   ra   r8   rz   r{   r|   ch_axisr   r   r}   r   r   rb   r   )r6   r   rb   r}   r   r   r   r|   rw   r_   rI   rc   s              r7   r8   !PerChannelMinMaxObserver.__init__  s    g&&%w  %O  	 
	
%)!
	
 
	
 00@YR(J>(JKYR(J>(JKLLE777!!

ell*%K  + " 8r:   c                 $    U R                  U5      $ r3   )_forward)r6   r   s     r7   rh    PerChannelMinMaxObserver.forward  s    }}V$$r:   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   rb   rz   flattenr   r   r   resize_r   r   r6   r   rg   r   r   x_diminew_axis_listyr   r   s              r7   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      $ r3   r   rD   s    r7   rl   *PerChannelMinMaxObserver.calculate_qparams   s    &&t||T\\BBr:   c                 :    SU R                    SU R                   3$ r   r   rD   s    r7   r   #PerChannelMinMaxObserver.extra_repr      $,,z$,,@@r:   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   rv   min_valsmax_valsr   r   z2Observer load_from_state_dict got unexpected name F)r   r   r  r   r   r~   r   rz   r   is_scriptingr   appendra   r   )r6   r   r   r   r   r   r   r   r   local_stateexpected_min_nameexpected_max_namenamekeyvalrc   s                  r7   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) (r:   c           	      2    U R                  UUUUUUU5        g r3   )r   )r6   r   r   r   r   r   r   r   s           r7   _load_from_state_dict_script5PerChannelMinMaxObserver._load_from_state_dict_scriptC  s'     	""	
r:   c                 p    [         R                  " S5      U l        [         R                  " S5      U l        g)r   r   N)rz   randr   r   rD   s    r7   r   +PerChannelMinMaxObserver.reset_min_max_valsW  s,     zz
 zz
r:   )r   r   r   r   )rP   rQ   rR   rS   ro   rz   r   r   r   r   r   r   rw   r8   rh   r   r   r   rl   r   r   strr   rp   r	   r   r  r   rT   rr   rs   s   @r7   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

 

r:   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'   ie  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   rb   r}   r   r   r   rw   r_   rU   )r   r   ra   r8   r   )r6   r   r   rb   r}   r   r   r   rw   r_   rI   rc   s              r7   r8   .MovingAveragePerChannelMinMaxObserver.__init__  sv     g&&%w  %\  	 
	
%!
	
 
	
 #5r:   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   rb   r   r   r  r   r   r  rz   r  r   r   r  r   r   r  s              r7   rh   -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   )rP   rQ   rR   rS   ro   rz   r   r   r   r   rw   r8   rh   rT   rr   rs   s   @r7   r'   r'   e  sa    :  ll((KK&**!5 
!5 !5F r:   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binsrb   rx   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   r+  r   r   r   r   r      rU   )r   r   ra   r8   rz   r{   r|   r,  r   r   r   r   iinforb   bits	dst_nbinsupsample_rate)r6   r,  rb   r}   r   r   r   r|   rw   r_   rI   rc   s              r7   r8   HistogramObserver.__init__  s    W%%%2  %H  	 
	
%)!
	
 
	
 00@	[%++dii*R>*RSYU5\(T^(TUYU6](Un(UVekk$**5::: 	r:   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
rv   rU   )r6   r4  r5  r6  norms        r7   	_get_normHistogramObserver._get_norm  s0     !I-0IK0WW ~r:   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   r,  r1  rz   aranger+  r   r   divr   r9  r   r   sum)r6   r;  r<  	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_endr6  r8  r4  r5  dst_bin_of_end_centers                   r7   _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  r:   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㈵>r>  r   r   r   )r+  r   r,  r   r   rz   rE  rB  cumsumr   rO  )r6   rF  totalcSumstepsizealphabeta	start_binend_binnorm_min
next_alpha	next_betalrY   r;  r<  r8  new_minnew_maxs                      r7   _non_linear_param_search*HistogramObserver._non_linear_param_searchM  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!::r:   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   rA  T)rightr   )weights	minlength)	repeat_interleaver2  r,  rz   linspacer   r   	bucketizebincount)r6   r+  rb  rc  rd  re  bin_sizemid_points_histogramboundaries_new_histogrambucket_assignmentsupdate_histograms              r7   _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
  r:   	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)r,  r   r   )rz   rE  histcr,  rs  )	r6   ru  rb  rc  rv  rd  re  	bin_valuetransformed_orig_hists	            r7   _combine_histograms%HistogramObserver._combine_histograms  s     !j&<** 		+.IH99*U " )66 %%%%%% !% 7 7!
 22r:   rg   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   rz   rx  r,  r+  detach_)r6   rg   r   r   new_histograms        r7   reset_histogram!HistogramObserver.reset_histogram  s     	W]]+7#W]]+7#MMOq W]]_%9	65	69AyygK (()<)<=]+r:   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   rz   r   r   r~   r   absr   r   r   r  r   r   rx  r,  r   r+  r   r  r  r   r   r{  )r6   r   rg   x_minx_maxcurrent_mincurrent_maxis_uninitializedrd  re  r^  r_  rr  combined_histograms                 r7   rh   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+r:   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   rz   r   r   r   r,  r   r+  r`  r   )r6   r  r^  r_  s       r7   rl   #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8r:   c                 j   > [         TU ]  XU5        U R                  XS-   '   U R                  XS-   '   g )Nr   r   )ra   _save_to_state_dictr   r   )r6   destinationr   	keep_varsrc   s       r7   r  %HistogramObserver._save_to_state_dict6  s4    #KC*.,,Y&'*.,,Y&'r:   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   rv   r   r   r   r   r   )
r   r   rz   Sizer   r   setattrr  ra   r   )r6   r   r   r   r   r   r   r   r   min_val_namemax_val_namer  r  r  r  rc   s                  r7   r   'HistogramObserver._load_from_state_dict;  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(   	%	
r:   c                 :    SU R                    SU R                   3$ r   r   rD   s    r7   r   HistogramObserver.extra_reprd  r  r:   )r,  r1  r2  ) rP   rQ   rR   rS   ro   rz   r   r   r   r   r   r   rw   r   rb   r8   r9  rO  r   r`  rs  r{  r  rh   r   r   rl   r  r   r   rT   rr   rs   s   @r7   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r:   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#   ih  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 quantizationrn   r   )rb   r   rU   )r   ra   r8   r   r   r   rz   r   r   r   rb   r}   )
r6   r   r   rb   r}   r   r   r_   rI   rc   s
            r7   r8   FixedQParamsObserver.__init__w  s     %K  	FuFvF""WellE7%++&NO\5<<EII+VW
r:   c                     U$ r3   rU   )r6   Xs     r7   rh   FixedQParamsObserver.forward      r:   c                 2    U R                   U R                  4$ r3   )r   r   rD   s    r7   rl   &FixedQParamsObserver.calculate_qparams  s    zz4??**r:   )rb   r}   r   r   )rP   rQ   rR   rS   ro   rz   r   r   r   r   r8   rh   r   r   rl   rT   rr   rs   s   @r7   r#   r#   h  sa    	 << ll''. YY+ +r:   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 )Nrn   TzPlease use `is_dynamic` instead of `compute_dtype`.                     `compute_dtype` will be deprecated in a future release                     of PyTorch.)ra   r8   rz   r   r   r   rw   rb   r}   r   r   	custom_opr~   r   )
r6   rb   custom_op_namecompute_dtyper   r   r}   rw   r_   rc   s
            r7   r8   PlaceholderObserver.__init__  s     	u<?--G;++emm,00C 
""'JMM! r:   c                     U$ r3   rU   rf   s     r7   rh   PlaceholderObserver.forward  r  r:   c                 :    SU R                    SU R                   3$ )Nzdtype=z, is_dynamic=rn   rD   s    r7   r   PlaceholderObserver.extra_repr  s    

|=0ABBr:   c                     [        S5      e)Nz>calculate_qparams should not be called for PlaceholderObserver	ExceptionrD   s    r7   rl   %PlaceholderObserver.calculate_qparams  s    L
 	
r:   )r  rb   rw   r}   r   r   r   )rP   rQ   rR   rS   ro   rz   r   r8   rh   r   r   r   rl   rT   rr   rs   s   @r7   r+   r+     s~    0 mm  
   D YYC C YY
 
r:   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 NFrn   )ra   r8   r  )r6   rb   rc   s     r7   r8   RecordingObserver.__init__  s    u7r:   c                 X    U R                   R                  UR                  5       5        U$ r3   )r  r  clonerf   s     r7   rh   RecordingObserver.forward  s    qwwy)r:   c                     [        S5      e)Nz<calculate_qparams should not be called for RecordingObserverr  rD   s    r7   rl   #RecordingObserver.calculate_qparams  s    J
 	
r:   c                     U R                   $ r3   r  rD   s    r7   get_tensor_value"RecordingObserver.get_tensor_value  s    r:   r  )rP   rQ   rR   rS   ro   r	   r
   rz   r   r   r   r8   rh   r   r   rl   r  rT   rr   rs   s   @r7   r,   r,     so     $T(5<<*@%ABO"\\  YY
 

 YY r:   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  )ra   r8   rb   r  )r6   rb   r  rc   s      r7   r8   NoopObserver.__init__	  s    u7
'r:   c                     U$ r3   rU   rf   s     r7   rh   NoopObserver.forward  r  r:   c                     [        S5      e)Nz7calculate_qparams should not be called for NoopObserverr  rD   s    r7   rl   NoopObserver.calculate_qparams  s    E
 	
r:   )r  rb   r   )rP   rQ   rR   rS   ro   rz   float16r8   rh   r   r   rl   rT   rr   rs   s   @r7   r(   r(     s@     #]]2 ( (
 YY
 
r:   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)r_   )ra   r8   rz   r   )r6   rc   s    r7   r8   ReuseInputObserver.__init__&  s    %8r:   c                     U$ r3   rU   rf   s     r7   rh   ReuseInputObserver.forward)  r  r:   c                     [        S5      e)Nz=calculate_qparams should not be called for ReuseInputObserverr  rD   s    r7   rl   $ReuseInputObserver.calculate_qparams,  s    K
 	
r:   rU   r   )rP   rQ   rR   rS   ro   r8   rh   rz   r   r   rl   rT   rr   rs   s   @r7   r-   r-     s0    9 YY
 
r:   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)	
isinstancerz   r   RecursiveScriptModule_cqualified_namesplitresub)modobs_type_namesuffixr  s       r7   _is_observer_script_moduler  3  sY    #uyy6677&&,,S!4Q7vv.F;$$r:   c                     [        U [        R                  R                  R                  [        R                  R                  R
                  45      =(       d    [        U S5      $ )Nzquantization.observer)r  rz   aoquantizationr)   FakeQuantizeBaser  modules    r7   _is_activation_post_processr  =  sN    				+	+UXX-B-B-S-ST E 
$F,C	DEr:   c                     [        U [        R                  R                  5      (       a  [	        U S5      =(       d    [	        U S5      $ g)Nz.quantization.observer.PerChannelMinMaxObserverz;quantization.observer.MovingAveragePerChannelMinMaxObserverF)r  rz   r   r  r  r  s    r7   #_is_per_channel_script_obs_instancer  D  sD    &%))99::)D
 
'Q
	

 r:   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  rz   r   r  r   items	_metadata)r  odkvs       r7   r   r   N  s    
 
B#uyy6677NN$**,DAQ1 -
 NN$**,DA(A-1 - >>#--BLIr:   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           r7   r    r    a  s     !L!#O))+&v..26:: 33b$r ,,b%PR , ?71<,QC~>  
 ?71</s.A  r:      )r   r   )rb   r}   ig      0?)rb   r}   r   r   rw   r  T)rb   r   r   r_   )rb   r}   r   g      ?r   )r   r   rb   r   r   g      p?)Jro   r  r~   abcr   r   collectionsr   	functoolsr   typingr   r   r	   r
   r   rz   torch.nnr{   torch.ao.quantization.utilsr   r   r   r   r   __all__r0   rG   r[   objectr\   r   Moduler)   r.   _ObserverBaser%   r&   r*   r'   r$   r#   r+   r,   r(   r-   r  r  r  r   r    rJ   r   r   r   r   r   r   r"   r   r   r   r!   r   r   r   r   r   r   r   r   r   r   r   rU   r:   r7   <module>r     sZ  
 
  ' #  3 3   D 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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 r:   