a
    OSic
                     @   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mZmZmZ ddlZddlmZ ddlmZmZ G dd	 d	eZd
d Zdd Ze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( Z+d)d* Z,d+d, Z-d-d. Z.d/d0 Z/e!j0dd1d2Z1e'Z2e(Z3e!j0ej4ej5d3Z6e!j0ej4ej5d4d1d5d6Z7e%j0dd1d2Z8e#j0ej4ej9d3Z:e!j0ej4ej9d4d1d5d6Z;e'j0ej<ej=d7Z>e#j0ej=ej?dd8Z@e#j0ejAej?dd8ZBe&j0d9d:ej=dd;d<ZCe&j0d=dej=dd;d<ZDeCZEeDZFe*ZGd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ListTupleOptionalDict)check_min_max_validcalculate_qmin_qmaxc                   @   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)selfr    r   Z/var/www/html/django/DPS/env/lib/python3.9/site-packages/torch/ao/quantization/observer.py__init__   s    z_PartialWrapper.__init__c                 O   s<   | j D ]$}||vri ||| j |  i}q| j|i |S r   )r   r   )r   argskeywordsarg_namer   r   r   __call__   s    
z_PartialWrapper.__call__c                 C   s   | j  | j  S r   )r   __repr__r   r   r   r   r   r      s    z_PartialWrapper.__repr__c                 K   s   t | fi |S r   )
_with_argsr   kwargsr   r   r   	with_args"   s    z_PartialWrapper.with_argsc                 K   s    t | jd}i | j||_|S )N)r   )r   r   r   )r   r   resultr   r   r   with_callable_args%   s    z"_PartialWrapper.with_callable_argsN)__name__
__module____qualname__r   r   r   r   r    r   r   r   r   r      s
   r   c                 K   s   t t| fi |}|S )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::

        >>> 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
    )r   r   cls_or_selfr   rr   r   r   r   +   s    r   c                 K   s   t t| }|jf 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::

        >>> Foo.with_callable_args = classmethod(_with_callable_args)
        >>> Foo.with_args = classmethod(_with_args)
        >>> foo_builder = Foo.with_callable_args(cur_time=get_time_func).with_args(name="dan")
        >>> foo_instance1 = foo_builder()
        >>> wait 50
        >>> foo_instance2 = foo_builder()
        >>> id(foo_instance1.creation_time) == id(foo_instance2.creation_time)
        False
    )r   r   r    r$   r   r   r   _with_callable_args>   s    r'   ABCc                       sH   e Zd ZdZ fddZedd Zedd Zee	Z
eeZ  ZS )ObserverBasea  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: Quantized data type
    c                    s   t t|   || _d S r   )superr)   r   dtype)r   r+   	__class__r   r   r   e   s    zObserverBase.__init__c                 C   s   d S r   r   r   xr   r   r   forwardi   s    zObserverBase.forwardc                 K   s   d S r   r   r   r   r   r   calculate_qparamsm   s    zObserverBase.calculate_qparams)r!   r"   r#   __doc__r   r   r0   r1   classmethodr   r   r'   r    __classcell__r   r   r,   r   r)   X   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fdd fddZ fd	d
ZejjeeddddZejjejejeejejf dddZejjdd Z  ZS )UniformQuantizationObserverBasea  Common base for all observers using uniform quantization to calculate
    scale and zero_point.

    Args:
        dtype: Quantized data type.
        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``.

    .. 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 || _|r.td || _| 	dt j
|gfi | | jt jt jt jt jt jfv svJ d| jt jt jt jt jfv sJ d|d uo|d u| _| jr| || t||| j| j| j\| _| _d S )Nr+   zPlease use quant_min and quant_max to specify the range for observers.                     reduce_range will be deprecated in a future release of PyTorch.r7   zDefault Observer only works for per_tensor_affine,                 per_tensor_symmetric, per_channel_affine,                 per_channel_symmetric and per_channel_float_qparams quantization schemezDDefault Observer only works for qint8, quint8 and quint4x2 data type)torchnnfactory_kwargsr*   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_qparamsr+   qint8quint8quint4x2qint32has_customized_qrange_validate_qmin_qmaxr   	quant_min	quant_maxr   r+   r>   rA   rO   rP   r=   r7   r,   r   r   r      sB    
	z(UniformQuantizationObserverBase.__init__c           
   	      s^   | dd }|d u s|dkr>tttjjg}	|	||d < tt| ||||||| d S )Nversion   r7   )	getr;   rC   finfofloat32r7   r*   r)   _load_from_state_dict)
