a
    Þñh(Î  ã                   @   sº  d dl Z d dlmZmZ d dlmZ d dlmZmZm	Z	m
Z
mZ d dlmZ d dlZd dlmZ d dlZdd„ Zeedƒefi ƒZG d	d
„ d
eejƒ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'd(„ Z&ej'd)d*�Z(e Z)ej'ej*ej+d+�Z,ej'd)d*�Z-ej'ej*ej.d+�Z/eZ0ej'ej1ej2d d,�Z3dS )-é    N)ÚABCMetaÚabstractmethod)Úpartial)ÚListÚTupleÚOptionalÚDictÚUnion)ÚOrderedDictc                 K   s(   G dd„ d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.

    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
    c                   @   s(   e Zd Zdd„ Zdd„ Zdd„ ZeZdS )z#_with_args.<locals>._PartialWrapperc                 S   s
   || _ d S ©N©Úp)Úselfr   © r   ú[/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/quantization/observer.pyÚ__init__   s    z,_with_args.<locals>._PartialWrapper.__init__c                 _   s   | j |i |¤ŽS r   r   )r   ÚargsÚkeywordsr   r   r   Ú__call__   s    z,_with_args.<locals>._PartialWrapper.__call__c                 S   s
   | j  ¡ S r   )r   Ú__repr__©r   r   r   r   r   !   s    z,_with_args.<locals>._PartialWrapper.__repr__N)Ú__name__Ú
__module__Ú__qualname__r   r   r   Ú
_with_argsÚ	with_argsr   r   r   r   Ú_PartialWrapper   s   r   )Úobjectr   )Úcls_or_selfÚkwargsr   Úrr   r   r   r      s    r   ÚABCc                       s@   e Zd ZdZ‡ fdd„Zedd„ ƒZedd„ ƒ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   8   s    zObserverBase.__init__c                 C   s   d S r   r   ©r   Úxr   r   r   Úforward<   s    zObserverBase.forwardc                 K   s   d S r   r   ©r   r   r   r   r   Úcalculate_qparams@   s    zObserverBase.calculate_qparams)r   r   r   Ú__doc__r   r   r)   r+   Úclassmethodr   r   Ú__classcell__r   r   r%   r   r"   ,   s   

r"   c                       sp   e Zd ZdZdZejejdddf‡ fdd„	Z‡ fdd„Z	ej
jd	d
„ ƒZej
jdd„ ƒZej
jdd„ ƒZ‡  ZS )Ú_ObserverBaseaò  Internal common base for all qint/quint8 observers.

    This base is for commonly used parameters used internally.
    Users should use `~torch.quantization.observer.ObserverBase` as a base class
    for custom observers.

    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.

    .. 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``
    é   FNc                    s¾   t t| ƒj|d� || _|r&t d¡ || _|  dt 	t 
tj¡jg¡¡ | jtjtjtjtjtjfv spJ dƒ‚| jtjtjfv sŠJ dƒ‚|d uo˜|d u| _| jr®|  ||¡ || _|| _d S )N©r$   zšPlease use quant_min and quant_max to specify the range for observers.                     reduce_range will be deprecated in a future release of PyTorch.ÚepszÄDefault 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 qint8 and quint8 data type)r#   r/   r   ÚqschemeÚwarningsÚwarnÚreduce_rangeÚregister_bufferÚtorchÚtensorÚfinfoÚfloat32r2   Úper_tensor_affineÚper_tensor_symmetricÚper_channel_affineÚper_channel_symmetricÚ per_channel_affine_float_qparamsr$   Úqint8Úquint8Úhas_customized_qrangeÚ_validate_qmin_qmaxÚ	quant_minÚ	quant_max©r   r$   r3   r6   rE   rF   r%   r   r   r   r   s8    ÿûú	þýz_ObserverBase.__init__c           
   	      s^   |  dd ¡}|d u s|dkr>t t tj¡jg¡}	|	||d < tt| ƒ |||||||¡ d S )NÚversioné   r2   )	Úgetr8   r9   r:   r;   r2   r#   r"   Ú_load_from_state_dict)
