o
    h'                    @   s  U d Z ddlZddlZddlmZmZ ddlmZ ddlm	Z	 ddl
mZmZ ddlZddlmZ ddlmZmZmZmZmZ g dZG d	d
 d
Zdd Zdd Zedefi Zeed< G dd deejZG dd deZeZ G dd deZ!G dd de!Z"G dd deZ#G dd de#Z$G dd deZ%G dd deZ&G d d! d!eZ'G d"d# d#eZ(G d$d% d%eZ)G d&d' d'eZ*	 dd(l+m,Z, dd)l-m.Z.m/Z/ G d*d+ d+e/Z0G d,d- d-e/Z1G d.d/ d/e/Z2e,d0d1G d2d3 d3Z3e,d0d1G d4d5 d5e3Z4e,d0d1G d6d7 d7e3Z5e,d0d1G d8d9 d9e3Z6e,d0d1G d:d; d;e3Z7G d<d= d=e3Z8G d>d? d?e3Z9d@e:e;dAf dBe3dCe:e;dAf fdDdEZ<G dFdG dGeejjZ=dHdI Z>dJdK Z?dLdM Z@dNdO ZAdPdQ ZBe!jCddRdSZD	 e'ZE	 e(ZF	 e!jCejGejHdTZI	 e!jCejGejHdUdRdVdWZJ	 e%jCddRdSZK	 e#jCejGejLdTZM	 e#jCejGejLdUdRdVdWZN	 e'jCejOddXd0dYZP	 e#jCejOejQddZZR	 e#jCejSejQddZZT	 e&jCd[d\ejOddXd]ZUe&jCd^dejOddXd]ZVeUZWeVZX	 e*ZYdS )_z
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                   @   s4   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZdS )_PartialWrapperc                 C   s   || _ i | _d S N)pcallable_args)selfr9    r<   r/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/ao/quantization/observer.py__init__L   s   
z_PartialWrapper.__init__c                 O   s<   | j D ]}||vri ||| j |  i}q| j|i |S r8   )r:   r9   )r;   argskeywordsarg_namer<   r<   r=   __call__P   s
   
z_PartialWrapper.__call__c                 C   s   | j  | j  S r8   )r9   __repr__r:   r;   r<   r<   r=   rC   X      z_PartialWrapper.__repr__c                 K   s   t | fi |S r8   )
_with_argsr;   kwargsr<   r<   r=   	with_args[   s   z_PartialWrapper.with_argsc                 K   s    t | jd}i | j||_|S )N)r9   )r7   r9   r:   )r;   rH   resultr<   r<   r=   with_callable_args^   s   z"_PartialWrapper.with_callable_argsN)__name__
__module____qualname__r>   rB   rC   rI   rK   r<   r<   r<   r=   r7   K   s    r7   c                 K   s   t t| fi |}|S )a9  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
    )r7   r   cls_or_selfrH   rr<   r<   r=   rF   d   s   rF   c                 K   s   t t| }|jdi |S )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
    Nr<   )r7   r   rK   rO   r<   r<   r=   _with_callable_argsy   s   rR   ABCc                       sP   e Zd ZdZd
def fddZedd Zedd	 Ze	e
Ze	eZ  ZS )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
    F
is_dynamicc                    s   t    || _|| _d S r8   )superr>   dtyperT   )r;   rV   rT   	__class__r<   r=   r>      s   

zObserverBase.__init__c                 C      d S r8   r<   r;   xr<   r<   r=   forward      zObserverBase.forwardc                 K   rY   r8   r<   rG   r<   r<   r=   calculate_qparams   r]   zObserverBase.calculate_qparams)F)rL   rM   rN   __doc__boolr>   r   r\   r^   classmethodrF   rI   rR   rK   __classcell__r<   r<   rW   r=   r%      s    