r   
state_dictprefixlocal_metadatastrictmissing_keysunexpected_keys
error_msgsrR   r7   r,   r   r   rW      s    
z5UniformQuantizationObserverBase._load_from_state_dict)rO   rP   r9   c                 C   s2   |d  kr|ksn 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   rO   rP   r   r   r   rN      s    
z3UniformQuantizationObserverBase._validate_qmin_qmax)min_valmax_valr9   c           
      C   s4  t ||s2t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s| jtjkr"t	| |}|t|| d  }t	|| j}| jtjkr| jr|	|	 || d }	n|	|	 d}	n| jtjkrl|| t||  }t|| jk|t|}d| | }	nJ|| 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   )r+   rc         )!r   r;   rC   rc   typerO   rP   min
zeros_likemaxonessizerV   zerosint64r>   rE   rG   floatr7   r+   rJ   rM   new_fullrH   where	ones_likeroundtointclamplenshape)
r   r_   r`   rO   rP   Zmin_val_negZmax_val_posrc   scale
zero_pointr   r   r   _calculate_qparams  sP    
(

z2UniformQuantizationObserverBase._calculate_qparamsc                 C   s   t dd S )Nz2Cannot reset min/max values in the given observer.)NotImplementedErrorr   r   r   r   reset_min_max_valsI  s    z2UniformQuantizationObserverBase.reset_min_max_vals)r!   r"   r#   r2   _versionr;   Tensor__annotations__rJ   rD   rU   rV   r7   r   rW   jitexportru   rN   r   r{   r}   r4   r   r   r,   r   r5   u   s,   
(
	+Gr5   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fd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 )MinMaxObservera	  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: 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`.

    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`   FNr8   c              	      s   t t| j|||||||d tj|}| dtjtdfi | | dtjtdfi | | j	tj
kr| jr| jtjkrtdd S )Nr+   r>   rA   rO   rP   r=   r7   r_   infr`   -infz`Cannot reduce range for symmetric                                        quantization for quint8)r*   r   r   r;   r<   r=   rB   rC   ro   r>   rE   rA   r+   rJ   r|   rQ   r,   r   r   r     s*    
	

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detachrt   r_   r+   r;   aminmaxrh   rj   r`   copy_)r   x_origr/   min_val_curmax_val_curr_   r`   r   r   r   r0     s    zMinMaxObserver.forwardc                 C   s   |  | j| jS )z'Calculates the quantization parameters.r{   r_   r`   r   r   r   r   r1     s    z MinMaxObserver.calculate_qparamsc                 C   s   d | j| jS Nzmin_val={}, max_val={}formatr_   r`   r   r   r   r   
extra_repr  s    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   r;   rC   ro   r`   r   r   r   r   r}     s    z!MinMaxObserver.reset_min_max_vals)r!   r"   r#   r2   r;   r   r   rJ   rD   rU   rV   r7   r   r0   r   r   r1   r   r}   r4   r   r   r,   r   r   T  s(   
=

	'