r   Ú
state_dictÚprefixÚlocal_metadataÚstrictÚmissing_keysÚunexpected_keysÚ
error_msgsrH   r2   r%   r   r   rK   �   s    ÿz#_ObserverBase._load_from_state_dictc                 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   rE   rF   r   r   r   rD   �   s    z!_ObserverBase._validate_qmin_qmaxc                 C   sô   | j r®d\}}| j| j }}|dur6|dur6|| }}|| d }d|  k rVdks`n J dƒ‚| jtjkr†| d |d d  }}nd|d  }}| jrì|d |d  }}n>| jtjkrÔ| jrÊd\}}qìd	\}}n| jräd
\}}nd\}}||fS )z|Calculates actual qmin and qmax based on the quantization range,
        observer datatype and if range is reduced.
        ©r   éÿ   NrI   r   é   zRquantization range should be positive and not exceed the maximum bit range (=256).r0   ©iÀÿÿÿé?   ©i€ÿÿÿé   ©r   rY   )rC   rE   rF   r$   r8   rA   r6   )r   Zinitial_quant_minZinitial_quant_maxZcustom_quant_minZcustom_quant_maxZ
qrange_lenrE   rF   r   r   r   Ú_calculate_qmin_qmax²   s,    
ÿ


z"_ObserverBase._calculate_qmin_qmaxc           
      C   sÄ  |  ¡ dks|  ¡ dkr:t d¡ t dg¡t dg¡fS | ¡ dksR| ¡ dkr¦|tdƒkrŒ|tdƒkrŒt d¡ t dg¡t dg¡fS ||ksÄJ d ||¡ƒ‚nt ||k¡sÄJ d ||¡ƒ‚|  	¡ \}}t 
|t |¡¡}t |t |¡¡}tj| ¡ tjd�}tj| ¡ tjd�}|j�r(d	nd
}	| jtjk�sH| jtjk�rºt | |¡}|t|| ƒd  }t || j¡}| jtjk�rF| j�r¨| | ¡ || d ¡}n| | ¡ d¡}nŒ| jtjk�r|| t|| ƒ }t || jk|t |¡¡}d| | }nB|| t|| ƒ }t || j¡}|t || ¡ }t |||¡}t |j!ƒdk�rnt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,)
        r   ú~must run observer before calling calculate_qparams.                                    Returning default scale and zero point ç      ð?Úinfú-infz‚must run observer before calling calculate_qparams.                                        Returning default scale and zero point ú!min {} should be less than max {}r1   ZcudaÚcpur0   é€   éÿÿÿÿ)r$   Údevice)#Únumelr4   r5   r8   r9   ÚdimÚfloatÚformatÚallr[   ÚminZ