r%   c                	       s   e Zd ZU dZdZejed< ejej	dddde
ejjdf	d fddZ fd	d
ZejjdededdfddZejjdejdejdeejejf fddZejjdd Z  ZS )r*   aG  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	                    s  t j|}t jd||d|	 || _|rtd || _| 	dt j
|gfi | | jt jt jt jt jt jfv s@J dt jt jt jt jt jt jt jt jt jt jt jf}
| j|
v seJ d|
 d|d uol|d u| _| jrvt|| t||| j| j| j\| _| _ d S )NrV   rT   zPlease use quant_min and quant_max to specify the range for observers.                     reduce_range will be deprecated in a future release of PyTorch.rd   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_kwargsrU   r>   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uint16rV   has_customized_qranger   r   	quant_min	quant_max)r;   rV   rj   rm   r   r   ri   rd   rT   rH   _ALLOWED_DTYPESrW   r<   r=   r>      sV   

z(UniformQuantizationObserverBase.__init__c           
   	      sZ   | dd }|d u s|dkrtttjjg}	|	||d < t ||||||| d S )Nversion   rd   )getrg   ro   finfofloat32rd   rU   _load_from_state_dict)
r;   
state_dictprefixlocal_metadatastrictmissing_keysunexpected_keys
error_msgsr   rd   rW   r<   r=   r      s   
z5UniformQuantizationObserverBase._load_from_state_dictr   r   c                 C   s8   |d  kr|ksJ d J d||k sJ ddS )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   r<   r<   r=   _validate_qmin_qmax;  s   
z3UniformQuantizationObserverBase._validate_qmin_qmaxmin_valmax_valc           
      C   sP  t ||stjdg|jjdtjdg|jjdfS | j| j}}t|t|}t	|t|}|j}tj
| tj|d}tj| tj|d}	| jtjksW| jtjkrt	| |}|t|| d  }t	|| j}| jtjtjfv r| jr|	|	 || d }	nb|	|	 d}	nY| jtjfv r|	|	 d}	nI| jtjkr|| t||  }t|| jk|t|}d| | }	n%|| t||  }t	|| j}|t|| tj }	t |	||}	t!|j"dkrtjt|g|j|d}t!|	j"dkr$tjt|	g|	j|d}	| jtjkr$tjt|	g|	j|d}	||	fS )	a  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   )rV   r         i   )#r	   rg   ro   r   typer   r   min
zeros_likemaxonessizer   zerosint64rj   rq   rs   floatrd   rV   rv   rz   r   new_fullr   rt   where	ones_likeroundtointclamplenshape)
r;   r   r   r   r   min_val_negmax_val_posr   scale
zero_pointr<   r<   r=   _calculate_qparamsS  sV   

z2UniformQuantizationObserverBase._calculate_qparamsc                 C      t d)Nz2Cannot reset min/max values in the given observer.)NotImplementedErrorrD   r<   r<   r=   reset_min_max_vals  s   z2UniformQuantizationObserverBase.reset_min_max_valsre   N)rL   rM   rN   r_   _versionrg   Tensor__annotations__rv   rp   r   r   rd   r>   r   jitexportr   r   tupler   r   rb   r<   r<   rW   r=   r*      s8   
 *
<Pr*   c                	       s   e Zd ZU dZejed< ejed< ejejdddde	ej
jdf	d fddZd	d
 Zejjdd Zejjdd Zejjdd Z  ZS )r!   a
  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   FNre   c	           
         s   t |stdt jd||||||||d|	 tj|}| dtjt	dfi | | dtjt	dfi | | j
