a
    Þñh5T  ã                   @   st  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  m
Z d dlm  m  mZ ddlmZmZmZmZ ddl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  d.dd	„Z!d/d
d„Z"dd„ Z#dd„ Z$dd„ Z%d0dd„Z&dd„ Z'dd„ Z(d1dd„Z)dd„ Z*d2dd„Z+dej,ddfdd „Z-d3d!d"„Z.d4d#d$„Z/d5d&d'„Z0d6d(d)„Z1d*d+„ Z2d7d,d-„Z3dS )8é    Né   )Ú!get_dynamic_quant_module_mappingsÚ get_static_quant_module_mappingsÚget_qat_module_mappingsÚget_qconfig_propagation_list)Úis_custom_module_classÚ get_observed_custom_module_classÚ!get_quantized_custom_module_classÚmark_observed_custom_moduleÚis_observed_custom_module)ÚDeQuantStubÚQuantWrapper)Údefault_dynamic_qconfigÚfloat16_dynamic_qconfigÚfloat_qparams_dynamic_qconfigÚ c           	      C   sv   |du rt ƒ }| t| ƒ|¡}| ||¡}t| d|ƒ}|| _|  ¡ D ],\}}|r\|d | n|}t|||||ƒ qDd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   Únamed_childrenÚ_propagate_qconfig_helper)	ÚmoduleÚqconfig_dictÚ
allow_listZqconfig_parentÚprefixZmodule_qconfigÚnameÚchildÚmodule_prefix© r    ú[/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/quantization/quantize.pyr      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_=   s    r"   c                 C   s
   |   |¡S )z3Forward hook that calls observer on the output
    )Úactivation_post_process)ÚselfÚinputÚoutputr    r    r!   Ú_observer_forward_hookO   s    r'   c                 C   s   | j |Ž  dS )zR Forward pre hook that calls observer on the input (can be a tuple of values)
    N)Úactivation_pre_process)r$   r%   r    r    r!   Ú_observer_forward_pre_hookT   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 rTt| ƒ}t|ƒdks8J d |¡ƒ‚t|ƒdkrPtt|ƒƒnd‰ dd„ ‰dd„ ‰‡ ‡‡fd	d
„}|  ¡ D ]ô\}}t|ƒtj	ks t|ƒtj
krÄt|dƒrÂ|jdurÂˆ|jˆ ƒ|_q||du�rt|ƒ|v �r||ƒ ˆ|ƒ�rp|du�rp| d|ƒ ¡ | t¡ q|ˆ|ƒ�r`tt|ƒƒ�r`tt|ƒƒ |¡}	t|	t|ƒƒ t| ||	ƒ ||	ƒ q|t|||ˆ |ƒ q|t| jƒdk�rÔt| tjjƒ�sÔt| ƒ|v �rÔ|| ƒ ˆ| ƒ�rÔ|du�rÔ|  d|ƒ ¡ |  t¡ 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
    Nr   zSadd_observer_ only works with cpu or single-device CUDA modules, but got devices {}r   c                 S   s   |   ¡ }|d ur| |¡ |S )N)Ú
activationÚto)r   Údevicer.   r    r    r!   Úget_activation_post_processz   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                    s:   ˆ| ƒr6|   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)Ú
add_moduler   r-   Ú_forward_hooksÚmove_to_endÚid)r3   Úhandle©r0   r1   r4   r    r!   Úinsert_activation_post_processƒ   s    z5add_observer_.<locals>.insert_activation_post_processr   r(   )r   Úget_unique_devices_ÚlenÚformatÚnextÚiterr   r   ÚnnqZFloatFunctionalZQFunctionalr*   r   r#   r6   Úregister_forward_pre_hookr)   r   r   Ú
from_floatr
   ÚsetattrÚadd_observer_Ú_modulesÚ
isinstanceÚtorchÚnnZ
Sequential)
r   Úqconfig_propagation_listZnon_leaf_module_listr0   ÚprehookÚdevicesr<   r   r   Zobserved_childr    r;   r!   rF   `   sJ    ÿÿ


 
ÿ

rF   c                 C   s$   dd„ |   ¡ D ƒdd„ |  ¡ D ƒB S )Nc                 S   s   h | ]
}|j ’qS r    ©r0   ©Ú.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   )r>   rG   r*   r   r   r   Úadd_quant_dequant)r   r   r   r    r    r!   rV   ³   s
    rV   Fc                 C   s`   |st  | ¡} |}|du r tƒ }t| dd� tdd„ |  ¡ D ƒƒsLt 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
        prehook: observer we want to add to forward_pre_hook
    N©r   c                 s   s   | ]}t |d ƒo|jV  qdS )r   Nr2   )rP   r3   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   )	ÚcopyÚdeepcopyr   r"   ÚanyÚmodulesÚwarningsÚwarnrF   )ÚmodelÚinplacer   Úobserver_non_leaf_module_listrL   rK   r    r    r!   ÚprepareÉ   s    

