
    קgX              	          d Z ddlZddlmZmZ ddlmZmZ ddlZddl	m
Z
mZmZmZmZmZmZ ddlmZ g dZdd	d
efdZdd	d
efdZdd	d
efdZdd	d
efdZ G d dee          Z G d de          Z G d de          Z G d de          Ze                    eddej        ej        d          Z 	 e                    eddej!        ej"        d          Z#	 e                    edddej        d          Z$	 e                    e          Z%e                    e          Z&e%Z'e&Z(e                    eddej!        ej)        dd           Z*	 e                    eej+        ej        dddd!          Z,	 e                    eej+        dej-        d"          Z.e                    eddej        ej        d          Z/	 e                    eddej        #          Z0	 e                    eddej!        ej"        $          Z1	 e                    eddej!        ej)        $          Z2	 e                    ed%dej!        ej"        d&'          Z3	 e                    ed%dej!        ej)        d&'          Z4	 d( Z5d) Z6d* Z7d+ Z8d, Z9dS )-z6Implements modules  used to perform fake quantization.    N)ABCabstractmethod)AnyTuple)
_with_args)default_fixed_qparams_range_0to1_observer,default_fixed_qparams_range_neg1to1_observerFixedQParamsObserverHistogramObserverMovingAverageMinMaxObserver%MovingAveragePerChannelMinMaxObserver)Module)FakeQuantizeBaseFakeQuantizeFixedQParamsFakeQuantizeFusedMovingAvgObsFakeQuantizedisable_fake_quantdisable_observerenable_fake_quantenable_observerdefault_fake_quantdefault_weight_fake_quantdefault_dynamic_fake_quant.default_fixed_qparams_range_neg1to1_fake_quant+default_fixed_qparams_range_0to1_fake_quant*default_symmetric_fixed_qparams_fake_quant'default_affine_fixed_qparams_fake_quant%default_per_channel_weight_fake_quantdefault_embedding_fake_quant!default_embedding_fake_quant_4bitdefault_histogram_fake_quantdefault_fused_act_fake_quantdefault_fused_wt_fake_quant'default_fused_per_channel_wt_fake_quant(fused_wt_fake_quant_range_neg_127_to_1274fused_per_channel_wt_fake_quant_range_neg_127_to_127qschemeztorch.qschemereturnc                 L    | t           j        t           j        t           j        fv S N)torchper_channel_symmetricper_channel_affine per_channel_affine_float_qparamsr'   s    _/var/www/html/ai-engine/env/lib/python3.11/site-packages/torch/ao/quantization/fake_quantize.py_is_per_channelr1   2   s&    # .      c                 6    | t           j        t           j        fv S r*   )r+   per_tensor_symmetricper_tensor_affiner/   s    r0   _is_per_tensorr6   :   s    u153JKKKr2   c                 6    | t           j        t           j        fv S r*   )r+   r4   r,   r/   s    r0   _is_symmetric_quantr8   >   s    u153NOOOr2   c                      | t           j        fv S r*   )r+   r.   r/   s    r0   _is_float_qparamsr:   B   s    .  r2   c                   P    e Zd ZU dZej        ed<   ej        ed<   d fdZed             Z	ed             Z
ej        j        dd
eddfd            Zej        j        d             Zej        j        dd
eddfd            Zej        j        d             Zed             Z xZS )r   a  Base fake quantize module.

    Base fake quantize module
    Any fake quantize implementation should derive from this class.

    Concrete fake quantize module should follow the same API. In forward, they will update
    the statistics of the observed Tensor and fake quantize the input. They should also provide a
    `calculate_qparams` function that computes the quantization parameters given
    the collected statistics.

    fake_quant_enabledobserver_enabledr(   Nc                    t                                                       |                     dt          j        dgt          j                             |                     dt          j        dgt          j                             dS )z,Set fake_quant_enabled and observer_enabled.r<      dtyper=   N)super__init__register_bufferr+   tensoruint8)self	__class__s    r0   rC   zFakeQuantizeBase.__init__X   su     	15<5;3W3W3WXXX/qc1U1U1UVVVVVr2   c                     d S r*    )rG   xs     r0   forwardzFakeQuantizeBase.forwarda       r2   c                     d S r*   rJ   )rG   kwargss     r0   calculate_qparamsz"FakeQuantizeBase.calculate_qparamse   rM   r2   Tenabledc                 "    |rdnd| j         d<   d S Nr?   r   )r<   rG   rQ   s     r0   r   z"FakeQuantizeBase.enable_fake_quanti   s    *1%8QQq"""r2   c                 0    |                      d           d S NF)r   rG   s    r0   r   z#FakeQuantizeBase.disable_fake_quantm   s    u%%%%%r2   c                 "    |rdnd| j         d<   d S rS   )r=   rT   s     r0   r   z FakeQuantizeBase.enable_observerq   s    (/#611Qa   r2   c                 0    |                      d           d S rV   )r   rW   s    r0   r   z!FakeQuantizeBase.disable_observeru   s    U#####r2   c                 .    t          | fi |}d|_        |S )Nz#torch.ao.quantization.fake_quantize)r   