zeros_likeÚmaxZonesÚsizer;   ÚzerosÚint64Zis_cudar3   r=   r?   r2   r$   rB   rC   Znew_fullr@   ÚwhereZ	ones_likeÚroundÚclampÚlenÚshapeÚint)
r   Úmin_valÚmax_valrE   rF   Zmin_val_negZmax_val_posÚscaleÚ
zero_pointrd   r   r   r   Ú_calculate_qparamsÚ   s\    ÿÿÿÿz _ObserverBase._calculate_qparams)r   r   r   r,   Ú_versionr8   rB   r<   r   rK   ÚjitÚexportrD   r[   ry   r.   r   r   r%   r   r/   G   s   (ÿ

'r/   c                       sX   e Zd ZdZejejdddf‡ fdd„	Z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.

    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:: Only works with ``torch.per_tensor_symmetric`` quantization scheme

    .. 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.
    FNc                    sp   t t| ƒj|||||d� |  dt tdƒ¡¡ |  dt tdƒ¡¡ | jtjkrl| j	rl| j
tjkrltdƒ‚d S )N©r$   r3   r6   rE   rF   ru   r^   rv   r_   z`Cannot reduce range for symmetric                                        quantization for quint8)r#   r}   r   r7   r8   r9   rg   r3   r=   r6   r$   rB   ÚNotImplementedErrorrG   r%   r   r   r   n  s    	üÿ
þzMinMaxObserver.__init__c                 C   s\   |  ¡ }| | jj¡}t |¡\}}t || j¡}t || j¡}| j 	|¡ | j 	|¡ |S )z1Records the running minimum and maximum of ``x``.)
ÚdetachÚtoru   r$   r8   Ú_aminmaxrj   rk   rv   Úcopy_)r   Úx_origr(   Úmin_val_curÚmax_val_curru   rv   r   r   r   r)   „  s    zMinMaxObserver.forwardc                 C   s   |   | j| j¡S )ú'Calculates the quantization parameters.)ry   ru   rv   r   r   r   r   r+   �  s    z MinMaxObserver.calculate_qparamsc                 C   s   d  | j| j¡S ©Nzmin_val={}, max_val={})rh   ru   rv   r   r   r   r   Ú
extra_repr”  s    zMinMaxObserver.extra_repr)r   r   r   r,   r8   rB   r<   r   r)   r{   r|   r+   r‰   r.   r   r   r%   r   r}   .  s   ?ÿ
r}   c                       s:   e Zd ZdZdejejdddf‡ 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.

    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.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.
    ç{®Gáz„?FNc                    s$   || _ tt| ƒj|||||d� d S )Nr~   )Úaveraging_constantr#   rŠ   r   )r   rŒ   r$   r3   r6   rE   rF   r%   r   r   r   Ä  s    üz$MovingAverageMinMaxObserver.__init__c                 C   s´   |  ¡ }| | jj¡}| j}| j}|tdƒkrJ|tdƒkrJt |¡\}}n2t |¡\}}|| j||   }|| j||   }| j 	|j
¡ | j 	|j
¡ | j |¡ | j |¡ |S )Nr^   r_   )r€   r�   ru   r$   rv   rg   r8   r‚   rŒ   Úresize_rs   rƒ   )r   r„   r(   ru   rv   r…   r†   r   r   r   r)   Î  s    z#MovingAverageMinMaxObserver.forward)
r   r   r   r,   r8   rB   r<   r   r)   r.   r   r   r%   r   rŠ   ™  s   *þ
rŠ   c                   @   s    e Zd ZdZejjdd„ ƒZdS )ÚMinMaxDynamicQuantObserveraî  Observer module for computing the quantization parameters based on the
    tensor min and max values in dynamic quantization.

    This observer will mimic the quantization steps followed in the operator
    to compute the activation tensor quantization parameters at run-time.

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

    .. warning:: Only works with ``torch.per_tensor_symmetric`` quantization scheme

    .. 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 0.1 and 0.
    c                 C   s  | j tdƒkr4| jtdƒkr4t dg¡t dg¡fS | j| j ksTJ d | j| j ¡ƒ‚| jtjkrz| jrpd\}}q’d\}}n| jrŠd\}}nd	\}}| j j	tjd
�| jj	tjd
� }}t 
|t d¡j	tjd
�¡}t |t d¡j	tjd
�¡}|j	tjd
�| t|| ƒ }|dk�s$t d| ¡�r<t d¡j	tjd
�}d}|||j	tjd
�  }|||j	tjd
�  }t|ƒt||j	tjd
� ƒ }	t|ƒt||j	tjd
� ƒ }
|	|
k �r´|}n|}d}||k �rÌ|}n||k�rÜ|}nt| ¡ ƒ}|j	tjd
�t |g¡fS )r‡   r_   r^   r]   r   r`   rV   rX   rZ   rS   r1   ç        gš™™™™™¹?)rv   rg   ru   r8   r9   rh   r$   rA   r6   r�   rj   rk   ÚdoubleÚisinfÚabsrt   rp   )r   ZqminZqmaxrv   ru   rw   rx   Zzero_point_from_minZzero_point_from_maxZzero_point_from_min_errorZzero_point_from_max_errorZinitial_zero_pointZnudged_zero_pointr   r   r   r+   ô  sB    ÿ


"


