a
    ds                     @   sj  d Z ddlZddlZddlmZ ddlmZmZ ddlm	Z	m
Z
mZmZmZmZ ddlZddlmZ ddlmZ ddlmZ eeeef eeeeef f e	f Zd	e_e	Zee
ee
e
f ee
ee
e
f f e	f Zd	e_G d
d dZejjejjejjejjejj ejj!ejj"ejj#ejj$ejj%ejj&ejj'ejj(ejj)ejj*hZ+ejj,j-ejj,j.ejj,j/ejj,j0ejj,j1ejj,j2ejj,j3ejj,j4ejj,j5ejj,j6ejj,j7ejj,j8ejj,j9ejj,j:ejj,j;ejj,j<ejj,j=ejj,j>ejj,j?ej@ejAej?ejBejCejDejEejFejGhZHejIddddddddddddddddddddd d!d"d#hZJd$d% ZKd&d' ZLd(d) ZMd*d+ ZNe	eOe	d,d-d.ZPd/d0 ZQd1d2 ZRd3d4 ZSd5d6 ZTd7d8 ZUd9d: ZVd;d< ZWd=d> ZXd?d@ ZYdAdB ZZdCdD Z[e\dEdFdGZ]dHdI Z^dJdK Z_ej`ej`e\dLdMdNZaebebe\ejce\eebebf dOdPdQZddRdS ZedTdU ZfejjgejjgeeO dVdWdXZhe
eeOe	f eeOe	f dYdZd[Zie
d\d]d^d_Zje
eeOe	f d\d`dadbZkebebddcdddeZlejmfej`ej`ebebejcej`e\ejneej`ej`f df	dgdhZoe
ebd]didjZpejjgee	dkf eeOee	dkf f dldmdnZqdsejjree
 ee
 ee
 ee
 ee
 ejsjjtjrdodpdqZug drZvdS )tz?
Utils shared by different modes of quantization (eager/graph)
    N)OrderedDict)getfullargspec	signature)AnyCallableDictOptionalTupleUnion)	QuantType)Node)is_parametrizedztorch.ao.quantization.utilsc                   @   s   e Zd ZdZdS )MatchAllNodezo A node pattern that matches all nodes, used in defining
    fusion patterns in FX Graph Mode Quantization
    N)__name__