tjkrQ| jrS| jtjkrUtdd S d S d S )	NzqMinMaxObserver's qscheme only support torch.per_tensor_symmetric                     and torch.per_tensor_affine.rV   rj   rm   r   r   ri   rd   rT   r   infr   -infz`Cannot reduce range for symmetric                                        quantization for quint8r<   )r   r   rU   r>   rg   rh   ri   rn   ro   r   rj   rq   rm   rV   rv   )
r;   rV   rj   rm   r   r   ri   rd   rT   rH   rW   r<   r=   r>     s8   	zMinMaxObserver.__init__c                 C   sl   |  dkr|S | }|| jj}t|\}}t|| j}t|| j	}| j
| | j	
| |S )z1Records the running minimum and maximum of ``x``.r   )numeldetachr   r   rV   rg   aminmaxr   r   r   copy_)r;   x_origr[   min_val_curmax_val_curr   r   r<   r<   r=   r\   $  s   zMinMaxObserver.forwardc                 C      |  | j| jS )z'Calculates the quantization parameters.r   r   r   rD   r<   r<   r=   r^   1  s   z MinMaxObserver.calculate_qparamsc                 C      d| j  d| j S Nzmin_val=z
, max_val=r   r   rD   r<   r<   r=   
extra_repr6     zMinMaxObserver.extra_reprc                 C   s0   | j ttd | jttd dS )Resets the min/max values.r   r   N)r   r   rg   ro   r   r   rD   r<   r<   r=   r   :  s   z!MinMaxObserver.reset_min_max_valsr   )rL   rM   rN   r_   rg   r   r   rv   rp   r   r   rd   r>   r\   r   r   r^   r   r   rb   r<   r<   rW   r=   r!     s,   
 
>
3

r!   c                	       sL   e Zd ZdZdejejdddeejj	df	d
 fddZ
dd	 Z  ZS )r"   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?FNre   c	           
   
      s`   t |std| || _|r| jdkrtd| j t jd|||||||d|	 d S )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 )rV   rj   rm   r   r   rd   rT   r<   )r   r   averaging_constantrU   r>   )
r;   r   rV   rj   rm   r   r   rd   rT   rH   rW   r<   r=   r>   o  s0   
z$MovingAverageMinMaxObserver.__init__c                 C   s   |  dkr|S | }|| jj}| j}| j}|tdkr-|tdkr-t|\}}nt|\}}|| j	||   }|| j	||   }| j
| | j
| |S )Nr   r   r   )r   r   r   r   rV   r   r   rg   r   r   r   )r;   r   r[   r   r   r   r   r<   r<   r=   r\     s   z#MovingAverageMinMaxObserver.forwardr   )rL   rM   rN   r_   rg   rv   rp   r   r   rd   r>   r\   rb   r<   r<   rW   r=   r"   A  s    /#r"   c                       s   e Zd ZU dZejed< ejed< dejejdddde	ej
jdf		d fdd	Zd
d Zdd Zejjdd Zdd Zdeeef dedeeejf dedee dee dee f fddZdeeef dedeeejf dedee dee dee fddZejjdd Z  ZS ) r&   a4  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   FNre   c
                    s   t |std|	rtdt jd||||||||	d|
 tj|}|| _| dtj	g fi | | dtj	g fi | | j
tjkrV| jrX| jtjkrZtdd S d S d S )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   rU   r>   rg   rh   ri   ch_axisrn   ro   rj   rs   rm   rV   rv   )r;   r   rV   rj   rm   r   r   ri   rd   rT   rH   rW   r<   r=   r>     sB   	z!PerChannelMinMaxObserver.__init__c                 C   s
   |  |S r8   )_forward)r;   r   r<   r<   r=   r\     s   
z PerChannelMinMaxObserver.forwardc           
      C   s
  |  dkr|S | }| j}| j}| }dd tt|D }d|| j< | j|d< ||}|	| jj
}tj|dd}|  dksJ|  dkrTtj|dd\}}ntj|dd\}}	t||}t|	|}| j|j | j|j | j| | j| |S )Nr   c                 S      g | ]}|qS r<   r<   .0ir<   r<   r=   
<listcomp>      z5PerChannelMinMaxObserver._forward.<locals>.<listcomp>r   	start_dimdim)r   r   r   r   r   ranger   r   permuter   rV   rg   flattenr   r   r   resize_r   r   
r;   r   r[   r   r   x_dimnew_axis_listyr   r   r<   r<   r=   r     s,   


z!PerChannelMinMaxObserver._forwardc                 C   r   r8   r   rD   r<   r<   r=   r^     s   z*PerChannelMinMaxObserver.calculate_qparamsc                 C   r   r   r   rD   r<   r<   r=   r     rE   z#PerChannelMinMaxObserver.extra_reprr   r   r   r   r   r   r   c              	      s   | dd }|d ur|dk rddg}	d}
d}nddg}	d}
d}|	D ]Y}|| }||v rs|| }||
kr;| j|j n||krG| j|j ntd|  tj	 rr||
kr_| j
| q!||krj| j
| q!td|  q!|rz|| q!tj	 st |||d||| d S d S )	Nr   rc   min_valsmax_valsr   r   z2Observer load_from_state_dict got unexpected name F)r   r   r   r   r   rk   rl   rg   r   is_scriptingr   appendrU   r   )r;   r   r   r   r   r   r   r   r   local_stateexpected_min_nameexpected_max_namenamekeyvalrW   r<   r=   r     sT   



z.PerChannelMinMaxObserver._load_from_state_dictc              	   C   s   |  ||||||| d S r8   )r   )r;   r   r   r   r   r   r   r   r<   r<   r=   _load_from_state_dict_scriptR  s   
z5PerChannelMinMaxObserver._load_from_state_dict_scriptc                 C   s   t d| _t d| _dS )r   r   N)rg   randr   r   rD   r<   r<   r=   r   f  s   
z+PerChannelMinMaxObserver.reset_min_max_valsr   )rL   rM   rN   r_   rg   r   r   rv   rr   r   r   rd   r>   r\   r   r   r   r^   r   dictstrr   r`   listr   r   r   rb   r<   r<   rW   r=   r&     sj   
 