z,MinMaxDynamicQuantObserver.calculate_qparamsN)r   r   r   r,   r8   r{   r|   r+   r   r   r   r   rŽ   à  s   rŽ   c                	       s  e Zd ZdZdejejdddf‡ fdd„	Zdd„ Zd	d
„ Z	ej
jdd„ ƒZdd„ Zej
jeeeejf eeejf f eeeejf eee ee ee dœ‡ fdd„ƒZej
jeeeejf eeejf f eeeejf eee ee ee dœ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.

    The quantization parameters are computed the same way as in
    :class:`~torch.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   FNc                    sn   t t| ƒj|||||d� || _|  dt g ¡¡ |  dt g ¡¡ | jtjkrj| j	rj| j
tjkrjtdƒ‚d S )Nr~   Úmin_valsÚmax_valsz9Cannot reduce range for symmetric quantization for quint8)r#   r“   r   Úch_axisr7   r8   r9   r3   r?   r6   r$   rB   r   )r   r–   r$   r3   r6   rE   rF   r%   r   r   r   E  s$    ü
ÿþ
ýÿz!PerChannelMinMaxObserver.__init__c                 C   s
   |   |¡S r   )Ú_forward)r   r„   r   r   r   r)   Y  s    z PerChannelMinMaxObserver.forwardc           
      C   sö   |  ¡ }| j}| j}| ¡ }dd„ tt|ƒƒD ƒ}d|| j< | j|d< | |¡}| | jj	¡}t
j|dd�}| ¡ dks„| ¡ dkr–t
 |d¡\}}n(t
 |d¡\}}	t
 ||¡}t
 |	|¡}| j |j¡ | j |j¡ | j |¡ | j |¡ |S )Nc                 S   s   g | ]}|‘qS r   r   ©Ú.0Úir   r   r   Ú
<listcomp>b  ó    z5PerChannelMinMaxObserver._forward.<locals>.<listcomp>r   rI   ©Z	start_dim)r€   r”   r•   rl   Úrangerr   r–   Úpermuter�   r$   r8   Úflattenre   r‚   rj   rk   r�   rs   rƒ   ©
r   r„   r(   r”   r•   Zx_dimZnew_axis_listÚyZmin_vals_curZmax_vals_curr   r   r   r—   \  s(    


z!PerChannelMinMaxObserver._forwardc                 C   s   |   | j| j¡S r   )ry   r”   r•   r   r   r   r   r+   v  s    z*PerChannelMinMaxObserver.calculate_qparamsc                 C   s   d  | j| j¡S rˆ   )rh   r”   r•   r   r   r   r   r‰   z  s    z#PerChannelMinMaxObserver.extra_repr)rL   rM   rN   rO   rP   rQ   rR   c              	      s¶   ddg}|D ]~}	||	 }
|
|v r|||
 }|	dkr@| j  |j¡ n| j |j¡ tj ¡ rŠ|	dkrn| j  |¡ qŠ| j |¡ q|r| |
¡ qtj ¡ s²t	t
| ƒ |||||||¡ d S )Nr”   r•   )r”   r�   rs   r•   r8   r{   Zis_scriptingrƒ   Úappendr#   r“   rK   )r   rL   rM   rN   rO   rP   rQ   rR   Úlocal_stateÚnameÚkeyÚvalr%   r   r   rK   }  s$    

ÿz.PerChannelMinMaxObserver._load_from_state_dictc              	   C   s   |   |||||||¡ d S r   )rK   )r   rL   rM   rN   rO   rP   rQ   rR   r   r   r   Ú_load_from_state_dict_scriptœ  s    z5PerChannelMinMaxObserver._load_from_state_dict_script)r   r   r   r,   r8   rB   r>   r   r)   r—   r{   r|   r+   r‰   r	   r   ÚstrÚTensorÚboolr   rK   r¨   r.   r   r   r%   r   r“   +  s(   þ
 þþr“   c                       s<   e Zd ZdZddejejdddf‡ 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.

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

    .. note:: If the running minimum equals to the running maximum, the scales
              and zero_points are set to 1.0 and 0.
    r‹   r   FNc                    s&   t t| ƒj||||||d� || _d S )N)r–   r$   r3   r6   rE   rF   )r#   r¬   r   rŒ   )r   rŒ   r–   r$   r3   r6   rE   rF   r%   r   r   r   ¾  s
    
þz.MovingAveragePerChannelMinMaxObserver.__init__c           
      C   s  |  ¡ }| | jj¡}| j}| j}| ¡ }dd„ tt|ƒƒD ƒ}d|| j< | j|d< | 	|¡}t
j|dd�}| ¡ dks„| ¡ dkr–t
 |d¡\}}n4t
 |d¡\}}	|| j||   }|| j|	|   }| j |j¡ | j |j¡ | j |¡ | j |¡ |S )Nc                 S   s   g | ]}|‘qS r   r   r˜   r   r   r   r›   Í  rœ   zAMovingAveragePerChannelMinMaxObserver.forward.<locals>.<listcomp>r   rI   r�   )r€   r�   r”   r$   r•   rl   rž   rr   r–   rŸ   r8   r    re   r‚   rŒ   r�   rs   rƒ   r¡   r   r   r   r)   Æ  s(    


z-MovingAveragePerChannelMinMaxObserver.forward)
r   r   r   r,   r8   rB   r>   r   r)   r.   r   r   r%   r   r¬   £  s   þr¬   c                       s�   e Zd ZdZddejejdf‡ fdd„	Zejj	dd„ ƒZ
ejj	d	d
„ ƒZejj	dd„ ƒZdd„ Zejjdd„ ƒZ‡ fdd„Z‡ fdd„Z‡  ZS )ÚHistogramObserveraX  
    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

    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.quantization.MinMaxObserver`
    i   rb   Fc                    sz   t t| ƒj|||d� || _|  dt | j¡¡ |  dt tdƒ¡¡ |  dt tdƒ¡¡ dt 	| j
¡j | _|| _d S )N)r$   r3   r6   Ú	histogramru   r^   rv   r_   r0   )r#   r­   r   Úbinsr7   r8   rm   r9   rg   Ziinfor$   ÚbitsÚ	dst_nbinsÚupsample_rate)r   r¯   r²   r$   r3   r6   r%   r   r   r   ÷  s    þzHistogramObserver.__init__c                    sx  dd„ ‰ ‡ ‡fdd„}ˆj  ¡ d ˆjks2J dƒ‚ˆjˆj ˆj }tˆj ƒ}tjˆj dd�}d}d	}d
}d}ˆjd }	tdƒ}
||k �rP|| }|| }|}|	}||	k rÄ|| || k rÄ|d }q¢||kræ|| || kræ|d }qÄ|}|	}|| |	| k�r
|}|}n|}|}||k�r(||	k�r(q€|||dƒ}||
k�rB�qP|}
|}|}	q€ˆ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
        c                 S   s@   |dksJ dƒ‚d}|dkr8|| | | |  |   d }|| S )zë
            Compute the norm of the values uniformaly distributed between
            delta_begin and delta_end.

            norm = density * (integral_{begin, end} x^2)
                 = density * (end^3 - begin^3) / 3
            ÚL2z%Only L2 norms are currently supportedr�   é   r   )Údelta_beginÚ	delta_endÚdensityÚ	norm_typeÚnormr   r   r   Ú	_get_norm  s    