__module__)clsrO   fake_quant_constructors      r0   	with_argszFakeQuantizeBase.with_argsy   s*    !+C!:!:6!:!: -R)%%r2   )r(   N)T)__name__r[   __qualname____doc__r+   Tensor__annotations__rC   r   rL   rP   jitexportboolr   r   r   r   classmethodr^   __classcell__rH   s   @r0   r   r   H   sr        
 
 $$$l"""W W W W W W   ^   ^ Y9 9 9 9 9 9 9 Y& & & Y7 7t 7t 7 7 7 7 Y$ $ $ & & [& & & & &r2   r   c                        e Zd ZU dZej        ed<   ej        ed<   edddf fd	Zej	        j
        d             Zd Zej	        j
        d	             Z fd
Z fdZ xZS )r   aK  Simulate the quantize and dequantize operations in training time.

    The output of this module is given by::

        x_out = (
          clamp(round(x/scale + zero_point), quant_min, quant_max) - zero_point
        ) * scale

    * :attr:`is_dynamic` indicates whether the fake quantie is a placeholder for dynamic quantization
      operators (choose_qparams -> q -> dq) or static quantization operators (q -> dq)

    * :attr:`scale` defines the scale factor used for quantization.

    * :attr:`zero_point` specifies the quantized value to which 0 in floating point maps to

    * :attr:`fake_quant_enabled` controls the application of fake quantization on tensors, note that
      statistics can still be updated.

    * :attr:`observer_enabled` controls statistics collection on tensors

    * :attr:`dtype` specifies the quantized dtype that is being emulated with fake-quantization,
        allowable values are torch.qint8 and torch.quint8.

    Args:

        observer (module): Module for observing statistics on input tensors and calculating scale
          and zero-point.
        observer_kwargs (optional): Arguments for the observer module

    Attributes:
        activation_post_process (Module): User provided module that collects statistics on the input tensor and
          provides a method to calculate scale and zero-point.

    scale
zero_pointNFc                    t                                                       ||||k    s
J d            |                    dt          j                  }t          |d          r4t          t          |di           di                               d|          }t          j        |          j        |k    s
J d            |t          j        |          j	        k    s
J d            |
                    ||d           ||d<    |di || _        | j        j        | _        | j        j        | _        | j        j        | _        t          | j        j                  rt          j        }nt          j        }|                     d	t          j        d
gt          j                             |                     dt          j        dg|                     | j        j        | _        | j        j        | _        t          | j        d          r| j        j        nd| _        t/          | j                  s3t1          | j                  sJ dt3          | j                  z               t/          | j                  | _        d S )Nz1quant_min must be less than or equal to quant_maxrA   pkeywordszquant_min out of boundzquant_max out of bound)	quant_min	quant_max
is_dynamicrk   g      ?r@   rl   r   ch_axiszYOnly per channel and per tensor quantization are supported in fake quantize got qscheme: rJ   )rB   rC   getr+   quint8hasattrgetattriinfominmaxupdateactivation_post_processrp   rq   rr   r:   r'   floatintrD   rE   rA   rs   r1   r6   stris_per_channel)	rG   observerrp   rq   rr   observer_kwargsrA   zero_point_dtyperH   s	           r0   rC   zFakeQuantize.__init__   s    	 Y%:Y&&&B '&&#''>>Ex%%   #r : :JKKOOU  ;u%%)Y6668P666E 2 2 66668P666""#S#STTT(2%'/x'B'B/'B'B$ 5?5?6AT9ABB 	)${$yWelC5&L&L&LMMM\5<CS+T+T+TUUU17
3; t3Y??D(00 	
 t|,, 	
t|0L0L 	
 	
$, 	
 	
 	

 .dl;;r2   c                 4    | j                                         S r*   r}   rP   rW   s    r0   rP   zFakeQuantize.calculate_qparams       +==???r2   c                 F   | j         d         dk    r|                     |                                           |                                 \  }}|                    | j        j                  |                    | j        j                  }}| j        j        |j        k    r>| j        	                    |j                   | j        	                    |j                   | j        
                    |           | j        
                    |           | j        d         dk    rz| j        r=t          j        || j        | j        | j        | j        j        | j        j                  }n6t          j        || j        | j        | j        j        | j        j                  }|S )Nr   r?   )r=   r}   detachrP   tork   devicerl   shaperesize_copy_r<   r   r+    fake_quantize_per_channel_affiners   rp   rq   fake_quantize_per_tensor_affine)rG   X_scale_zero_points       r0   rL   zFakeQuantize.forward   sz    #q((((444"&"8"8":":FK"())DJ,=">">&A AKF z6<//
""6<000''(9:::JV$$$O!!+..."1%**" :JOL0:0:  9JO0:0:  r2   c                     d| j          d| j         d| j        j         d| j        j         d| j         d| j         d| j         d| j         d	| j	         S )
Nfake_quant_enabled=, observer_enabled=, quant_min=, quant_max=, dtype=
, qscheme=z
, ch_axis=, scale=, zero_point=)
r<   r=   r}   rp   rq   rA   r'   rs   rk   rl   rW   s    r0   
extra_reprzFakeQuantize.extra_repr  s    @$"9 @ @dNc @ @5?@ @MQMiMs@ @Z@ @+/<@ @CG<@ @ Z@ @ /3o@ @	
r2   c                     t                                          |||           | j        ||dz   <   | j        ||dz   <   d S Nrk   rl   )rB   _save_to_state_dictrk   rl   )rG   destinationprefix	keep_varsrH   s       r0   r   z FakeQuantize._save_to_state_dict
  sI     	##KCCC(,
FW$%-1_F\)***r2   c           	         ddg}|D ]}	||	z   }
|
|v r||
         }|	dk    r | j                             |j                   n'|	dk    sJ | j                            |j                   t          j                                        rC|	dk    r| j                             |           |	dk    sJ | j                            |           |r|                    |
           t                      
                    |||||||           d S r   )rk   r   r   rl   r+   rd   is_scriptingr   appendrB   _load_from_state_dict)rG   
state_dictr   local_metadatastrictmissing_keysunexpected_keys
error_msgslocal_statenamekeyvalrH   s               r0   r   z"FakeQuantize._load_from_state_dict  sD    - 	) 	)D4-Cj   o
 7??J&&sy1111<////O++CI666 9))++ 3w
((----#|3333--c222 )##C(((%%	
 	
 	
 	
 	
r2   )r_   r[   r`   ra   r+   rb   rc   r   rC   rd   re   rP   rL   r   r   r   rh   ri   s   @r0   r   r      s         ! !F < -1< 1< 1< 1< 1< 1<f Y@ @ @  B Y
 
 
= = = = =,
 ,
 ,
 ,
 ,
 ,
 ,
 ,
 ,
r2   r   c                   v     e Zd ZdZ fdZej        j        d             Zej        j        d             Z	 xZ
S )r   zSimulate quantize and dequantize in training time.

    Simulate quantize and dequantize with fixed quantization
    parameters in training time. Only per tensor quantization
    is supported.
    c                    t                                          |           t          | j                  t          k    s#J | j        j         dt          j                     || _        | j        j        | _        | j        j	        | _	        t          | j                  sJ dt          | j                  z               d S )Nr   z's observer must be a zWOnly per tensor quantization is supported FixedQParamsFakeQuantize module, got qscheme:)rB   rC   typer}   r
   rH   r_   _observer_ctrrk   rl   r6   r'   r   )rG   r   rH   s     r0   rC   z!FixedQParamsFakeQuantize.__init__I  s    (+++-..2FFFFn%\\=Q=Z\\ GFF%17
6Adl++ 	
 	
?$, 	
 	
 	
 	
 	
r2   c                     | j         | j        fS r*   )rk   rl   rW   s    r0   rP   z*FixedQParamsFakeQuantize.calculate_qparamsW  s    z4?**r2   c                     d| j          d| j         d| j         d| j         d| j         d| j        j         d| j        j         d| j         S )	z:Define a string representation of the object's attributes.r   r   r   r   r   r   r   r   )	r<   r=   rk   rl   rA   r}   rp   rq   r'   rW   s    r0   r   z#FixedQParamsFakeQuantize.extra_repr[  s    Z$"9 Z ZdNc Z ZZZ Z.2oZ ZZZ Z-1-I-SZ Z 5?Z Z LP<Z Z	
r2   )r_   r[   r`   ra   rC   r+   rd   re   rP   r   rh   ri   s   @r0   r   r   @  s         
 
 
 
 
 Y+ + + Y
 
 
 
 
 
 
r2   r   c                        e Zd ZdZeddfdededededd	f
 fd
Zej	        j
        deej        ej        f         fd            Zej	        j
        defd            Zdej        dej        fdZ xZS )r   a  Define a fused module to observe the tensor.

    Fused module that is used to observe the input tensor (compute min/max), compute
    scale/zero_point and fake_quantize the tensor.
    This module uses calculation similar MovingAverageMinMaxObserver for the inputs,
    to compute the min/max values in order to compute the scale/zero_point.
    The qscheme input in the observer is used to differentiate between symmetric/affine
    quantization scheme.

    The output of this module is given by
    x_out = (clamp(round(x/scale + zero_point), quant_min, quant_max)-zero_point)*scale

    Similar to :class:`~torch.ao.quantization.FakeQuantize`, and accepts the same attributes as the
    base class.

    r      r   rp   rq   r   r(   Nc                     t                      j        |||fi | t          | j        t          t
          f          s
J d            |                     dt          j        dgt          j	                             |                     dt          j        dgt          j	                             t          | j        j                  | _        d S )NzLFused observer+fake_quant module only works with MovingAverageMinMaxObserverr<   r?   r@   r=   )rB   rC   
isinstancer}   r   r   rD   r+   rE   longr8   r'   is_symmetric_quant)rG   r   rp   rq   r   rH   s        r0   rC   z&FusedMovingAvgObsFakeQuantize.__init__x  s     	9iKK?KKK((*OP
 
 	Z 	Z Z	Z 	Z 	Z 	15<5:3V3V3VWWW/qc1T1T1TUUU"5(0#
 #
r2   c                 4    | j                                         S r*   r   rW   s    r0   rP   z/FusedMovingAvgObsFakeQuantize.calculate_qparams  r   r2   c                     d| j          d| j         d| j         d| j         d| j         d| j        j         d| j        j         d| j         d	| j        j	         S )
Nr   r   r   r   r   r   r   r   z, reduce_range=)
r<   r=   rk   rl   rA   r}   rp   rq   r'   reduce_rangerW   s    r0   r   z(FusedMovingAvgObsFakeQuantize.extra_repr  s    `$"9 ` `dNc ` `Z` `.2o` `GKz` `5?` `MQMiMs` ` |` ` 594P4]` `	
r2   r   c                     t          j        || j        | j        | j        j        | j        j        | j        | j        | j        j	        | j        j
        | j        j        | j        | j        | j                  S r*   )r+   fused_moving_avg_obs_fake_quantr=   r<   r}   min_valmax_valrk   rl   averaging_constantrp   rq   rs   r   r   )rG   r   s     r0   rL   z%FusedMovingAvgObsFakeQuantize.forward  sn    4!#(0(0JO(;(2(2L#
 
 	
r2   )r_   r[   r`   ra   r   r   r   rC   r+   rd   re   r   rb   rP   r   r   rL   rh   ri   s   @r0   r   r   f  s        & 4	
 

 
 	

 
 

 
 
 
 
 
$ Y@5u|)C#D @ @ @ @ Y
C 
 
 
 

 
%, 
 
 
 
 
 
 
 
r2   r   r   T)r   rp   rq   rA   r'   r   i   Fr?   )r   rp   rq   rr   rA   r   r   )r   rp   rq   rA   r'   r   rs   )r   r'   rA   rp   rq   rs   r   )r   r'   rs   rA   r   )r   rp   rq   rA   )r   rp   rq   rA   r'   ig      0?)r   rp   rq   rA   r'   epsc                     t          | t          j        j                  rH| j        j                            dd          d         }t          j        dd|          }|dk    p|dk    S dS )zFReturn true if given mod is an instance of FakeQuantize script module..r?   z\.___torch_mangle_\d+ z0torch.ao.quantization.fake_quantize.FakeQuantizezAtorch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantizeF)	r   r+   rd   RecursiveScriptModule_cqualified_namesplitresub)modsuffixr   s      r0   _is_fake_quant_script_moduler   H  ss    #uy677 
&,,S!44Q7v.F;;FF SRS	

 5r2   c                 z    t          | t                    st          |           r|                                  dS dS )zDisable fake quantization for the module.

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

      # model is any PyTorch model
      model.apply(torch.ao.quantization.disable_fake_quant)

    N)r   r   r   r   r   s    r0   r   r   V  sI     #'(( !,H,M,M !     ! !r2   c                 z    t          | t                    st          |           r|                                  dS dS )zEnable fake quantization for the module.

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

      # model is any PyTorch model
      model.apply(torch.ao.quantization.enable_fake_quant)

    N)r   r   r   r   r   s    r0   r   r   c  sI     #'((  ,H,M,M     r2   c                 z    t          | t                    st          |           r|                                  dS dS )zDisable observation for this module.

    Disable observation for this module, if applicable. Example usage::

      # model is any PyTorch model
      model.apply(torch.ao.quantization.disable_observer)

    N)r   r   r   r   r   s    r0   r   r   p  sI     #'(( ,H,M,M  r2   c                 z    t          | t                    st          |           r|                                  dS dS )zEnable observation for this module.

    Enable observation for this module, if applicable. Example usage::

      # model is any PyTorch model
      model.apply(torch.ao.quantization.enable_observer)

    N)r   r   r   r   r   s    r0   r   r   }  sI     #'(( ,H,M,M  r2   ):ra   r   abcr   r   typingr   r   r+   torch.ao.quantization.observerr   r   r	   r
   r   r   r   torch.nnr   __all__rf   r1   r6   r8   r:   r   r   r   r   r^   rv   r5   r   qint8r4   r   r   r   r   r   r   r,   r   r.   r   quint4x2r    r!   r"   r#   r$   r%   r&   r   r   r   r   r   rJ   r2   r0   <module>r      sk   = < 				 # # # # # # # #                                  8_     LO L L L L LP PT P P P P 4    7& 7& 7& 7& 7&sF 7& 7& 7&t{
 {
 {
 {
 {
# {
 {
 {
|#
 #
 #
 #
 #
| #
 #
 #
L@
 @
 @
 @
 @
L @
 @
 @
F "++(
,# ,    )22(
+& 3   
 *33(
, 4    2J1S1S9 2T 2 2 . /G.P.P6 /Q / / +
 3 + +V '(4(>(>2
+' )? ) ) %  ,5522
,  6     
 %1$:$:22
. %; % % !  ,55
,#  6     
  =FF(
,	  G     
 <EE(
+& F    +H*Q*Q2
+' +R + + ' ,I+R+R(
+& ,S , , (
 "++6k+ ,   5
  
! 
! 
!
  
  
 
 
 

 
 
 
 
r2   