.

<

r&   c                
       sN   e Zd ZdZddejejdddeejj	df		d fddZ
d	d
 Z  ZS )r#   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   FNre   c
                    sJ   t |std|	rtdt jd||||||||	d|
 || _d S )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   rV   rj   rm   r   r   rd   rT   r<   )r
   r   rU   r>   r   )r;   r   r   rV   rj   rm   r   r   rd   rT   rH   rW   r<   r=   r>     s*   	
z.MovingAveragePerChannelMinMaxObserver.__init__c           
      C   s  |  dkr|S | }|| jj}| j}| j}| }dd tt|D }d|| j	< | j	|d< |
|}tj|dd}|  dksJ|  dkrTtj|dd\}}ntj|dd\}}	|| j||   }|| j|	|   }| j|j | j|j | j| | j| |S )Nr   c                 S   r   r<   r<   r   r<   r<   r=   r     r   zAMovingAveragePerChannelMinMaxObserver.forward.<locals>.<listcomp>r   r   r   )r   r   r   r   rV   r   r   r   r   r   r   rg   r   r   r   r   r   r   r   r<   r<   r=   r\     s,   


z-MovingAveragePerChannelMinMaxObserver.forwardr   )rL   rM   rN   r_   rg   rv   rr   r   r   rd   r>   r\   rb   r<   r<   rW   r=   r#   t  s    #r#   c                       s  e Zd ZU dZejed< ejed< ejed< dejejdddde	ej
jdf	ded	ejd
df fddZdejdejdejd
ejfddZdedefddZd
eejejf fddZdejdejdejdejdejf
ddZdejdejdejdejdejdejd
ejfd d!Zd"ejdejdejd
dfd#d$Zd%ejd
ejfd&d'Zejjd(d) Z fd*d+Z fd,d-Zd.d/ Z  ZS )0r    aT  
    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binsrV   re   c
                    s   t |std|	rtdt jd||||||||	d|
 tj|}|| _| dtj	| jfi | | dtj
tdfi | | dtj
tdfi | d	t| jj | _d
| _d S )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      r<   )r   r   rU   r>   rg   rh   ri   r   rn   r   ro   r   iinforV   bits	dst_nbinsupsample_rate)r;   r   rV   rj   rm   r   r   ri   rd   rT   rH   rW   r<   r=   r>     s8   	zHistogramObserver.__init__delta_begin	delta_enddensityc                 C   s$   || | || |  d }|| S )a  
        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
        rc   r<   )r;   r   r   r   normr<   r<   r=   	_get_norm  s   zHistogramObserver._get_normnext_start_binnext_end_binc              	   C   s~  | j  | j  | j }||| d  | j }|dkrdS tj| j| jjd}|| | }|| }t	tj