__module____qualname____doc__ r   r   d/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torch/ao/quantization/utils.pyr   "   s   r   reluZrelu_
contiguousdetachZdetach_hardsigmoidZhardsigmoid_Zpermuterepeatrepeat_interleaveZreshapeZresize_shapesigmoidZsigmoid_sizesqueezeZsqueeze_tanhZtanh_	transpose	unsqueezeZ
unsqueeze_viewc                 C   sR   | j dko| jtv }| j dko&| jtv }| j dkoFt|t| j tv }|||fS )Ncall_functionZcall_methodZcall_module)optarget	func_listmethod_listtypestrmodule_type_list)nodemodulesZis_call_functionZis_call_methodZis_call_moduler   r   r   
check_nodet   s     r-   c                 C   s   |   }|| |S N)copyupdate)Zdefault_dictZadditional_dictdr   r   r   get_combined_dict{   s    
r2   c                 C   s   | t jkp| t jkS r.   )torchper_tensor_affineper_tensor_symmetricqschemer   r   r   is_per_tensor   s    
r8   c                 C   s   | t jt jt jfv S r.   )r3   per_channel_affine per_channel_affine_float_qparamsper_channel_symmetricr6   r   r   r   is_per_channel   s    r<   )objfqnreturnc                 C   s   t t|d| S )zO
    Given an obj and a fqn such as "foo.bar.baz", returns gm.foo.bar.baz.
    .)	functoolsreducegetattrsplit)r=   r>   r   r   r   getattr_from_fqn   s    rE   c              
   C   sH   t jt jt jt jt jt jt jt jt jt ji}| |v s@J d|  ||  S )NzUnsupported dtype: )	r3   quint8uint8qint8Zint8qint32int32quint4x2Zquint2x4)ZqdtypeZDTYPE_MAPPINGr   r   r   to_underlying_dtype   s    rL   c                 C   s   t | dr| jnd }| j}||d}|s,|S t|r<tj}n2t|r`|tjkrTtj}| j	|d< nt
d| ||d< |  \}}||d< ||d< |S )Nr7   )r7   dtypeZaxiszUnrecognized qscheme: scale
zero_point)hasattrr7   rM   r8   r3   r4   r<   r;   r9   Zch_axisRuntimeErrorZcalculate_qparams)Zobserver_or_fake_quantr7   rM   ZqparamsrN   rO   r   r   r   get_qparam_dict   s"    

rR   c                 C   s@   t |}||i }t| |v s4J dt| ||t|  S )a   Get the observed/quantized custom module class that we need
    to swap `custom_module` to
    Input:
        custom_module: input, can be an instance of either a float or observed custom module
        custom_module_class_mapping: the float to observed or observed to quantized custom module class mapping
        qconfig: qconfig configured for the custom module

    Output:
        corresponding observed/quantized custom module class for input custom module instance
    zFdid not find corresponding observed module class for {} in mapping: {})get_quant_typegetr(   format)Zcustom_moduleZcustom_module_class_mappingqconfigZ
quant_typeZclass_mappingr   r   r   get_swapped_custom_module_class   s    rW   c                 C   s   | d usJ |   }|jS r.   )
activationrM   )rV   rX   r   r   r   activation_dtype   s    rY   c                 C   s   | d usJ |   }|jS r.   )weightrM   )rV   rZ   r   r   r   weight_dtype   s    r[   c                 C   s&   t | tjtjtjtjfv o$t|  S )z Given a qconfig, decide if the activation needs to be
    quantized or not, this includes quantizing to quint8, qint8 and qint32 and float16
    )rY   r3   rF   rH   rI   float16#activation_is_dynamically_quantizedrV   r   r   r   "activation_is_statically_quantized   s    r_   c                 C   s   t | \}}}|S )z Given a qconfig, decide if the activation needs to be
    dynamically quantized or not, this includes dynamically quantizing to
    quint8, qint8 and float16
    )get_qconfig_dtypes)rV   rY   _activation_is_dynamicr   r   r   r]      s    r]   c                 C   s   t | tjtjfv S )z Given a qconfig, decide if the activation needs to be
    quantized to int8 or not, this includes quantizing to quint8, qint8
    )rY   r3   rF   rH   r^   r   r   r   activation_is_int8_quantized   s    rc   c                 C   s   t | tjkS )zY Given a qconfig, decide if the activation needs to be
    quantized to int32 or not
    )rY   r3   rI   r^   r   r   r   activation_is_int32_quantized   s    rd   c                 C   s   t | tjtjtjtjfv S )zL Given a qconfig, decide if the weight needs to be
    quantized or not
    )r[   r3   rF   rH   r\   rK   r^   r   r   r   weight_is_quantized   s    re   c                 C   s   t | tjtjfv S )zW Given a qconfig, decide if the weight needs to be statically
    quantized or not
    )r[   r3   rF   rH   r^   r   r   r   weight_is_statically_quantized   s    rf   )r?   c                 C   s&   t | \}}}|tju o$|tju o$|S )zU Given a qconfig, returns True if this op is using int8 dynamic
    quantization
    )r`   r3   rF   rH   )rV   rY   r[   rb   r   r   r    op_is_int8_dynamically_quantized   s    
rg   c                 C   s>   | dusJ |   }|  }t|dr,|jnd}|j|j|fS )zh returns the qconfig tuple for qconfig:
    (activation_dtype, weight_dtype, activation_is_dynamic)
    N
is_dynamicF)rX   rZ   rP   rh   rM   )rV   rX   rZ   Zact_is_dynamicr   r   r   r`   	  s
    r`   c                 C   s   | d usJ |   }|  }tjtjtjtjg}|j|v rft|drP|j	rPt
