a
    –¥»aË^  ã                   @   sR  d dl Z d dlZd dlZd dlZd dlmZ d dlm  mZ d dl	m
Z
 d dlmZmZmZmZmZmZmZ d dlmZmZ d dlmZmZmZmZ dd„ Zd/d	d
„Zd0dd„Zdd„ Zdd„ Zd1dd„Z dd„ Z!dd„ Z"d2dd„Z#dd„ Z$dd„ Z%d3dd„Z&dej'ddfd d!„Z(d4d"d#„Z)d5d$d%„Z*d6d'd(„Z+d7d)d*„Z,d+d,„ Z-d8d-d.„Z.dS )9é    N)Ú_FusedModule)Ú)get_default_dynamic_quant_module_mappingsÚ(get_default_static_quant_module_mappingsÚget_default_qat_module_mappingsÚ$get_default_qconfig_propagation_listÚno_observer_setÚ_has_special_act_post_processÚ_get_special_act_post_process)ÚDeQuantStubÚQuantWrapper)Úadd_module_to_qconfig_obs_ctrÚdefault_dynamic_qconfigÚfloat16_dynamic_qconfigÚ!float_qparams_weight_only_qconfigc                 C   s   t | tjjƒpt | tjjƒS ©N)Ú
isinstanceÚtorchÚquantizationZObserverBaseZFakeQuantizeBase©Úmodule© r   úX/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/ao/quantization/quantize.pyÚis_activation_post_process   s    ÿr   Ú c           
      C   s�   |du rt ƒ }| t| ƒ|¡}| ||¡}t| d|ƒ}tjj || ¡ t|| ƒ}|| _|  	¡ D ],\}}|rv|d | n|}	t
|||||	ƒ q^dS )ay  This is a helper function for `propagate_qconfig_`

    Args:
        module: input module
        qconfig_dict: dictionary that maps from name of submodule to quantization
                     configuration
        allow_list: list of quantizable modules
        qconfig_parent: quantization config of parent module, we will fallback to
                       this config when there is no specified config for current
                       module
        prefix: corresponding prefix of the current module, used as key in
                qconfig_dict

    Return:
        None, module is modified inplace with qconfig attached
    NÚqconfigÚ.)r   ÚgetÚtypeÚgetattrr   r   r   Zassert_valid_qconfigr   Únamed_childrenÚ_propagate_qconfig_helper)