||ddd| jd }|d | }	t	tj
||ddd| jd }
| j| }tj| j| jjd}||	 }|d }|| |tj| j| jjd| |7 }||
| d | t| d t|d | 7 }|
| |d  }| d }|| }|| t|||7 }|  S )	z
        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   r   rg   aranger   r   r   divr   r   r   ro   sum)r;   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_endr   r   r   r   dst_bin_of_end_centerr<   r<   r=   _compute_quantization_error&  sF   

z-HistogramObserver._compute_quantization_errorc                 C   s  | j  d | jksJ d| j| j | j }t| j  }tj| j dd}d}d}d}d}| jd }t	d}	||k r|| }
|| }|}|}||k rd|| |
| k rd|d }||k rd|| |
| k sT||kr|| || kr|d }||kr|| || ksp|}|}|| || kr|}|
}n|}|}||kr||krq8| 
||}||	krn
|}	|}|}||k s<| j||  }| j||d   }||fS )	aZ  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   rg   r  r  cumsumr   r  )r;   r  totalcSumstepsizealphabeta	start_binend_binnorm_min
next_alpha	next_betalrQ   r   r   r   new_minnew_maxr<   r<   r=   _non_linear_param_search\  sP   
%z*HistogramObserver._non_linear_param_searchorig_minorig_max
update_min
update_maxc                 C   s   | | j| j }|| | j| j  }tj||| j| j d |jdd d |jd|  }tj||| jd |jd|j}tj||ddd }	| jd |	|	| jk< d|	|	dk < tj|	|| jd}
|
S )	Nr   r   r   r  T)rightr   )weights	minlength)	repeat_interleaver   r   rg   linspacer   r   	bucketizebincount)r;   r   r!  r"  r#  r$  bin_sizemid_points_histogramboundaries_new_histogrambucket_assignmentsupdate_histogramr<   r<   r=   _upscale_histogram  s:   
	z$HistogramObserver._upscale_histogram	orig_histupdate_histc           	      C   s|   ||kr||kr|| S ||kr%t |}t j|| j||d| }|| S ||ks+J ||ks1J | |||||}|| S )N)r   r   r   )rg   r  histcr   r1  )	r;   r2  r!  r"  r3  r#  r$  	bin_valuetransformed_orig_histr<   r<   r=   _combine_histograms  s&   
z%HistogramObserver._combine_histogramsr[   c                 C   s   | j |j | j | | j|j | j| | dkr&| dks*J dtj|| j||d}| j	
 |j | j	| d S )Nr   z(histogram min/max values must be scalar.r   r   )r   r   r   r   r   r   rg   r4  r   r   detach_)r;   r[   r   r   new_histogramr<   r<   r=   reset_histogram  s   z!HistogramObserver.reset_histogramr   c                 C   s  |  dkr|S | }t|\}}|tj ks|tjkr;td || tjk }|  dkr4|S t|\}}| j}| j	}| jt
dkpN| j	t
dk}|rZ| ||| |S ||}}	t||}
t||	}|
 | }
}tj|| j|
|d| jj}|
|kr||kr| j| }| j |j | j| |S | | j||||
|}| j |j | j| | j |
j | j|
 | j	 |j | j	| |S )Nr   z2torch.inf detected in input tensor, ignoring inputr   r   r8  )r   r   rg   r   r   rk   rl   absr   r   r   r;  r   r   r4  r   r   r   r   r9  r   r   r   r7  )r;   r   r[   x_minx_maxcurrent_mincurrent_maxis_uninitializedr#  r$  r  r  r0  combined_histogramr<   r<   r=   r\     sZ   
 



zHistogramObserver.forwardc                 C   s   | j tdko| jtdk}|r+td tjdg| j jjdtjdg| j jjdfS | j	t
| jks7J d|  \}}| ||S )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   rk   rl   rg   ro   r   r   r   r   r   r   r   )r;   rA  r  r  r<   r<   r=   r^   /  s   z#HistogramObserver.calculate_qparamsc                    s0   t  ||| | j||d < | j||d < d S )Nr   r   )rU   _save_to_state_dictr   r   )r;   destinationr   	keep_varsrW   r<   r=   rC  E  s   z%HistogramObserver._save_to_state_dictc              	      s   | dd }|d u s|dk rG|d |d }	}
|	|v r/||	 jtdgkr/ttd||	< |
|v rG||
 jtdgkrGttd||