r   c                	       sL   e Zd ZdZdejejdddeejj	fdd fddZ
dd	 Z  ZS )
MovingAverageMinMaxObservera  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: 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 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?FNr8   c           	   	      s.   || _ tt| jf ||||||d| d S )N)r+   r>   rA   rO   rP   r7   )averaging_constantr*   r   r   )	r   r   r+   r>   rA   rO   rP   r7   r   r,   r   r   r     s    z$MovingAverageMinMaxObserver.__init__c                 C   s   |  dkr|S | }|| jj}| j}| j}|tdkrZ|tdkrZt|\}}n2t|\}}|| j	||   }|| j	||   }| j
| | j
| |S )Nr   r   r   )r   r   rt   r_   r+   r`   ro   r;   r   r   r   )r   r   r/   r_   r`   r   r   r   r   r   r0     s    z#MovingAverageMinMaxObserver.forward)r!   r"   r#   r2   r;   rJ   rD   rU   rV   r7   r   r0   r4   r   r   r,   r   r     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fdd fdd	Zd
d Zdd Zejjdd Zdd Zeeef eeeejf eee ee ee d fddZeeef eeeejf eee ee ee dddZejjdd Z  ZS )PerChannelMinMaxObservera  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: 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.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   FNr8   c	           	   	      s   t t| j|||||||d tj|}|| _| dtjg fi | | dtjg fi | | j	tj
kr| jr| jtjkrtdd S )Nr   r_   r`   z9Cannot reduce range for symmetric quantization for quint8)r*   r   r   r;   r<   r=   ch_axisrB   rC   r>   rG   rA   r+   rJ   r|   )	r   r   r+   r>   rA   rO   rP   r=   r7   r,   r   r   r   J  s,    
	

z!PerChannelMinMaxObserver.__init__c                 C   s
   |  |S r   )_forward)r   r   r   r   r   r0   k  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s|  dkrtj|dd\}}n*tj|dd\}}	t||}t|	|}| j|j | j|j | j| | j| |S )Nr   c                 S   s   g | ]}|qS r   r   .0ir   r   r   
<listcomp>v      z5PerChannelMinMaxObserver._forward.<locals>.<listcomp>rS   	start_dimdim)r   r   r_   r`   rl   rangerw   r   permutert   r+   r;   flattenr   rh   rj   resize_rx   r   
r   r   r/   r_   r`   Zx_dimZnew_axis_listyr   r   r   r   r   r   n  s,    


z!PerChannelMinMaxObserver._forwardc                 C   s   |  | j| jS r   r   r   r   r   r   r1     s    z*PerChannelMinMaxObserver.calculate_qparamsc                 C   s   d | j| jS r   r   r   r   r   r   r     s    z#PerChannelMinMaxObserver.extra_repr)rX   rY   rZ   r[   r\   r]   r^   c              	      s"  | dd }|d u s|dk r.ddg}	d}
d}nddg}	d}
d}|	D ]}|| }||v r|| }||
krv| j|j n(||kr| j|j ntd| tj	
 r||
kr| j| q||kr| j| qtd| qB|rB|| qBtj	
 stt| |||d||| d S )	NrR   r6   Zmin_valsZmax_valsr_   r`   z4Observer load_from_state_dict got unexpected name {}F)rT   r_   r   rx   r`   r?   r@   r   r;   r   is_scriptingr   appendr*   r   rW   )r   rX   rY   rZ   r[   r\   r]   r^   rR   local_stateZexpected_min_nameZexpected_max_namenamekeyvalr,   r   r   rW     sF    


z.PerChannelMinMaxObserver._load_from_state_dictc              	   C   s   |  ||||||| d S r   )rW   )r   rX   rY   rZ   r[   r\   r]   r^   r   r   r   _load_from_state_dict_script  s    z5PerChannelMinMaxObserver._load_from_state_dict_scriptc                 C   s   t g | _t g | _dS )r   N)r;   rC   r_   r`   r   r   r   r   r}     s    z+PerChannelMinMaxObserver.reset_min_max_vals)r!   r"   r#   r2   r;   r   r   rJ   rF   rU   rV   r7   r   r0   r   r   r   r1   r   r
   strr   boolr   rW   r   r}   r4   r   r   r,   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	fdd fddZ
d	d
 Z  ZS )%MovingAveragePerChannelMinMaxObservera.  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   FNr8   c	           
   
      s0   t t| jf |||||||d|	 || _d S )N)r   r+   r>   rA   rO   rP   r7   )r*   r   r   r   )
r   r   r   r+   r>   rA   rO   rP   r7   r   r,   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s|  dkrtj|dd\}}n6tj|dd\}}	|| j||   }|| j|	|   }| j|j | j|j | j| | j| |S )Nr   c                 S   s   g | ]}|qS r   r   r   r   r   r   r   "  r   zAMovingAveragePerChannelMinMaxObserver.forward.<locals>.<listcomp>rS   r   r   )r   r   rt   r_   r+   r`   rl   r   rw   r   r   r;   r   r   r   r   rx   r   r   r   r   r   r0     s,    