r   Úqconfig_dictÚ
allow_listZqconfig_parentÚprefixZmodule_qconfigZqconfig_with_device_checkÚnameÚchildÚmodule_prefixr   r   r   r       s    
ÿr    c                 C   s   |du ri }t | ||ƒ dS )a  Propagate qconfig through the module hierarchy and assign `qconfig`
    attribute on each leaf module

    Args:
        module: input module
        qconfig_dict: dictionary that maps from name or type of submodule to
            quantization configuration, qconfig applies to all submodules of a
            given module unless qconfig for the submodules are specified (when
            the submodule already has qconfig attribute)

    Return:
        None, module is modified inplace with qconfig attached
    N)r    )r   r!   r"   r   r   r   Úpropagate_qconfig_D   s    r'   c                 C   s
   |   |¡S )z3Forward hook that calls observer on the output
    )Úactivation_post_process)ÚselfÚinputÚoutputr   r   r   Ú_observer_forward_hookV   s    r,   c                 C   s   t | dƒsJ dƒ‚|  t¡S )Nr(   zFExpect activation_post_process attribut already attached to the module)ÚhasattrÚregister_forward_hookr,   r   r   r   r   Ú%register_activation_post_process_hook[   s    ÿr/   c                    sÄ  |du rt ƒ }|du ri }ˆ du r`t| ƒ}t|ƒdksDJ d |¡ƒ‚t|ƒdkr\tt|ƒƒnd‰ ddd„‰dd„ ‰d‡ ‡‡fd	d
„	}|  ¡ D ]ü\}}t|ƒtj	tj
fv rÀˆ|ƒr¾ˆ|jˆ ƒ|_qŒt|tƒrÜˆ|ƒrÚ||ƒ qŒt|ƒrøt|ƒ}	|||	ƒ qŒ|du�r$t|ƒ|v �r$ˆ|ƒ�rˆ||ƒ qŒˆ|ƒ�rxt|ƒ|v �rx|t|ƒ  |¡}
t| ||
ƒ |t|ƒ tƒ v�rˆ||
ƒ qŒt|||ˆ |ƒ qŒt| jƒdk�rÀt| tjjƒ�sÀt| ƒ|v �rÀ|| ƒ dS )aé  Add observer for the leaf child of the module.

    This function insert observer module to all leaf child module that
    has a valid qconfig attribute.

    Args:
        module: input module with qconfig attributes for all the leaf modules that we want to quantize
        device: parent device, if any
        non_leaf_module_list: list of non-leaf modules we want to add observer

    Return:
        None, module is modified inplace with added observer modules and forward_hooks
    Né   zSadd_observer_ only works with cpu or single-device CUDA modules, but got devices {}r   c                 S   s,   |d u r|   ¡ n|ƒ }|d ur(| |¡ |S r   )Ú
activationÚto)r   ÚdeviceÚspecial_act_post_processr1   r   r   r   Úget_activation_post_process}   s    
z2add_observer_.<locals>.get_activation_post_processc                 S   s   t | dƒo| jd uS )Nr   ©r-   r   )Úmr   r   r   Úneeds_observationƒ   s    z(add_observer_.<locals>.needs_observationc                    sF   ˆ| ƒrBt | tƒsB|  dˆ| jˆ |ƒ¡ t| ƒ}| jj|jdd� dS )zg Adds an activation post process module and register
        a post hook that calls the module
        r(   F)ÚlastN)r   r
   Z
add_moduler   r/   Ú_forward_hooksÚmove_to_endÚid)r7   r4   Úhandle©r3   r5   r8   r   r   Úinsert_activation_post_process†   s    ÿz5add_observer_.<locals>.insert_activation_post_process)N)N)r   Úget_unique_devices_ÚlenÚformatÚnextÚiterr   r   ÚnnqZFloatFunctionalZQFunctionalr   r(   r   r   r   r	   Ú
from_floatÚsetattrr   Úadd_observer_Ú_modulesr   ÚnnZ
Sequential)r   Úqconfig_propagation_listZnon_leaf_module_listr3   Úcustom_module_class_mappingÚdevicesr?   r$   r%   r4   Zobserved_childr   r>   r   rH   `   sL    ÿÿ





 
ÿrH   c                 C   s$   dd„ |   ¡ D ƒdd„ |  ¡ D ƒB S )Nc                 S   s   h | ]
}|j ’qS r   ©r3   ©Ú.0Úpr   r   r   Ú	<setcomp>³   ó    z&get_unique_devices_.<locals>.<setcomp>c                 S   s   h | ]
}|j ’qS r   rN   rO   r   r   r   rR   ´   rS   )Ú
parametersÚbuffersr   r   r   r   r@   ²   s    ÿr@   c                 C   sJ   t | jƒdkr&t| dƒr&| jr&t| ƒS |  ¡ D ]\}}t|ƒ| j|< q.| S )a{  Wrap the leaf child module in QuantWrapper if it has a valid qconfig
    Note that this function will modify the children of module inplace and it
    can return a new module which wraps the input module as well.

    Args:
        module: input module with qconfig attributes for all the leaf modules
        that we want to quantize

    Return:
        Either the inplace modified module with submodules wrapped in
        `QuantWrapper` based on qconfig or a new `QuantWrapper` module which
        wraps the input module, the latter case only happens when the input
        module is a leaf module and we want to quantize it.
    r   r   )rA   rI   r-   r   r   r   Úadd_quant_dequant)r   r$   r%   r   r   r   rV   ¶   s
    rV   Fc                 C   s„   t j d¡ |du ri }| di ¡}|s2t | ¡} |}|du rDtƒ }t| dd� tdd„ |  	¡ D ƒƒspt
 d¡ t| |||d� | S )	aƒ  Prepares a copy of the model for quantization calibration or quantization-aware training.

    Quantization configuration should be assigned preemptively
    to individual submodules in `.qconfig` attribute.

    The model will be attached with observer or fake quant modules, and qconfig
    will be propagated.

    Args:
        `model`: input model to be modified in-place
        `inplace`: carry out model transformations in-place, the original module is mutated
        `allow_list`: list of quantizable modules
        `observer_non_leaf_module_list`: list of non-leaf modules we want to add observer
        `prepare_custom_config_dict`: customization configuration dictionary for prepare function

    .. code-block:: python

       # Example of prepare_custom_config_dict:
       prepare_custom_config_dict = {
           # user will manually define the corresponding observed
           # module class which has a from_float class method that converts
           # float custom module to observed custom module
           "float_to_observed_custom_module_class": {
               CustomModule: ObservedCustomModule
           }
        }

    z!quantization_api.quantize.prepareNZ%float_to_observed_custom_module_class©r!   c                 s   s   | ]}t |d ƒo|jV  qdS )r   Nr6   )rP   r7   r   r   r   Ú	<genexpr>ú   rS   zprepare.<locals>.<genexpr>z¬None of the submodule got qconfig applied. Make sure you passed correct configuration through `qconfig_dict` or by assigning the `.qconfig` attribute directly on submodules)rL   )r   Ú_CÚ_log_api_usage_oncer   ÚcopyÚdeepcopyr   r'   ÚanyÚmodulesÚwarningsÚwarnrH   )ÚmodelÚinplacer"   Úobserver_non_leaf_module_listZprepare_custom_config_dictrL   rK   r   r   r   ÚprepareÌ   s"    