< ddg}|D ]}|| }||v rb|| }t| || qM|ri|| qMt 	||||||| d S )Nr   rc   r   r   r   r   r   )
r   r   rg   Sizero   r   setattrr   rU   r   )r;   r   r   r   r   r   r   r   r   min_val_namemax_val_namer   r   r   r   rW   r<   r=   r   J  s6   

z'HistogramObserver._load_from_state_dictc                 C   r   r   r   rD   r<   r<   r=   r   s  rE   zHistogramObserver.extra_repr)rL   rM   rN   r_   rg   r   r   rv   rp   r   r   rd   r   rV   r>   r   r  r   r   r1  r7  r;  r\   r   r   r^   rC  r   r   rb   r<   r<   rW   r=   r      s   
 


,
6?
)
'
6
)r    c                       s^   e Zd ZU dZejed< ejed< ejejdddf fdd	Z	d	d
 Z
ejjdd Z  ZS )r   aU  
    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           	         st   |rt dt jd||d| || _|| _| dtj|gtjd | dtj|gtj	d || _
|| _d S )Nz9FixedQParamsObserver doesn't support dynamic quantizationrf   r   )rV   r   r<   )r   rU   r>   r   r   rn   rg   ro   r   r   rV   rj   )	r;   r   r   rV   rj   r   r   rT   rH   rW   r<   r=   r>     s   
zFixedQParamsObserver.__init__c                 C      |S r8   r<   )r;   Xr<   r<   r=   r\        zFixedQParamsObserver.forwardc                 C   s   | j | jfS r8   )r   r   rD   r<   r<   r=   r^     s   z&FixedQParamsObserver.calculate_qparams)rL   rM   rN   r_   rg   r   r   rv   rp   r>   r\   r   r   r^   rb   r<   r<   rW   r=   r   w  s   
 

r   c                       s`   e Zd ZdZejdddddddf	d fddZdd	 Zejj	d
d Z
ejj	dd Z  ZS )r'   ai  
    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.
     NFre   c	           	         sr   t  j||d |d u rtj}|d u rttjj}|| _|| _|| _	|| _
|| _|| _|r7d}td d S d S )Nrf   TzPlease use `is_dynamic` instead of `compute_dtype`.                     `compute_dtype` will be deprecated in a future release                     of PyTorch.)rU   r>   rg   rp   r   r   rd   rV   rj   r   r   	custom_oprk   rl   )	r;   rV   custom_op_namecompute_dtyper   r   rj   rd   rT   rW   r<   r=   r>     s"   zPlaceholderObserver.__init__c                 C   rK  r8   r<   rZ   r<   r<   r=   r\     rM  zPlaceholderObserver.forwardc                 C   r   )Nzdtype=z, is_dynamic=rf   rD   r<   r<   r=   r     r   zPlaceholderObserver.extra_reprc                 C   r   )Nz>calculate_qparams should not be called for PlaceholderObserver	ExceptionrD   r<   r<   r=   r^        z%PlaceholderObserver.calculate_qparamsr   )rL   rM   rN   r_   rg   r   r>   r\   r   r   r   r^   rb   r<   r<   rW   r=   r'     s$    
"
r'   c                       s`   e Zd ZdZdeeej  iZej	f fdd	Z
dd Zejjdd Zejjd	d
 Z  ZS )r(   a   
    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                    s   t  j|dd g | _d S NFrf   )rU   r>   rU  )r;   rV   rW   r<   r=   r>     s   