z-MovingAveragePerChannelMinMaxObserver.forward)r!   r"   r#   r2   r;   rJ   rF   rU   rV   r7   r   r0   r4   r   r   r,   r   r     s   r   c                       s:  e Zd ZU dZejed< ejed< ejed< ddejejdddde	ej
jf	eeejdd	 fd
dZejejejejdddZeedddZeejejf dddZejejeeejejeef dddZejejeeeeejdddZejejdddZejjdd Z fd d!Z fd"d#Z  ZS )$HistogramObservera  
    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
        upsample_rate: Factor by which the histograms are upsampled, this is
                       used to interpolate histograms with varying ranges across observations
        dtype: Quantized data type
        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   re   FN)binsupsample_rater+   r9   c
           
   	      s   t t| j|||||||	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 S )Nr   r   r_   r   r`   r   rd   )r*   r   r   r;   r<   r=   r   rB   rm   rC   ro   iinfor+   bits	dst_nbinsr   )
r   r   r   r+   r>   rA   rO   rP   r=   r7   r,   r   r   r   Q  s     
	zHistogramObserver.__init__)delta_begin	delta_enddensityr9   c                 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
        r6   r   )r   r   r   r   normr   r   r   	_get_normo  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 }
|
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.
        rS           rb   floor)rounding_moder   g      ?rd   )r`   itemr_   r   r   r;   aranger   rc   rv   divrm   r   rk   rC   sum)r   r   r   	bin_widthZdst_bin_widthZsrc_binZsrc_bin_beginZsrc_bin_endZdst_bin_of_beginZdst_bin_of_begin_centerZdst_bin_of_endZdst_bin_of_end_centerr   r   r   r   r   r   r   _compute_quantization_error  s>    

z-HistogramObserver._compute_quantization_errorr8   c                 C   sf  | 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 r|| |
| k r|d }q||kr|| || kr|d }q|}|}|| || kr|}|
}n|}|}||kr||krqp| 
||}||	kr0q>|}	|}|}qp| 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 mistmatchr   gh㈵>r   ra   rS   r   )r   rl   r   r`   r_   r;   r   r   cumsumro   r   )r   r   totalZcSumZstepsizealphabetaZ	start_binZend_binZnorm_minZ
next_alphaZ	next_betalr&   r   r   r   new_minnew_maxr   r   r   _non_linear_param_search  sJ    




z*HistogramObserver._non_linear_param_search)combined_mincombined_maxr   r9   c                 C   s   | j | j | j|  }tt|| | j|   }|| j|  ||  }|| }|}tt| j| |  }||||fS r   )r`   r_   r   ru   r;   ceilr   rs   )r   r   r   r   Zhist_bin_widthdownsample_ratee	start_idxr   r   r   _adjust_min_max  s    	z!HistogramObserver._adjust_min_max)	orig_histnew_histr   r   r   Nbinsr9   c                 C   s   | |}tj|| |jd}||||| | < tj|dtjd|d d | }	tj||jd}
|	dd |
d|< |	|
 | }||tj }|S )Nrb   r   r:   rS   rf   )repeat_interleaver;   rm   rc   r   doublert   ro   )r   r   r   r   r   r   r   Zupsampled_histogramZhistogram_with_output_rangeZintegral_histogramZshifted_integral_histogramZinterpolated_histogramr   r   r   _combine_histograms
  s(    

z%HistogramObserver._combine_histograms)r   r9   c                 C   s  |  dkr|S | }| j}| j}| | k}|tdkoJ|tdk}|sT|rt|\}}| j|j	 | j
| | j|j	 | j
| |  dkr|  dksJ dtj|| jt|t|| jd nt|\}}t||}	t||}
| |	|
| j\}	}
}}|	  dkr4|
  dks<J dtj|| jt|	t|
d}|	|krx|
|krx|| j7 }n| || j| j||| j}| j |j	 | j
| | j |	j	 | j
|	 | j |
j	 | j
|
 |S )Nr   r   r   rS   z(histogram min/max values must be scalar.)rh   rj   out)rh   rj   )r   r   r_   r`   r   ro   r;   r   r   rx   r   histcr   ru   r   rh   rj   r   r   r   detach_)r   r   r/   r_   r`   Zsame_valuesis_uninitializedr   r   r   r   r   r   Zcombined_histogramr   r   r   r0   .  sr    


	

	zHistogramObserver.forwardc                 C   s   | j tdko| jtdk}|rVtd tjdg| j jjdtjdg| j jjdfS | j	t
