o
    ãÊi!  ã                   @   sV   d dl mZ d dlZd dlmZ d dlmZ dgZG dd„ deƒZdd„ Z	d	d
„ Z
dS )é    )ÚOptionalN)Ú	Parameter)ÚFakeQuantizeBaseÚLearnableFakeQuantizec                       sö   e Zd ZdZ			d#‡ fdd„	Zejjd$d	d
„ƒZejjd$dd„ƒZ	ejjd%de
ddfdd„ƒZejjdd„ ƒZejjd%de
d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„ ƒZdejdejddfdd „Zd!d"„ Z‡  ZS )&r   a”  Generalized extension of the FakeQuantize module.

    This is an extension of the FakeQuantize module, which
    supports more generalized lower-bit quantization and supports learning of the scale
    and zero point parameters through backpropagation.

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

    * :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:`learning_enabled` defines the flag for enabling backpropagation for scale and zero point.
    r   éÿ   Fc                    s   t ƒ  ¡  ||k sJ dƒ‚|| _|| _||d< ||d< || _d | _d | _|di |¤Ž| _t 	| jj
¡j|ks:J dƒ‚|t 	| jj
¡jksHJ dƒ‚| jj
| _
| jj| _t| jdƒr\| jjnd| _|  dtjd	gtjd
¡ |  dt t tj¡jg¡¡ d| _d S )Nz/quant_min must be strictly less than quant_max.Ú	quant_minÚ	quant_maxzquant_min out of boundzquant_max out of boundÚch_axiséÿÿÿÿÚlearning_enabledr   )ÚdtypeÚepsF© )ÚsuperÚ__init__r   r   Úuse_grad_scalingÚscaleÚ
zero_pointÚactivation_post_processÚtorchÚiinfor   ÚminÚmaxÚqschemeÚhasattrr	   Úregister_bufferÚtensorÚuint8ÚfinfoÚfloat32r   Ú_initialized)ÚselfÚobserverr   r   r   Úobserver_kwargs©Ú	__class__r   úe/home/ubuntu/.local/lib/python3.10/site-packages/torchao/quantization/pt2e/learnable_fake_quantize.pyr       s2   
ÿÿ



ÿý
zLearnableFakeQuantize.__init__ÚreturnNc                 C   s>   d| j d< |  ¡  | jdurd| j_| jdurd| j_dS dS )zŽEnable quantization parameter learning.

        Enables learning of quantization parameters and
        disables observer estimates.
        é   r   NT)r   Údisable_observerr   Úrequires_gradr   ©r!   r   r   r&   Úenable_range_learningH   s   


ÿz+LearnableFakeQuantize.enable_range_learningc                 C   s6   d| j d< | jdurd| j_| jdurd| j_dS dS )zgDisable quantization parameter learning.

        Disables learning of quantization parameters
        r   NF)r   r   r*   r   r+   r   r   r&   Údisable_range_learningV   s   


ÿz,LearnableFakeQuantize.disable_range_learningTÚenabledc                 C   s&   |rdnd| j d< |r|  ¡  dS dS )zwEnable observer.

        Enables observer estimates and disables learning of
        quantization parameters.
        r(   r   N)Úobserver_enabledr-   ©r!   r.   r   r   r&   Úenable_observerb   s   ÿz%LearnableFakeQuantize.enable_observerc                 C   ó   |   d¡ d S ©NF)r1   r+   r   r   r&   r)   m   ó   z&LearnableFakeQuantize.disable_observerc                 C   s   |rdnd| j d< d S )Nr(   r   )Úfake_quant_enabledr0   r   r   r&   Úenable_fake_quantq   s   z'LearnableFakeQuantize.enable_fake_quantc                 C   r2   r3   )r6   r+   r   r   r&   Údisable_fake_quantu   r4   z(LearnableFakeQuantize.disable_fake_quantc                 C   s,   t d| j ¡ › ƒ t d| j ¡ › ƒ d S )NzLearnableFakeQuantize Scale: z"LearnableFakeQuantize Zero Point: )Úprintr   Údetachr   r+   r   r   r&   Úobserve_quant_paramsy   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   Úitemr9   r   ÚroundÚclampr   r   Úlong©r!   r   r   r   r   r&   Úcalculate_qparams~   s   
üz'LearnableFakeQuantize.calculate_qparamsc                 C   s\   d| j › d| j› d| j› d| j› d| j› d| j› d| j› d| j› d	| j› d
| j	› d| j
› S )Nzfake_quant_enabled=z, observer_enabled=z, learning_enabled=z, quant_min=z, quant_max=z, dtype=z
, qscheme=z
, ch_axis=z, use_grad_scaling=z, scale=z, zero_point=)r5   r/   r   r   r   r   r   r	   r   r   r   r+   r   r   r&   Ú
extra_reprŠ   s(   ÿÿÿþþþýýýÿz LearnableFakeQuantize.extra_reprr   r   c                 C   s|   | j s,t|ƒ| _t| ¡ ƒ| _| jd dkrd| j_d| j_nd| j_d| j_d| _ dS | jj |¡ | jj | ¡ ¡ dS )z’
        Initialize scale and zero_point parameters if they are not initialized yet.
        Update them if they are already initialized.
        r   r(   TFN)	r    r   r   Úfloatr   r   r*   r;   Úcopy_rA   r   r   r&   Ú_initialize_or_update_qparams“   s   


z3LearnableFakeQuantize._initialize_or_update_qparamsc              	   C   sà   | j d dks
| js|  | ¡ ¡ | j ¡ \}}|  ||¡ | jd dkrn| jtj	tj
fv r4| jj ¡  | jrCd| ¡ | j d  }nd}| jtj	tjfv r`t || j| j| j| j| j|¡}|S t || j| j| j| j|¡}|S )Nr   r(   g      ð?g      à?)r/   r    r   r9   rB   rF   r5   r   r   Úper_channel_symmetricÚper_tensor_symmetricr   r;   Úzero_r   Únumelr   Úper_channel_affineÚ+_fake_quantize_learnable_per_channel_affiner   r	   r   Ú*_fake_quantize_learnable_per_tensor_affine)r!   ÚXÚ_scaleÚ_zero_pointÚgrad_factorr   r   r&   Úforwardª   sB   þù÷ú	zLearnableFakeQuantize.forward)r   r   F)r'   N)T)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   ÚjitÚexportr,   r-   Úboolr1   r)   r6   r7   r:   rB   rC   ÚTensorrF   rR   Ú__classcell__r   r   r$   r&   r      s@    û(





ÿÿ
þc                 C   ó   t | tƒr|  ¡  dS dS )zâEnable quantization parameter learning.

    Enable fake quantization for this module, if applicable. Example usage::

      # model is any PyTorch model
      model.apply(torchao.quantization.pt2e.enable_range_learning)

    N)Ú
isinstancer   r,   ©Úmodr   r   r&   r,   Ò   ó   
	ÿr,   c                 C   r\   )zãEnable quantization parameter learning.

    Enable fake quantization for this module, if applicable. Example usage::

      # model is any PyTorch model
      model.apply(torchao.quantization.pt2e.disable_range_learning)

    N)r]   r   r-   r^   r   r   r&   r-   ß   r`   r-   )Útypingr   r   Útorch.nn.parameterr   Ú'torchao.quantization.pt2e.fake_quantizer   Ú__all__r   r,   r-   r   r   r   r&   Ú<module>   s    E