U
    KºcQ  ã                   @   s.   d dl Z d dlmZ G dd„ de jjjƒZdS )é    N)Ú	Parameterc                       sÂ   e Zd ZdZd‡ fdd	„	Zejjd
d„ ƒZejjdd„ ƒZ	ejjdd„ ƒZ
ejjd dd„ƒZejjd!dd„ƒZejjd"dd„ƒZejjd#dd„ƒZejjdd„ ƒZejjdd„ ƒZdd„ Z‡  ZS )$Ú_LearnableFakeQuantizea$   This is an extension of the FakeQuantize module in fake_quantize.py, which
    supports more generalized lower-bit quantization and support learning of the scale
    and zero point parameters through backpropagation. For literature references,
    please see the class _LearnableFakeQuantizePerTensorOp.

    In addition to the attributes in the original FakeQuantize module, the _LearnableFakeQuantize
    module also includes the following attributes to support quantization parameter learning.

    * :attr:`channel_len` defines the length of the channel when initializing scale and zero point
      for the per channel case.

    * :attr:`use_grad_scaling` defines the flag for whether the gradients for scale and zero point are
      normalized by the constant, which is proportional to the square root of the number of
      elements in the tensor. The related literature justifying the use of this particular constant
      can be found here: https://openreview.net/pdf?id=rkgO66VKDS.

    * :attr:`fake_quant_enabled` defines the flag for enabling fake quantization on the output.

    * :attr:`static_enabled` defines the flag for using observer's static estimation for
      scale and zero point.

    * :attr:`learning_enabled` defines the flag for enabling backpropagation for scale and zero point.
    r   éÿ   ç      ð?ç        éÿÿÿÿFc           
         sÂ  t t| ƒ ¡  ||k stdƒ‚|| _|| _||d< ||d< || _|dkrntt 	|g¡ƒ| _
tt 	|g¡ƒ| _nFt|tƒr€|dksˆtdƒ‚tt 	|g| ¡ƒ| _
tt 	|g| ¡ƒ| _|f |Ž| _t | jj¡j|ksÜtdƒ‚|t | jj¡jksøtdƒ‚| jj| _| jj| _t| jd	ƒr"| jjnd| _|  d
tj	dgtjd¡ |  dtj	dgtjd¡ |  dtj	dgtjd¡ t 	|| d ¡ ¡ }	tt |	¡ ¡ ƒ| _|  dt 	t tj¡jg¡¡ d S )Nz/quant_min must be strictly less than quant_max.Ú	quant_minÚ	quant_maxr   r   z(Channel size must be a positive integer.zquant_min out of boundzquant_max out of boundÚch_axisÚfake_quant_enabledé   )ÚdtypeÚstatic_enabledÚlearning_enabledÚeps)Úsuperr   Ú__init__ÚAssertionErrorr   r	   Úuse_grad_scalingr   ÚtorchZtensorÚscaleÚ
zero_pointÚ
isinstanceÚintÚactivation_post_processZiinfor   ÚminÚmaxÚqschemeÚhasattrr
   Zregister_bufferZuint8ÚdoubleÚlog2ÚitemZbitwidthZfinfoZfloat32r   )
ÚselfZobserverr   r	   r   r   Zchannel_lenr   Zobserver_kwargsZbitrange©Ú	__class__© úR/tmp/pip-unpacked-wheel-gikjz4vx/torch/ao/quantization/_learnable_fake_quantize.pyr      s@    ÿÿ


ÿÿz_LearnableFakeQuantize.__init__c                 C   s    | j ddjddjdd | S )z‹Enables learning of quantization parameters and
        disables static observer estimates. Forward path returns fake quantized X.
        T©ÚenabledF©Útoggle_qparam_learningÚtoggle_fake_quantÚtoggle_observer_update©r"   r%   r%   r&   Úenable_param_learning@   s    ÿþz,_LearnableFakeQuantize.enable_param_learningc                 C   s    | j ddjddjdd dS )z‹Enables static observer estimates and disbales learning of
        quantization parameters. Forward path returns fake quantized X.
        Fr'   TNr)   r-   r%   r%   r&   Úenable_static_estimateJ   s
    ÿþz-_LearnableFakeQuantize.enable_static_estimatec                 C   s    | j ddjddjdd dS )zšEnables static observer accumulating data from input but doesn't
        update the quantization parameters. Forward path returns the original X.
        Fr'   TNr)   r-   r%   r%   r&   Úenable_static_observationS   s
    ÿþz0_LearnableFakeQuantize.enable_static_observationTc                 C   s   t |ƒ| jd< | S ©Nr   )r   r   ©r"   r(   r%   r%   r&   r,   \   s    z-_LearnableFakeQuantize.toggle_observer_updatec                 C   s   |   |¡ d S )N)r,   r2   r%   r%   r&   Úenable_observera   s    z&_LearnableFakeQuantize.enable_observerc                 C   s"   t |ƒ| jd< || j_|| j_| S r1   )r   r   r   Zrequires_gradr   r2   r%   r%   r&   r*   e   s    z-_LearnableFakeQuantize.toggle_qparam_learningc                 C   s   t |ƒ| jd< | S r1   )r   r   r2   r%   r%   r&   r+   l   s    z(_LearnableFakeQuantize.toggle_fake_quantc                 C   s,   t d | j ¡ ¡ƒ t d | j ¡ ¡ƒ d S )Nz _LearnableFakeQuantize Scale: {}z%_LearnableFakeQuantize Zero Point: {})ÚprintÚformatr   Údetachr   r-   r%   r%   r&   Úobserve_quant_paramsq   s    z+_LearnableFakeQuantize.observe_quant_paramsc                 C   sF   | j jj| j ¡ d | j  ¡ }| j ¡  ¡  | j	| j
¡ ¡ }||fS )N©r   )r   ÚdataÚclamp_r   r!   r6   r   ÚroundÚclampr   r	   Úlong)r"   r   r   r%   r%   r&   Úcalculate_qparamsv   s    
z(_LearnableFakeQuantize.calculate_qparamsc              	   C   s  | j d dkrd|  | ¡ ¡ | j ¡ \}}| | jj¡}| | jj¡}| jj 	|¡ | jj 	|¡ n| jjj
| j ¡ d | jd dkr| jtjtjfkr¨| jj ¡  | jrÆd| ¡ | j d  }nd}| jtjtjfkrþt || j| j| j| j| j|¡}nt || j| j| j| j|¡}|S )Nr   r   r8   r   g      à?)r   r   r6   r>   Útor   Zdevicer   r9   Zcopy_r:   r   r!   r   r   r   Zper_channel_symmetricZper_tensor_symmetricZzero_r   Znumelr	   Zper_channel_affineZ+_fake_quantize_learnable_per_channel_affiner
   r   Z*_fake_quantize_learnable_per_tensor_affine)r"   ÚXZ_scaleZ_zero_pointZgrad_factorr%   r%   r&   Úforward}   sH     ÿ     þ    þz_LearnableFakeQuantize.forward)r   r   r   r   r   F)T)T)T)T)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   ZjitÚexportr.   r/   r0   r,   r3   r*   r+   r7   r>   rA   Ú__classcell__r%   r%   r#   r&   r      s.     ÿ#
	



r   )r   Ztorch.nn.parameterr   ZaoZquantizationZFakeQuantizeBaser   r%   r%   r%   r&   Ú<module>   s   