jS |j|v r`t
jS t
jS |jtjkrt|dr|j	rt
jS |jtjkrt
jS td|j|jd S )Nrh   zKUnrecognized dtype combination in get_quant_type: activation({}),weight({}))rX   rZ   r3   rF   rH   rK   rI   rM   rP   rh   r   ZDYNAMICZSTATICZWEIGHT_ONLYr\   	ExceptionrU   )rV   rX   rZ   Zstatic_dtypesr   r   r   rS     s$    

rS   )min_valmax_valr?   c                 C   s   |   dks|  dkr&td dS |  dks>| dkr~| tdkrd|tdkrdtd dS | |ksJ d| |nt| |ksJ d| |dS )z Checks if the given minimum and maximum values are valid, meaning that
    they exist and the min value is less than the max value.
    r   zMmust run observer before calling calculate_qparams. Returning default values.Finfz-infz!min {} should be less than max {}T)ZnumelwarningswarnZdimfloatrU   r3   all)rj   rk   r   r   r   check_min_max_valid)  s(    
rq   )	quant_min	quant_maxhas_customized_qrangerM   reduce_ranger?   c           
      C   s&  |r|t jkrd\}}nd\}}| | }}|durD|durD|| }}|| d }	|t jkrzd|	  k rndksn J dn(|t jkrd|	  k rdksn J d	|r| d
 |d
  } }nd|t jkr|rd\} }nd\} }nB|t jkr |rd\} }nd\} }n|t jkrd\} }nd\} }| |fS )ztCalculates actual qmin and qmax based on the quantization range,
    observer datatype and if range is reduced.
    )r   )r      N   r      zRquantization range should be positive and not exceed the maximum bit range (=256).l        zYquantization range should be positive and not exceed the maximum bit range (=4294967296).   )i?   )i   )r   r|   )i   rv   )r      )r3   rI   rH   rF   )
rr   rs   rt   rM   ru   Zinitial_quant_minZinitial_quant_maxZcustom_quant_minZcustom_quant_maxZ
qrange_lenr   r   r   calculate_qmin_qmaxH  sL    












r~   c                 C   s8   |  dd}t|dkr$d|d fS |d |d fS dS )z,
    Turn 'foo.bar' into ['foo', 'bar']
    r@   rx    r   N)rsplitlen)r%   rr   r   r   _parent_name}  s    r   c                 C   s:   t | jdkrdS t| r2t | jdko0d| jv S dS dS )z
    Checks if module._modules is empty or
    if module is a parametrization, checks that module._modules only has
    the 'parametrizations' module
    r   Trx   ZparametrizationsFN)r   Z_modulesr   )moduler   r   r   )has_no_children_ignoring_parametrizations  s
    r   )root	submoduler?   c                 C   s&   |   D ]\}}||u r|  S qdS )aS   Get the path (fully qualified name) of a submodule

    Example::

    >> class M(torch.nn.Module):
           def __init__(self):
               self.linear = torch.nn.Linear(5, 5)
           def forward(self, x):
               return self.linear(x)

    >> m = M()
    >> l = m.linear
    >> _get_path_of_module(m, l)
    "linear"
    N)Znamed_modules)r   r   npr   r   r   _get_path_of_module  s    
r   )flocr?   c                    s    fdd|  D S )z Get local keyword arguments

    Example::

    >> def f(self, a, b=9):
           pass
    >> loc = {"a": 6, "c": 7}
    >> _get_signature_locals(f, loc)
    {"a": 6}
    c                    s$   i | ]\}}|t  jv r||qS r   )r   
parameters).0kvr   r   r   
<dictcomp>      z)_get_signature_locals.<locals>.<dictcomp>)items)r   r   r   r   r   _get_signature_locals  s    r   zOrderedDict[str, Any])r   r?   c                 C   sf   i }t | j D ]J\}}|j|jur2|j||< q|j|ju rHd||< q|j|ju ri ||< qt|S )z Get all default keyword arguments from function signature

    Example::

    >> def f(self, a, b=9):
           pass
    >> _get_default_kwargs(f)
    {"b": 9}
    r   )	r   r   r   defaultemptykindVAR_POSITIONALVAR_KEYWORDr   )r   kwargsnameparamr   r   r   _get_default_kwargs  s    


r   )funcr   r?   c                 C   s@   t | }t| |}| }| D ]\}}||v r"|||< q"|S )a)   Given a function and local function arguments, normalize the keyword
    arguments by filling in default arguments from function signature

    Example::

    >> def f(self, key1=3, key2=3):
           pass
    >> loc = {"key2": 6}
    >> _normalize_kwargs(f, loc)
    {"key1": 3, "key2": 6}
    )r   r   r/   r   )r   r   Zdefault_kwargsZlocal_kwargsnormalized_kwargsattrvalr   r   r   _normalize_kwargs  s    

r   )rr   rs   r?   c                 C   s2   | d  kr|ksn J d| |k s.J ddS )ae  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   )rr   rs   r   r   r   validate_qmin_qmax  s    
r   )	rj   rk   rr   rs   rM   epsrt   r7   r?   c                 C   s  t | |s2tjdg| jjdtjdg| jjdfS t| t| }t|t|}	|j}
tj|	 tj
|
d}tj|	 tj|
d}|tjks|tjkrt| |	}	|	t|| d  }t||}|tjks|tjkr|r||	 || d }n||	 d}n|tjkrZ||  t||  }t||k|t|}d|  | }nH|	| t||  }t||}|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}|tjkrtjt|g|j|
d}||fS )ad  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,)
    g      ?)devicer   )rM   r   rz      )rq   r3   Ztensorr   r(   minZ
zeros_likemaxZonesr   float32zerosint64r5   r;   ro   rG   rF   Znew_fullr:   whereZ	ones_likeroundtointclampr   r   rM   )rj   rk   rr   rs   rM   r   rt   r7   Zmin_val_negZmax_val_posr   rN   rO   r   r   r   determine_qparams  sN    
(r   c                 C   s   t t| jS )z Get number of positional args for a function

    Example::

    >> def f(self, key1=3, key2=3):
           pass
    >> _get_num_pos_args(f)
    3
    )r   r   argsr   r   r   r   _get_num_pos_argsB  s    
r   .)modelexample_inputsr?   c                    sT   | i   fdd}t jjj|t jj_z| |  W t jj_nt jj_0  S )a   Given a model and its example inputs, return a dictionary from
    fully qualified name of submodules to example_inputs for that submodule,
    e.g. {"linear1": (tensor1,), "linear2": (tensor2,), "sub": (tensor3,),
          "sub.linear1": (tensor4,), ...}

    Used to make quantizing submodules easier now that FX Graph Mode Quantization requries
    example inputs.

    Also works for keyword arguments with default values, we would flatten keyword
    arguments as positional arguments and fill in the missing keyword args with default
    values, e.g. if we have a forward function:
    def forward(self, x, key1=3, key2=3):
        ...

    and we call it with self.submodule(x, key2=6)
    we'll get example_inputs: (x, 3, 6)

    user can also override `key1` with positional arguments as well:
    for self.submodule(x, 5, key2=6)
    we'll get: (x, 5, 6)

    variable positional arguments and variable positional keyword arguments in forward
    function are not supported currently, so please make sure no submodules is using
    them.
    c           	         s   t | }t| j|}t| jd }|t| }|rP|rP|jdd |d8 }q2||  t	|}t
| }|d ur| |< | g|R i |S )Nrx   F)last)listr/   r   Zforwardr   r   popitemextendvaluestupler   )	selfr   r   Zsubmodule_example_inputsr   num_argsZ
num_to_popZsubmodule_example_inputs_tupler>   Zfqn_to_example_inputsZorig_module_callr   r   r   _patched_module_calln  s    

z7get_fqn_to_example_inputs.<locals>._patched_module_call)r3   nnModule__call__)r   r   r   r   r   r   get_fqn_to_example_inputsN  s    


r   )
float_lstmlinear_output_obs_ctrsigmoid_obs_ctrtanh_obs_ctrcell_state_obs_ctrhidden_state_obs_ctrr?   c              	   C   s  t tjjjddd}tjjj| j| j	| j
| j| j| j| j}|jD ]}|jg}	| jrf|	|j |	D ]}
|
j}|dur||}||j_||j_|dur||}||j_||j_||j_|dur|||j_|dur|||j_| }t|drt|dr|j|jf|_|j |_!|durj|||j"_| }t|drZt|drZ|j|jf|_#|j |_$qjqFddl%m&} ||tjj'tjj(gd	 |S )
aJ  
    Return an observed `torch.ao.nn.quantizable.LSTM` created from a `torch.nn.LSTM`
    with specific observers or fake quantizes assigned to the inner ops or submodules.

    In both eager and FX graph mode quantization, `torch.ao.nn.quantizable.LSTM` is
    used as an observed custom module, which is responsible for inserting its own
    observers. By default, all inner ops inherit the parent custom module's QConfig.
    Users who wish to override this behavior may extend `torch.ao.nn.quantizable.LSTM`
    and use this helper function to customize the observer insertion logic.

    Args:
        `float_lstm`: The float LSTM module
        `linear_output_obs_ctr`: observer or fake quantize for linear outputs Wx + b,
            where W is the weight matrix, b is the bias, and x is either the inputs
            or the hidden state from the previous layer (if any)
        `sigmoid_obs_ctr`: observer or fake quantize for sigmoid activations
        `tanh_obs_ctr`: observer or fake quantize for tanh activations
        `cell_state_obs_ctr`: observer or fake quantize for the cell state
        `hidden_state_obs_ctr`: observer or fake quantize for the hidden state and
            the output

    Return:
        A `torch.ao.nn.quantizable.LSTM` with the specified observers or fake quantizes
        attached to the inner submodules.
    )obs_ctrr?   c                 S   s:   t |  tjjjrtjjj}n
tjjj}tjjj| |dS )zP
        Make a QConfig with fixed qparams observers or fake quantizes.
        )rX   rZ   )
isinstancer3   aoquantizationZFakeQuantizeBaseZdefault_weight_fake_quantZdefault_weight_observerQConfig)r   rZ   r   r   r   make_qconfig  s    
z@_get_lstm_with_individually_observed_parts.<locals>.make_qconfigNrN   rO   r   )_add_observer_)Znon_leaf_module_list))r   r3   r   r   r   r   quantizableLSTMZ
input_sizeZhidden_sizeZ
num_layersZbiasZbatch_firstdropoutbidirectionalZlayersZlayer_fwappendZlayer_bwcellZigatesrV   ZhgatesZ
input_gateZforget_gateZoutput_gateZ	cell_gateZfgate_cx_igate_cgaterP   rN   rO   Zinitial_cell_state_qparamsrM   Zcell_state_dtypeZogate_cyZinitial_hidden_state_qparamsZhidden_state_dtypeZtorch.ao.quantization.quantizer   SigmoidTanh)r   r   r   r   r   r   r   Zobserved_lstmZlayerZinner_layersZinner_layerr   rV   Zobsr   r   r   r   *_get_lstm_with_individually_observed_parts  sP    "


r   )NodePatternPatternr   r-   r2   r8   r<   rE   rR   rW   rY   r[   r_   r]   rc   rd   re   rf   rg   r`   rS   rq   r~   r   r   rL   r   r   )NNNNN)wr   rA   rm   collectionsr   inspectr   r   typingr   r   r   r   r	   r
   r3   Z torch.ao.quantization.quant_typer   Ztorch.fxr   Ztorch.nn.utils.parametrizer   r   r   ZQuantizerClsr   r   r   ZReLUZReLU6ZAdaptiveAvgPool1dZAdaptiveAvgPool2dZAdaptiveAvgPool3dZ	AvgPool1dZ	AvgPool2dZ	AvgPool3dZ	MaxPool1dZ	MaxPool2dZ	MaxPool3dZIdentityZHardsigmoidr   r   r*   Z
functionalZadaptive_avg_pool1dZadaptive_avg_pool2dZadaptive_avg_pool3dZeluZ	hardswishZinstance_normZ
layer_normZ
leaky_reluZsiluZmishr   Z
max_pool1dZ
max_pool2dZ
max_pool3dr   ZhardtanhZ	hardtanh_r   r   r    r   r   stacksumr   r!   catr&   meanr'   r-   r2   r8   r<   r)   rE   rL   rR   rW   rY   r[   r_   r]   rc   rd   re   rf   boolrg   r`   rS   ZTensorrq   r   rM   r~   r   r   r   r   r   r   r   r   r4   r7   r   r   r   r   r   r   r   __all__r   r   r   r   <module>   s    &"		

5
"
G
<     
Z