þrd   c                 C   sd   t | dƒrt| jƒrt| dƒ tƒ }| j ¡ D ]\}}|tu r.| |¡ q.|D ]}| j 	|¡ qNd S )Nr(   )
r-   r   r(   ÚdelattrÚsetr:   Úitemsr,   ÚaddÚpop)r   Zhandle_ids_to_removeZ	handle_idÚhook_fnr   r   r   Ú_remove_activation_post_process  s    
ÿ
rk   c                 C   s0   |   ¡ D ]}t|ƒ qt| dƒr$| `t| ƒ dS )zŠClean up the qconfig left in the module so that new qconfig can be
    propagated.

    Args:
        module: module to be cleaned up
    r   N)ÚchildrenÚ_remove_qconfigr-   r   rk   )r   r%   r   r   r   rm     s
    

rm   c                 C   s^   t j d¡ |du rtƒ }|s(t | ¡} |  ¡  t| dd� || g|¢R Ž  t| |dd� | S )aƒ  Quantize the input float model with post training static quantization.

    First it will prepare the model for calibration, then it calls
    `run_fn` which will run the calibration step, after that we will
    convert the model to a quantized model.

    Args:
        model: input float model
        run_fn: a calibration function for calibrating the prepared model
        run_args: positional arguments for `run_fn`
        inplace: carry out model transformations in-place, the original module is mutated
        mapping: correspondence between original module types and quantized counterparts

    Return:
        Quantized model.
    z"quantization_api.quantize.quantizeNT©rb   )	r   rY   rZ   r   r[   r\   Úevalrd   Úconvert)ra   Úrun_fnÚrun_argsÚmappingrb   r   r   r   Úquantize#  s    
rt   c                 C   sB  t j d¡ |du r¢|t jkrHtjttjttjttj	ttj
ttjti}qþ|t jkr|tjttjttjttj	ttj
ttjti}qþ|t jkr’tjti}qþtd |¡ƒ‚n\t|tƒrþ|t ju r¼t}n.|t ju rÌt}n|t ju rÜt}ntdt|ƒƒ‚tt|t |¡ƒƒ}|du �rtƒ }|�st | ¡} |  ¡  t| |ƒ t | |dd� | S )a}  Converts a float model to dynamic (i.e. weights-only) quantized model.

    Replaces specified modules with dynamic weight-only quantized versions and output the quantized model.

    For simplest usage provide `dtype` argument that can be float16 or qint8. Weight-only quantization
    by default is performed for layers with large weights size - i.e. Linear and RNN variants.

    Fine grained control is possible with `qconfig` and `mapping` that act similarly to `quantize()`.
    If `qconfig` is provided, the `dtype` argument is ignored.

    Args:
        model: input model
        qconfig_spec: Either:

            - A dictionary that maps from name or type of submodule to quantization
              configuration, qconfig applies to all submodules of a given
              module unless qconfig for the submodules are specified (when the
              submodule already has qconfig attribute). Entries in the dictionary
              need to be QConfigDynamic instances.

            - A set of types and/or submodule names to apply dynamic quantization to,
              in which case the `dtype` argument is used to specify the bit-width

        inplace: carry out model transformations in-place, the original module is mutated
        mapping: maps type of a submodule to a type of corresponding dynamically quantized version
            with which the submodule needs to be replaced

    z*quantization_api.quantize.quantize_dynamicNzTDon't know how to quantize with default settings for {}. Provide full qconfig pleasez.Unknown dtype specified for quantize_dynamic: Trn   )!r   rY   rZ   Úqint8rJ   ZLinearr   ZLSTMZGRUZLSTMCellZRNNCellZGRUCellÚfloat16r   Zquint8ZEmbeddingBagr   Ú
ValueErrorrB   r   rf   ÚRuntimeErrorÚstrÚdictÚzipÚ	itertoolsÚrepeatr   r[   r\   ro   r'   rp   )ra   Zqconfig_specZdtypers   rb   Zdefault_qconfigr   r   r   Úquantize_dynamic?  sR    
ú
ú
ÿÿ






r~   c                 C   s^   t j d¡ |du rtƒ }|s(t | ¡} t| dd� t| |ddd� t| t	| 
¡ ƒdd� | S )a  
    Prepares a copy of the model for quantization calibration or
    quantization-aware training and converts it to quantized version.

    Quantization configuration should be assigned preemptively
    to individual submodules in `.qconfig` attribute.

    Args:
        model: input model to be modified in-place
        mapping: dictionary that maps float modules to quantized modules to be
                 replaced.
        inplace: carry out model transformations in-place, the original module
                 is mutated
    z%quantization_api.quantize.prepare_qatNrW   TF)rs   rb   Úremove_qconfig)rc   rb   )r   rY   rZ   r   r[   r\   r'   rp   rd   rf   Úvalues)ra   rs   rb   r   r   r   Úprepare_qat�  s    
r�   c                 C   sN   t j d¡ |st | ¡} |  ¡  t| dd� || g|¢R Ž  t| dd� | S )ag  Do quantization aware training and output a quantized model

    Args:
        model: input model
        run_fn: a function for evaluating the prepared model, can be a
                function that simply runs the prepared model or a training
                loop
        run_args: positional arguments for `run_fn`

    Return:
        Quantized model.
    z&quantization_api.quantize.quantize_qatTrn   )r   rY   rZ   r[   r\   Ztrainr�   rp   )ra   rq   rr   rb   r   r   r   Úquantize_qat¨  s    
r‚   Tc                 C   s:   t j d¡ |st | ¡} t| |d|d� |r6t| ƒ | S )ag  Converts submodules in input module to a different module according to `mapping`
    by calling `from_float` method on the target module class. And remove qconfig at the
    end if remove_qconfig is set to True.

    Args:
        `module`: prepared and calibrated module
        `mapping`: a dictionary that maps from source module type to target
                   module type, can be overwritten to allow swapping user defined
                   Modules
        `inplace`: carry out model transformations in-place, the original module
                   is mutated
        `convert_custom_config_dict`: custom configuration dictionary for convert function

    .. code-block:: python

       # Example of convert_custom_config_dict:
       convert_custom_config_dict = {
           # user will manually define the corresponding quantized
           # module class which has a from_observed class method that converts
           # observed custom module to quantized custom module
           "observed_to_quantized_custom_module_class": {
               ObservedCustomModule: QuantizedCustomModule
           }
       }

    z!quantization_api.quantize.convertT)rb   Úconvert_custom_config_dict)r   rY   rZ   r[   r\   Ú_convertrm   )r   rs   rb   r   rƒ   r   r   r   rp   ¾  s    
þrp   c           
      C   sž   |du rt ƒ }|du ri }| di ¡}|s4t | ¡} i }|  ¡ D ]<\}}t|tƒslt|ƒ|vrlt||d|ƒ t	|||ƒ||< q@| 
¡ D ]\}}	|	| j|< q†| S )aÚ  Converts submodules in input module to a different module according to `mapping`
    by calling `from_float` method on the target module class

    Args:
        module: input module
        mapping: a dictionary that maps from source module type to target
                 module type, can be overwritten to allow swapping user defined
                 Modules
        inplace: carry out model transformations in-place, the original module
                 is mutated

    NZ)observed_to_quantized_custom_module_classT)r   r   r[   r\   r   r   r   r   r„   Úswap_modulerg   rI   )
r   rs   rb   rƒ   rL   Zreassignr$   ÚmodÚkeyÚvaluer   r   r   r„   å  s&    


ÿÿr„   c           	      C   sò   | }t | dƒrî| jdurîd}t| ƒ|v r@|t| ƒ  | ¡}d}n"t| ƒ|v rb|t| ƒ  | ¡}d}|rî| j ¡ D ]}| |¡ qp| j ¡ D ]}|t	urŠ| 
|¡ qŠt| ƒ}t|ƒdksÄJ d |¡ƒ‚t|ƒdkrÜtt|ƒƒnd}|rî| |¡ |S )a	  Swaps the module if it has a quantized counterpart and it has an
    `observer` attached.

    Args:
        mod: input module
        mapping: a dictionary that maps from nn module to nnq module

    Return:
        The corresponding quantized module of `mod`
    r   NFTr0   zQswap_module only works with cpu or single-device CUDA modules, but got devices {}r   )r-   r   r   Zfrom_observedrF   Z_forward_pre_hooksr€   Zregister_forward_pre_hookr:   r,   r.   r@   rA   rB   rC   rD   r2   )	r†   rs   rL   Únew_modZswappedZpre_hook_fnrj   rM   r3   r   r   r   r…     s2    ÿÿ
r…   c                 C   sZ   dd„ }t | dƒr$| j|||ƒd < |  ¡ D ](\}}|rD||ƒ| n|}t|||ƒ q,dS )a,  Traverse the modules and save all observers into dict.
    This is mainly used for quantization accuracy debug
    Args:
        mod: the top module we want to save all observers
        prefix: the prefix for the current module
        target_dict: the dictionary used to save all the observers
    c                 S   s   | dkr| S | d S )Nr   r   r   )r#   r   r   r   Ú
get_prefix=  s    z%get_observer_dict.<locals>.get_prefixr(   N)r-   r(   r   Úget_observer_dict)r†   Útarget_dictr#   rŠ   r$   r%   r&   r   r   r   r‹   5  s    
r‹   )NNr   )NN)NNNN)FNNN)NF)NF)F)NFTN)NFN)r   )/r[   r|   r_   r   Ztorch.nnrJ   Ztorch.nn.quantizedZ	quantizedrE   Ztorch.nn.intrinsicr   Z(torch.quantization.quantization_mappingsr   r   r   r   r   r   r	   Ztorch.ao.quantization.stubsr
   r   Ztorch.quantization.qconfigr   r   r   r   r   r    r'   r,   r/   rH   r@   rV   rd   rk   rm   rt   ru   r~   r�   r‚   rp   r„   r…   r‹   r   r   r   r   Ú<module>   sN   $
  ÿ
%

R   þ
8
ÿ
N

  þ
(  þ
&*