ÿýz=HistogramObserver._non_linear_param_search.<locals>._get_normc                    s@  ˆj  ¡ ˆj ¡  ˆj }|||  d  ˆj }|dkr<dS t ˆj¡}||  | }|| }t || dˆjd ¡}|d | }	t || dˆjd ¡}
|
d | }ˆj| }t 	ˆj¡}||	 }|d }|ˆ ||||ƒ7 }||
| d ˆ | d |d ||ƒ 7 }|
| |d  }| d }|| }|ˆ ||||ƒ7 }| 
¡ S )zŽ
            Compute the quantization error if we use start_bin to end_bin as the
            min and max to do the quantization.
            rI   r�   r   g      à?r0   )rv   Úitemru   r¯   r±   r8   Zarangerq   r®   rm   Úsum)Únext_start_binÚnext_end_binr¸   Ú	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   r   Ú_compute_quantization_error  s2    
ÿÿ
zOHistogramObserver._non_linear_param_search.<locals>._compute_quantization_errorr   zbins mistmatch)rf   gñhãˆµøä>r�   r]   rI   r^   r³   )	r®   rl   r¯   rv   ru   r¼   r8   Úcumsumrg   )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  sN    	.





z*HistogramObserver._non_linear_param_searchc                 C   sˆ   | j | j | j|  }t || | j|  ¡ tj¡ ¡ }|| j|  ||  }|| }|}t | j| | ¡ tj¡ ¡ }||||fS r   )	rv   ru   r¯   r8   Úceilr�   rt   r»   rp   )r   Úcombined_minÚcombined_maxr²   Zhist_bin_widthÚdownsample_rateÚeÚ	start_idxr   r   r   Ú_adjust_min_maxƒ  s    	$ z!HistogramObserver._adjust_min_maxc                 C   s–   |  |¡}tj|| |jd�}||||| | …< tj|dtjd�|d d |… }	tj||jd�}
|	dd… |
d|…< |	|
 | }|| tj¡ }|S )N)rd   r   r1   rI   rc   )Zrepeat_interleaver8   rm   rd   rÂ   r�   r�   rg   )r   Z	orig_histZnew_histr²   rÍ   rÏ   ZNbinsZupsampled_histogramZhistogram_with_output_rangeZintegral_histogramZshifted_integral_histogramZinterpolated_histogramr   r   r   Ú_combine_histograms•  s    