zRecordingObserver.__init__c                 C   s   | j |  |S r8   )rU  r   clonerZ   r<   r<   r=   r\     s   zRecordingObserver.forwardc                 C   r   )Nz<calculate_qparams should not be called for RecordingObserverrR  rD   r<   r<   r=   r^     rT  z#RecordingObserver.calculate_qparamsc                 C   s   | j S r8   )rU  rD   r<   r<   r=   get_tensor_value  s   z"RecordingObserver.get_tensor_value)rL   rM   rN   r_   r   r   rg   r   r   rv   r>   r\   r   r   r^   rX  rb   r<   r<   rW   r=   r(     s    
r(   c                       sB   e Zd ZdZejdfd fddZdd Zejj	d	d
 Z
  ZS )r$   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).
    rN  re   Nc                    s    t  j|dd || _|| _d S rV  )rU   r>   rV   rO  )r;   rV   rP  rW   r<   r=   r>     s   
zNoopObserver.__init__c                 C   rK  r8   r<   rZ   r<   r<   r=   r\     rM  zNoopObserver.forwardc                 C   r   )Nz7calculate_qparams should not be called for NoopObserverrR  rD   r<   r<   r=   r^      rT  zNoopObserver.calculate_qparamsr   )rL   rM   rN   r_   rg   float16r>   r\   r   r   r^   rb   r<   r<   rW   r=   r$   
  s    r$   c                       s:   e Zd ZdZd
 fddZdd Zejjdd	 Z	  Z
S )r)   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
    re   Nc                    s   t  jtjdd d S )NF)rT   )rU   r>   rg   rv   rD   rW   r<   r=   r>   5  s   zReuseInputObserver.__init__c                 C   rK  r8   r<   rZ   r<   r<   r=   r\   8  rM  zReuseInputObserver.forwardc                 C   r   )Nz=calculate_qparams should not be called for ReuseInputObserverrR  rD   r<   r<   r=   r^   ;  rT  z$ReuseInputObserver.calculate_qparamsr   )rL   rM   rN   r_   r>   r\   rg   r   r   r^   rb   r<   r<   rW   r=   r)   '  s    r)   )	dataclass)autoEnumc                   @   "   e Zd ZdZe Ze Ze ZdS )r-   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))
    N)rL   rM   rN   r_   r[  	SYMMETRICSYMMETRIC_NO_CLIPPING_ERR
ASYMMETRICr<   r<   r<   r=   r-   K  s
    
r-   c                   @   r]  )r5   aH  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)
    N)rL   rM   rN   r_   r[  INTFLOATNONEr<   r<   r<   r=   r5   c  s
    
r5   c                   @   s:   e Zd ZdZe Ze Ze Ze Ze Z	e Z
e ZdS )r4   zG
    Placeholder for dtypes that do not exist in PyTorch core yet.
    N)rL   rM   rN   r_   r[  INT1INT2INT3INT4INT5INT6INT7r<   r<   r<   r=   r4   p  s    
r4   T)frozenc                   @      e Zd ZdZdS )r,   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.
    NrL   rM   rN   r_   r<   r<   r<   r=   r,         r,   c                   @   s"   e Zd ZU dZeedf ed< dS )r/   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_sizeN)rL   rM   rN   r_   r   r   r   r<   r<   r<   r=   r/     s   
 	r/   c                   @   rl  )r2   z
    Represents per-tensor granularity in quantization.

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

    Nrm  r<   r<   r<   r=   r2     rn  r2   c                   @      e Zd ZU dZeed< dS )r.   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.
    axisNrL   rM   rN   r_   r   r   r<   r<   r<   r=   r.     s   
 r.   c                   @   rp  )r0   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_sizeNrr  r<   r<   r<   r=   r0     s   
 r0   c                   @   rl  )r1   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]).
    Nrm  r<   r<   r<   r=   r1         r1   c                   @   rl  )r3   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.
    Nrm  r<   r<   r<   r=   r3     rt  r3   input_shape.granularityre   c                 C   s   t |ts	J dt |tr| S t |tr"t| }d||j< t|S t |tr4dt| d  | d f S t |t	rKt| dksFJ d|  d|j
fS t |tr^t| }| d |d< t|S td| )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,   r2   r.   r   rq  r   r1   r   r0   rs  r3   
ValueError)ru  rv  ro  r<   r<   r=   r6     s.   	