| jksnJ d|  \}}| ||S )Nr   r   z~must run observer before calling calculate_qparams.                                    Returning default scale and zero point ra   rb   r   ziThe number of bins in histogram should be equal to the number of bins supplied while making this observer)r_   ro   r`   r?   r@   r;   rC   rc   rg   r   rw   r   r   r{   )r   r   r   r   r   r   r   r1   i  s    ,z#HistogramObserver.calculate_qparamsc                    s4   t t| ||| | j||d < | j||d < d S )Nr_   r`   )r*   r   _save_to_state_dictr_   r`   )r   destinationrY   	keep_varsr,   r   r   r   }  s
    
z%HistogramObserver._save_to_state_dictc              	      s   | dd }|d u s|dk r|d |d  }	}
|	|v r^||	 jtdgkr^ttd||	< |
|v r||
 jtdgkrttd||
< ddg}|D ]8}|| }||v r|| }t| || q|r|| qtt	| 
||||||| d S )NrR   r6   r_   r`   r   r   r   )rT   rx   r;   SizerC   ro   setattrr   r*   r   rW   )r   rX   rY   rZ   r[   r\   r]   r^   rR   Zmin_val_nameZmax_val_namer   r   r   r   r,   r   r   rW     s4    

z'HistogramObserver._load_from_state_dict)r!   r"   r#   r2   r;   r   r   rJ   rD   rU   rV   r7   ru   r+   r   r   r   r   r   r   r   r0   r   r   r1   r   rW   r4   r   r   r,   r   r   4  sP   