rb   c                 C   s(   |   ¡ D ]}t|ƒ qt| dƒr$| `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   )r   r   r    r    r!   rd   ë   s    

rd   c                 C   sL   |du rt ƒ }|st | ¡} |  ¡  t| dd� || |ƒ 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.
    NT©r`   )r   rY   rZ   Úevalrb   Úconvert)r_   Úrun_fnÚrun_argsÚmappingr`   r    r    r!   Úquantizeø   s    

rk   c                 C   s6  |du r–|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rpt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

    NzTDon't know how to quantize with default settings for {}. Provide full qconfig pleasez.Unknown dtype specified for quantize_dynamic: Tre   )rI   Úqint8rJ   ZLinearr   ZLSTMZGRUZLSTMCellZRNNCellZGRUCellÚfloat16r   Zquint8ZEmbeddingBagr   Ú
ValueErrorr?   rH   ÚsetÚRuntimeErrorÚstrÚdictÚzipÚ	itertoolsÚrepeatr   rY   rZ   rf   r"   rg   )r_   Zqconfig_specZdtyperj   r`   Zdefault_qconfigr    r    r!   Úquantize_dynamic  sP    
ú
ú
ÿÿ






rv   c                 C   sR   |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
    NrW   TF)rj   r`   Úremove_qconfig)ra   r`   )r   rY   rZ   r"   rg   rb   ro   Úvalues)r_   rj   r`   r    r    r!   Úprepare_qat`  s    
ry   c                 C   s<   |st  | ¡} |  ¡  t| dd� || |ƒ 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.
    Tre   )rY   rZ   Ztrainry   rg   )r_   rh   ri   r`   r    r    r!   Úquantize_qaty  s    

rz   Tc                 C   s,   |st  | ¡} t| |dd� |r(t| ƒ | S )a  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: 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

    Tre   )rY   rZ   Ú_convertrd   )r   rj   r`   rw   r    r    r!   rg   Ž  s    
rg   c           	      C   s¶   |du rt ƒ }|st | ¡} i }tjtjtjtjtjtj	tj
tjtjtjtjtjf}|  ¡ D ]8\}}t|ƒ|vr†t|ƒs†t||d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

    NTre   )r   rY   rZ   ÚnniZConvBn2dZConvBnReLU2dZ
LinearReLUZBNReLU2dZBNReLU3dZConvBn1dZ
ConvReLU1dZConvBnReLU1dZ
ConvReLU2dZ
ConvReLU3dÚnniqatr   r   r   r{   Úswap_moduleÚitemsrG   )	r   rj   r`   ZreassignZSWAPPABLE_MODULESr   ÚmodÚkeyÚvaluer    r    r!   r{   £  s6    
õÿr{   c                 C   sø   | }t | dƒr| jdus$t| ƒtkrôd}t| ƒrFt| jƒ | ¡}d}n"t| ƒ|v rh|t| ƒ  | ¡}d}|rô| j	 
¡ D ]}| |¡ qv| 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   NFTr   zQswap_module only works with cpu or single-device CUDA modules, but got devices {}r   )r*   r   r   r   r   r	   Z_FLOAT_MODULEZfrom_observedrD   Z_forward_pre_hooksrx   rC   r7   r'   r+   r=   r>   r?   r@   rA   r/   )r€   rj   Únew_modZswappedZpre_hook_fnZhook_fnrM   r0   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…   ý  s    
r…   )NNr   )NN)NNNN)FNNN)NF)NF)F)NFT)NF)r   )4rY   rt   r]   rI   Ztorch.nnrJ   Ztorch.nn.intrinsicZ	intrinsicr|   Ztorch.nn.quantizedZ	quantizedrB   Ztorch.nn.intrinsic.qatZqatr}   Zquantization_mappingsr   r   r   r   Zcustom_module_class_mappingsr   r   r	   r
   r   Zstubsr   r   r   r   r   r   r   r"   r'   r)   r-   rF   r=   rV   rb   rd   rk   rl   rv   ry   rz   rg   r{   r~   r…   r    r    r    r!   Ú<module>   sF     ÿ
!

O  ÿ
"
ÿ
M



/+