r6   c                       s   e Zd ZdZeeZddddddejfde	de
jdedee dee d	ee d
ee
j dee
j dedee f fddZede
jde
jfddZedee
je
jf fddZ  ZS )r+   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_dtyperv  r   r   rd   scale_dtypezero_point_dtypepreserve_zerozero_point_domainc                    sf   t    |d usJ d|| _|| _|| _|| _|| _|| _|| _|| _	|	| _
|
| _d | _d | _d S )Nzgranularity is None)rU   r>   ry  rz  rv  r   r   rd   r{  r|  r}  r~  ro  original_dtype)r;   ry  rz  rv  r   r   rd   r{  r|  r}  r~  rH   rW   r<   r=   r>     s   

z$AffineQuantizedObserverBase.__init__inputre   c                 C      dS )z~forward function should take the input tensor
        and updates internal stats and return the original input Tensor
        Nr<   )r;   r  r<   r<   r=   r\   1      z#AffineQuantizedObserverBase.forwardc                 C   r  )zCalculate quantization parameter based on the stats attached to the observer module
        and returns a tuple of scale and zero_point Tensor
        Nr<   rD   r<   r<   r=   r^   7  r  z-AffineQuantizedObserverBase.calculate_qparams)rL   rM   rN   r_   ra   rF   rI   r5   ra  r-   rg   rV   r,   r   r   r   r`   r>   r   r   r\   r   r^   rb   r<   r<   rW   r=   r+     sF    		
 $r+   c                 C   s<   t | tjjr| jjddd }tdd|}||v S dS )zCReturns true if given mod is an instance of Observer script module..r   z\.___torch_mangle_\d+rN  F)	rw  rg   r   RecursiveScriptModule_cqualified_namesplitresub)modobs_type_namesuffixr   r<   r<   r=   _is_observer_script_module>  s
   r  c                 C   s&   t | tjjjtjjjtfpt| dS )Nzquantization.observer)rw  rg   aoquantizationr%   FakeQuantizeBaser+   r  moduler<   r<   r=   _is_activation_post_processK  s   r  c                 C   s&   t | tjjrt| dpt| dS dS )Nz.quantization.observer.PerChannelMinMaxObserverz;quantization.observer.MovingAveragePerChannelMinMaxObserverF)rw  rg   r   r  r  r  r<   r<   r=   #_is_per_channel_script_obs_instanceV  s   r  c                 C   sr   t  }t| tjjr|   D ]\}}d|v r|||< qn|   D ]\}}d|v r0|||< q$|  j|_|S )z
    Returns the state dict corresponding to the observer stats.
    Traverse the model state_dict and extract out the stats.
    observeractivation_post_process)r   rw  rg   r   r  r   items	_metadata)r  odkvr<   r<   r=   r   `  s   r   c              
   C   s   g }g }|   D ]'\}}|d }t|r/t|r$|||i d||g  q|||i d||g  q|D ]}d|v s<d|v rDtd| dq2|D ]}d|v sQd|v rYtd| dqGd	S )
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   rS  )r  obs_dictr   r   r   r  r   r  r<   r<   r=   r   s  s4   

r      )r   r   )rV   rj   ig      0?)rV   rj   r   r   rd   rJ  )rV   r   r   rT   )rV   rj   r   g      ?r   )r   r   rV   r   r   g      p?)Zr_   r  rk   abcr   r   collectionsr   	functoolsr   typingr   r   rg   torch.nnrh   torch.ao.quantization.utilsr   r	   r
   r   r   __all__r7   rF   rR   objectrS   r   Moduler%   r*   _ObserverBaser!   r"   r&   r#   r    r   r'   r(   r$   r)   dataclassesrZ  enumr[  r\  r-   r5   r4   r,   r/   r2   r.   r0   r1   r3   r   r   r6   r+   r  r  r  r   r   rI   r   r   r   ru   rq   r   r   r   rs   r   r   rv   r   rt   r   rw   r   r   r   r   r   r   r<   r<   r<   r=   <module>   s   	.! x c QZ   ,.G	




 9
"