ÿÿz%HistogramObserver._combine_histogramsc                 C   s~  |  ¡ }| j}| j}| ¡ | ¡ k}|tdƒko:|tdƒk}|sD|r t |¡\}}| j |j¡ | j 	|¡ | j |j¡ | j 	|¡ tj
|| j||| jd� nÚt |¡\}}t ||¡}	t ||¡}
|  |	|
| j¡\}	}
}}tj
|| j|	|
d�}|	|k�r|
|k�r|| j7 }n|  || j| j||| j¡}| j |j¡ | j 	|¡ | j |	j¡ | j 	|	¡ | j |
j¡ | j 	|
¡ |S )Nr^   r_   )rj   rk   Úout)rj   rk   )r€   ru   rv   r»   rg   r8   r‚   r�   rs   rƒ   Zhistcr¯   r®   rj   rk   rÐ   r²   rÑ   )r   r„   r(   ru   rv   Zsame_valuesÚis_uninitializedrÇ   rÈ   rË   rÌ   rÍ   rÏ   Zcombined_histogramr   r   r   r)   ¬  sF    ÿ
úzHistogramObserver.forwardc                 C   sr   | j tdƒko| jtdƒk}|rBt d¡ t dg¡t dg¡fS | jt| j	ƒksZJ dƒ‚|  
¡ \}}|  ||¡S )Nr^   r_   r\   r]   r   ziThe number of bins in histogram should be equal to the number of bins supplied while making this observer)ru   rg   rv   r4   r5   r8   r9   r¯   rr   r®   rÉ   ry   )r   rÓ   rÇ   rÈ   r   r   r   r+   ×  s    ÿÿÿz#HistogramObserver.calculate_qparamsc                    s4   t t| ƒ |||¡ | j||d < | j||d < d S )Nru   rv   )r#   r­   Ú_save_to_state_dictru   rv   )r   ZdestinationrM   Z	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rŽt tdƒ¡||
< ddg}|D ]8}|| }||v rÄ|| }t| ||ƒ qš|rš| |¡ qštt	| ƒ 
|||||||¡ d S )NrH   r´   ru   rv   r   r^   r_   )rJ   rs   r8   ÚSizer9   rg   Úsetattrr£   r#   r­   rK   )r   rL   rM   rN   rO   rP   rQ   rR   rH   Zmin_val_nameZmax_val_namer¤   r¥   r¦   r§   r%   r   r   rK   ï  s(    ÿz'HistogramObserver._load_from_state_dict)r   r   r   r,   r8   rB   r<   r   r{   ÚignorerÉ   rÐ   rÑ   r)   r|   r+   rÔ   rK   r.   r   r   r%   r   r­   Þ  s   ÿ
~