2@
$;
r   c                       s\   e Zd ZU dZejed< ejed< ejejddf fdd	Z	dd	 Z
ejjd
d Z  ZS )FixedQParamsObserveraU  
    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`
    ry   rz   r      c                    sb   t t| j|d || _|| _| dtj|gtjd | dtj|gtj	d || _
|| _d S )Nr:   ry   rz   )r*   r   r   rO   rP   rB   r;   rC   ro   ru   r+   r>   )r   ry   rz   r+   r>   rO   rP   r,   r   r   r     s    zFixedQParamsObserver.__init__c                 C   s   |S r   r   )r   Xr   r   r   r0     s    zFixedQParamsObserver.forwardc                 C   s   | j | jfS r   )ry   rz   r   r   r   r   r1     s    z&FixedQParamsObserver.calculate_qparams)r!   r"   r#   r2   r;   r   r   rJ   rD   r   r0   r   r   r1   r4   r   r   r,   r   r     s   


r   c                       sH   e Zd ZdZejddfdd fddZdd Zejj	d	d
 Z
  ZS )PlaceholderObservera  
    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: 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).
     Nr8   c                    s,   t t| j|d || _|| _|r(|| _d S Nr:   )r*   r   r   r+   	custom_opcompute_dtype)r   r+   custom_op_namer   r,   r   r   r     s
    zPlaceholderObserver.__init__c                 C   s   |S r   r   r.   r   r   r   r0     s    zPlaceholderObserver.forwardc                 C   s   t dd S )Nz>calculate_qparams should not be called for PlaceholderObserver	Exceptionr   r   r   r   r1     s    z%PlaceholderObserver.calculate_qparams)r!   r"   r#   r2   r;   rV   r   r0   r   r   r1   r4   r   r   r,   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 )RecordingObservera   
    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 t| jf d|i| g | _d S )Nr+   )r*   r   r   r   )r   r+   r   r,   r   r   r     s    zRecordingObserver.__init__c                 C   s   | j |  |S r   )r   r   cloner.   r   r   r   r0     s    zRecordingObserver.forwardc                 C   s   t dd S )Nz<calculate_qparams should not be called for RecordingObserverr   r   r   r   r   r1     s    z#RecordingObserver.calculate_qparamsc                 C   s   | j S r   )r   r   r   r   r   get_tensor_value  s    z"RecordingObserver.get_tensor_value)r!   r"   r#   r2   r   r	   r;   r   r   rJ   r   r0   r   r   r1   r   r4   r   r   r,   r   r     s   
r   c                       sF   e Zd ZdZejdfdd fddZdd Zejj	d	d
 Z
  ZS )NoopObservera  
    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   Nr8   c                    s"   t t| j|d || _|| _d S r   )r*   r   r   r+   r   )r   r+   r   r,   r   r   r   "  s    zNoopObserver.__init__c                 C   s   |S r   r   r.   r   r   r   r0   '  s    zNoopObserver.forwardc                 C   s   t dd S )Nz7calculate_qparams should not be called for NoopObserverr   r   r   r   r   r1   *  s    zNoopObserver.calculate_qparams)r!   r"   r#   r2   r;   float16r   r0   r   r   r1   r4   r   r   r,   r   r     s
   r   c                       s8   e Zd ZdZ fddZdd Zejjdd Z	  Z
S )ReuseInputObservera   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                    s   t  tj d S r   )r*   r   r;   rJ   r   r,   r   r   r   ;  s    zReuseInputObserver.__init__c                 C   s   |S r   r   r.   r   r   r   r0   >  s    zReuseInputObserver.forwardc                 C   s   t dd S )Nz=calculate_qparams should not be called for ReuseInputObserverr   r   r   r   r   r1   A  s    z$ReuseInputObserver.calculate_qparams)r!   r"   r#   r2   r   r0   r;   r   r   r1   r4   r   r   r,   r   r   .  s
   r   c                 C   s<   t | tjjr8| jjddd }tdd|}||v S dS )zCReturns true if given mod is an instance of Observer script module..rS   z\.___torch_mangle_\d+r   F)	
isinstancer;   r   RecursiveScriptModule_cqualified_namesplitresub)modZobs_type_namesuffixr   r   r   r   _is_observer_script_moduleE  s
    r  c                 C   s*   t | tjjjp(t | tjjjp(t| dS )Nzquantization.observer)r   r;   aoquantizationr)   FakeQuantizer  moduler   r   r   _is_activation_post_processO  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)r   r;   r   r   r  r  r   r   r   #_is_per_channel_script_obs_instanceW  s    r  c                 C   sr   t  }t| tjjr<|   D ]\}}d|v r |||< q n&|   D ]\}}d|v rH|||< qH|  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   r   r;   r   r   rX   items	_metadata)r  Zodkvr   r   r   get_observer_state_dicta  s    
r  c              
   C   s   g }g }|   D ]N\}}|d }t|rt|rH|||i d||g  q|||i d||g  q|D ]"}d|v sxd|v rdtd|qd|D ]"}d|v sd|v rtd|qd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 {} in state_dictz-Unexpected keys for observer {} in state_dictN)named_modulesr
  r  r   rW   r   r   )r  Zobs_dictr\   r]   r   r	  rY   r  r   r   r   load_observer_state_dictt  s$    r     )rO   rP   )r+   r>   ig      0?)r+   r>   rO   rP   r7   )r+   r   )r+   r>   r   g      ?re   r   )ry   rz   r+   rO   rP   g      p?)Hr2   r   r?   abcr   r   collectionsr   	functoolsr   typingr   r   r   r	   r
   r;   torch.nnr<   Ztorch.ao.quantization.utilsr   r   objectr   r   r'   r   r(   r   Moduler)   r5   Z_ObserverBaser   r   r   r   r   r   r   r   r   r   r  r
  r  r  r  r   default_observerdefault_placeholder_observerZdefault_debug_observerrI   rE   default_weight_observerZ$weight_observer_range_neg_127_to_127Zdefault_histogram_observerrG   #default_per_channel_weight_observerZ0per_channel_weight_observer_range_neg_127_to_127ro   rJ   Zdefault_dynamic_quant_observerrH   Zdefault_float_qparams_observerrK   Z#default_float_qparams_observer_4bit,default_fixed_qparams_range_neg1to1_observer)default_fixed_qparams_range_0to1_observerZ(default_symmetric_fixed_qparams_observerZ%default_affine_fixed_qparams_observerZdefault_reuse_input_observerr   r   r   r   <module>   s    ] U 9O  |&$



	