+
r­   c                       s@   e Zd ZdZejdf‡ 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).
    Ú c                    s"   t t| ƒj|d� || _|| _d S ©Nr1   )r#   rØ   r   r$   Ú	custom_op©r   r$   Zcustom_op_namer%   r   r   r     s    zPlaceholderObserver.__init__c                 C   s   |S r   r   r'   r   r   r   r)     s    zPlaceholderObserver.forwardc                 C   s   t dƒ‚d S )Nz>calculate_qparams should not be called for PlaceholderObserver©Ú	Exceptionr   r   r   r   r+     s    z%PlaceholderObserver.calculate_qparams©r   r   r   r,   r8   Úfloat16r   r)   r{   r|   r+   r.   r   r   r%   r   rØ   	  s
   rØ   c                       sZ   e Zd ZdZdeeej  iZ‡ 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 i |¤Ž g | _d S 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   r)   3  s    zRecordingObserver.forwardc                 C   s   t dƒ‚d S )Nz<calculate_qparams should not be called for RecordingObserverrÝ   r   r   r   r   r+   7  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   r,   r   r   r8   rª   Ú__annotations__r   r)   r{   r|   r+   rä   r.   r   r   r%   r   rá   $  s   
rá   c                       s@   e Zd ZdZejdf‡ 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Ù   c                    s"   t t| ƒj|d� || _|| _d S rÚ   )r#   ræ   r   r$   rÛ   rÜ   r%   r   r   r   M  s    zNoopObserver.__init__c                 C   s   |S r   r   r'   r   r   r   r)   R  s    zNoopObserver.forwardc                 C   s   t dƒ‚d S )Nz7calculate_qparams should not be called for NoopObserverrÝ   r   r   r   r   r+   U  s    zNoopObserver.calculate_qparamsrß   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 )zI Returns true if given mod is an instance of Observer script module.
    Ú.rI   z\.___torch_mangle_\d+rÙ   F)	Ú
isinstancer8   r{   ÚRecursiveScriptModuleZ_cZqualified_nameÚsplitÚreÚsub)ÚmodZobs_type_nameÚsuffixr¥   r   r   r   Ú_is_observer_script_moduleY  s
    rï   c                 C   s&   t | tjjƒp$t | tjjƒp$t| dƒS )Nztorch.quantization.observer)rè   r8   Zquantizationr"   ZFakeQuantizerï   ©Úmoduler   r   r   Ú_is_activation_post_processc  s
    ÿþrò   c                 C   s&   t | tjjƒr"t| dƒp t| dƒS dS )Nz4torch.quantization.observer.PerChannelMinMaxObserverzAtorch.quantization.observer.MovingAveragePerChannelMinMaxObserverF)rè   r8   r{   ré   rï   rð   r   r   r   Ú#_is_per_channel_script_obs_instanceh  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è   r8   r{   ré   rL   ÚitemsÚ	_metadata)rí   ZodÚkÚvr   r   r   Úget_observer_state_dictn  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 s d|v rŒtd |¡ƒ‚qŒd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.quantization.get_observer_state_dict
    rç   TFrô   rõ   z*Missing keys for observer {} in state_dictz-Unexpected keys for observer {} in state_dictN)Znamed_modulesrò   ró   r¨   rK   rÞ   rh   )rí   Zobs_dictrP   rQ   r¥   rñ   rM   rø   r   r   r   Úload_observer_state_dict€  s    rû   T)r6   )r$   r3   )r$   r3   r–   )4r4   Úabcr   r   Ú	functoolsr   Útypingr   r   r   r   r	   Úcollectionsr
   r8   Ztorch.nnÚnnrë   r   r©   r   r!   ÚModuler"   r/   r}   rŠ   rŽ   r“   r¬   r­   rØ   rá   ræ   rï   rò   ró   rú   rû   r   Zdefault_observerZdefault_debug_observerrA   r=   Zdefault_weight_observerZdefault_histogram_observerr?   Z#default_per_channel_weight_observerZdefault_dynamic_quant_observerrB   r@   Zdefault_float_qparams_observerr   r   r   r   Ú<module>   sL    hkGKx;  -
þ