a
    Ž¥»aß_  ã                	   @   s¶  d dl Z d dlmZ d dlmZ d dlmZmZmZ ddl	m
Z
 ddl	mZmZ ddl	mZ dd	l	mZ dd
lmZ ddlmZ ddlmZmZ ddlmZmZmZmZ d dlmZ d dlmZmZmZm Z m!Z!m"Z"m#Z# e j$j%ddœdd„Z&e j$j%ddœdd„Z'd7eee(ef edœdd„Z)G dd„ de*ƒZ+G dd„ de*ƒZ,G dd„ deƒZ-d8e j$j%ee"ee(ef  e"ee(ef  e"ee(ef  e.edœd d!„Z/d9e j$j%eee(ef ee(ef ed"œd#d$„Z0d:e j$j%ee(ef ed%œd&d'„Z1d;e j$j%ee"ee(ef  e"ee(ef  e"ee(ef  ed(œd)d*„Z2d<e j$j%ee"ee(ef  e"ee(ef  ed"œd+d,„Z3d=ee.ee(ef e.e.ed.œd/d0„Z4d>ee.ee(ef e.ed1œd2d3„Z5d?ee.ee(ef ed4œd5d6„Z6dS )@é    N)ÚGraphModule)ÚTracer)ÚTargetÚNodeÚArgumenté   )ÚFuser)ÚprepareÚconvert)Úget_fbgemm_backend_config_dict)Ú get_tensorrt_backend_config_dict)Úgraph_pretty_str)Úget_custom_module_class_keys)ÚObservedGraphModuleÚQuantizedGraphModule)Ú)check_is_valid_convert_custom_config_dictÚ&check_is_valid_fuse_custom_config_dictÚ)check_is_valid_prepare_custom_config_dictÚcheck_is_valid_qconfig_dict)Ú_FusedModule)ÚDictÚAnyÚListÚCallableÚTupleÚOptionalÚSet)ÚmodelÚreturnc                 C   s*   t | tƒs&tdtt| ƒƒ d d ƒ‚d S )Nz,input model must be a GraphModule, Got type:z Please make zsure to follow the tutorials.)Ú
isinstancer   Ú
ValueErrorÚstrÚtype)r   © r#   úX/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/quantization/quantize_fx.pyÚ_check_is_graph_module   s    

ÿÿþÿr%   c                 C   sb   g }|   ¡ D ],\}}t|tjjjƒr0| |¡ qt|ƒ q|D ]}| j|= tjj 	¡ | j|< q>dS )z1 Swap FloatFunctional with FXFloatFunctional
    N)
Znamed_childrenr   ÚtorchÚnnÚ	quantizedZFloatFunctionalÚappendÚ_swap_ff_with_fxffZ_modulesZFXFloatFunctional)r   Zmodules_to_swapÚnameÚmoduler#   r#   r$   r*      s    
r*   )Úgraph_moduleÚfuse_custom_config_dictr   c                 C   s   t | ƒ tƒ }| | |¡S )z² Internal helper function to fuse modules in preparation for quantization

    Args:
        graph_module: GraphModule object from symbolic tracing (torch.fx.symbolic_trace)
    )r%   r   Zfuse)r-   r.   Zfuserr#   r#   r$   Ú_fuse_fx)   s    r/   c                       s(   e Zd ZdZeedœ‡ fdd„Z‡  ZS )ÚScopeaõ   Scope object that records the module path and the module type
    of a module. Scope is used to track the information of the module
    that contains a Node in a Graph of GraphModule. For example:
    class Sub(torch.nn.Module):
        def forward(self, x):
            # This will be a call_method Node in GraphModule,
            # scope for this would be (module_path="sub", module_type=Sub)
            return x.transpose(1, 2)

    class M(torch.nn.Module):
        def __init__(self):
            self.sub = Sub()

        def forward(self, x):
            # This will be a call_method Node as well,
            # scope for this would be (module_path="", None)
            x = x.transpose(1, 2)
            x = self.sub(x)
            return x

    )Úmodule_pathÚmodule_typec                    s   t ƒ  ¡  || _|| _d S ©N)ÚsuperÚ__init__r1   r2   )Úselfr1   r2   ©Ú	__class__r#   r$   r5   K   s    
zScope.__init__)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r!   r   r5   Ú__classcell__r#   r#   r7   r$   r0   5   s   r0   c                       s>   e Zd ZdZeejjedœ‡ fdd„Z	dd„ Z
dd„ Z‡  ZS )	ÚScopeContextManagerzÿ A context manager to track the Scope of Node during symbolic
    tracing.
    When entering a forward function of a Module, we'll update the scope information of
    the current module, and when we exit, we'll restore the previous scope information.
    )ÚscopeÚcurrent_moduleÚcurrent_module_pathc                    s8   t ƒ  ¡  |j| _|j| _|| _|| j_t|ƒ| j_d S r3   )r4   r5   r2   Úprev_module_typer1   Úprev_module_pathr?   r"   )r6   r?   r@   rA   r7   r#   r$   r5   V   s    
zScopeContextManager.__init__c                 C   s   d S r3   r#   )r6   r#   r#   r$   Ú	__enter__b   s    zScopeContextManager.__enter__c                 G   s   | j | j_| j| j_d S r3   )rC   r?   r1   rB   r2   )r6   Úargsr#   r#   r$   Ú__exit__e   s    

zScopeContextManager.__exit__)r9   r:   r;   r<   r0   r&   r'   ÚModuler!   r5   rD   rF   r=   r#   r#   r7   r$   r>   P   s   ür>   c                	       s°   e Zd Zee ee dœ‡ fdd„Zejj	ee
dœdd„Zejj	edef eedf eeef edœ‡ fd	d
„Zdeeeedf eeef ee ee edœ‡ fdd„Z‡  ZS )ÚQuantizationTracer)Úskipped_module_namesÚskipped_module_classesc                    s,   t ƒ  ¡  || _|| _tdd ƒ| _i | _d S )NÚ )r4   r5   rI   rJ   r0   r?   Únode_name_to_scope)r6   rI   rJ   r7   r#   r$   r5   l   s
    
zQuantizationTracer.__init__)ÚmÚmodule_qualified_namer   c                 C   s>   |j  d¡rt|tjjƒ p<|| jv p<t|ƒ| jv p<t|t	ƒS )Nztorch.nn)
r:   Ú
startswithr   r&   r'   Z
SequentialrI   r"   rJ   r   )r6   rM   rN   r#   r#   r$   Úis_leaf_module{   s    ÿþýüz!QuantizationTracer.is_leaf_module.)rM   ÚforwardrE   Úkwargsr   c                    sN   |   |¡}t| j||ƒ�" tƒ  ||||¡W  d   ƒ S 1 s@0    Y  d S r3   )Zpath_of_moduler>   r?   r4   Úcall_module)r6   rM   rQ   rE   rR   rN   r7   r#   r$   rS   ‚   s    
zQuantizationTracer.call_moduleN)ÚkindÚtargetrE   rR   r+   Ú	type_exprr   c                    s2   t ƒ  ||||||¡}| jj| jjf| j|j< |S r3   )r4   Úcreate_noder?   r1   r2   rL   r+   )r6   rT   rU   rE   rR   r+   rV   Únoder7   r#   r$   rW   ‰   s    zQuantizationTracer.create_node)NN)r9   r:   r;   r   r!   r   r5   r&   r'   rG   ÚboolrP   r   r   r   rS   r   r   r   r   rW   r=   r#   r#   r7   r$   rH   k   s   ý6  þþrH   F)r   Úqconfig_dictÚprepare_custom_config_dictÚequalization_qconfig_dictÚbackend_config_dictÚis_standalone_moduler   c              	   C   s(  |du ri }|du ri }t |ƒ t|ƒ t |ƒ | dg ¡}| dg ¡}t| ƒ |s¢| dg ¡}|dd„ |D ƒ7 }| dg ¡}	|dd„ |	D ƒ7 }t|d	ƒ}
||
7 }| d
g ¡}t||ƒ}t| | | ¡ƒ}|D ]}t||t	| |ƒƒ qÌt
||ƒ}t|||j||||d�}|D ]}t||t	| |ƒƒ �q
|S )a7   Internal helper function for prepare_fx
    Args:
      `model`, `qconfig_dict`, `prepare_custom_config_dict`, `equalization_qonfig_dict`:
      see docs for :func:`~torch.quantization.prepare_fx`
      `is_standalone_module`: a boolean flag indicates whether we are
      quantizing a standalone module or not, a standalone module
      is a submodule of the parent module that is not inlined in the
forward graph of the parent module,
      the way we quantize standalone module is described in:
      :func:`~torch.quantization._prepare_standalone_module_fx`
    NZnon_traceable_module_nameZnon_traceable_module_classZstandalone_module_namec                 S   s   g | ]}|d  ‘qS ©r   r#   ©Ú.0Úconfigr#   r#   r$   Ú
<listcomp>´   ó    z_prepare_fx.<locals>.<listcomp>Zstandalone_module_classc                 S   s   g | ]}|d  ‘qS r_   r#   r`   r#   r#   r$   rc   ·   rd   Z%float_to_observed_custom_module_classÚpreserved_attributes)r[   r\   r]   r^   )r   r   Úgetr*   r   rH   r   ÚtraceÚsetattrÚgetattrr/   r	   rL   )r   rZ   r[   r\   r]   r^   rI   rJ   Zstandalone_module_name_configsZstandalone_module_class_configsZfloat_custom_module_classesre   Ztracerr-   Ú	attr_nameÚpreparedr#   r#   r$   Ú_prepare_fx�   sN    ÿÿ
ù	rl   )r   rZ   r[   r]   r   c                 C   s   t | |||dd�S )aú   [Internal use only] Prepare a standalone module, so that it can be used when quantizing the
    parent module.
    standalone_module means it a submodule that is not inlined in parent module,
        and will be quantized separately as one unit.

    How the standalone module is observed is specified by `input_quantized_idxs` and
    `output_quantized_idxs` in the prepare_custom_config for the standalone module

    Returns:
        model(GraphModule): prepared standalone module
        attributes:
            _standalone_module_input_quantized_idxs(List[Int]): a list of
                indexes for the graph input that is expected to be quantized,
                same as input_quantized_idxs configuration provided
                for the standalone module
            _standalone_module_output_quantized_idxs(List[Int]): a list of
                indexs for the graph output that is quantized
                same as input_quantized_idxs configuration provided
                for the standalone module
    T©r^   )rl   ©r   rZ   r[   r]   r#   r#   r$   Ú_prepare_standalone_module_fxÐ   s    ro   )r   r.   r   c                 C   sn   t j d¡ | jrJ dƒ‚t|ƒ t j | ¡}tƒ }|rHt| dg ¡ƒ}|D ]}t	||t
| |ƒƒ qLt||ƒS )a´   Fuse modules like conv+bn, conv+bn+relu etc, model must be in eval mode.
    Fusion rules are defined in torch.quantization.fx.fusion_pattern.py
    Args:
        `model`: a torch.nn.Module model
        `fuse_custom_config_dict`: Dictionary for custom configurations for fuse_fx, e.g.
         fuse_custom_config_dict = {
           "additional_fuser_method_mapping": {
             (Module1, Module2): fuse_module1_module2
           }

           # Attributes that are not used in forward function will
           # be removed when constructing GraphModule, this is a list of attributes
           # to preserve as an attribute of the GraphModule even when they are
           # not used in the code, these attributes will also persist through deepcopy
           "preserved_attributes": ["preserved_attr"],
         }

    Example:
    ```python
    from torch.quantization import fuse_fx
    m = Model().eval()
    m = fuse_fx(m)
    ```
    z$quantization_api.quantize_fx.fuse_fxz)fuse_fx only works on models in eval modere   )r&   Ú_CÚ_log_api_usage_onceÚtrainingr   ÚfxZsymbolic_traceÚsetrf   rh   ri   r/   )r   r.   r-   re   rj   r#   r#   r$   Úfuse_fxë   s    ru   )r   rZ   r[   r\   r]   r   c                 C   s*   t j d¡ | jrJ dƒ‚t| ||||ƒS )a¢   Prepare a model for post training static quantization

    Args:
      `model`: torch.nn.Module model, must be in eval mode
      `qconfig_dict`: qconfig_dict is a dictionary with the following configurations:
      qconfig_dict = {
      # optional, global config
      "": qconfig?,

      # optional, used for module and function types
      # could also be split into module_types and function_types if we prefer
      "object_type": [
        (torch.nn.Conv2d, qconfig?),
        (torch.nn.functional.add, qconfig?),
        ...,
       ],

      # optional, used for module names
      "module_name": [
        ("foo.bar", qconfig?)
        ...,
      ],

      # optional, matched in order, first match takes precedence
      "module_name_regex": [
        ("foo.*bar.*conv[0-9]+", qconfig?)
        ...,
      ],

      # optional, used for matching object type invocations in a submodule by
      # order
      # TODO(future PR): potentially support multiple indices ('0,1') and/or
      #   ranges ('0:3').
      "module_name_object_type_order": [
        # fully_qualified_name, object_type, index, qconfig
        ("foo.bar", torch.nn.functional.linear, 0, qconfig?),
      ],

      # priority (in increasing order):
      #   global, object_type, module_name_regex, module_name,
      #   module_name_object_type_order
      # qconfig == None means fusion and quantization should be skipped for anything
      # matching the rule
      }
      `prepare_custom_config_dict`: customization configuration dictionary for
      quantization tool:
      prepare_custom_config_dict = {
        # optional: specify the path for standalone modules
        # These modules are symbolically traced and quantized as one unit
        "standalone_module_name": [
           # module_name, qconfig_dict, prepare_custom_config_dict
           ("submodule.standalone",
            None,  # qconfig_dict for the prepare function called in the submodule,
                   # None means use qconfig from parent qconfig_dict
            {"input_quantized_idxs": [], "output_quantized_idxs": []})  # prepare_custom_config_dict
        ],

        "standalone_module_class": [
            # module_class, qconfig_dict, prepare_custom_config_dict
            (StandaloneModule,
             None,  # qconfig_dict for the prepare function called in the submodule,
                    # None means use qconfig from parent qconfig_dict
            {"input_quantized_idxs": [0], "output_quantized_idxs": [0]})  # 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
        # (only needed for static quantization)
        "float_to_observed_custom_module_class": {
           "static": {
               CustomModule: ObservedCustomModule
           }
        },

        # the qualified names for the submodule that are not symbolically traceable
        "non_traceable_module_name": [
           "non_traceable_module"
        ],

        # the module classes that are not symbolically traceable
        # we'll also put dynamic/weight_only custom module here
        "non_traceable_module_class": [
           NonTraceableModule
        ],

        # Additional fuser_method mapping
        "additional_fuser_method_mapping": {
           (torch.nn.Conv2d, torch.nn.BatchNorm2d): fuse_conv_bn
        },

        # Additioanl module mapping for qat
        "additional_qat_module_mapping": {
           torch.nn.intrinsic.ConvBn2d: torch.nn.qat.ConvBn2d
        },

        # Additional fusion patterns
        "additional_fusion_pattern": {
           (torch.nn.BatchNorm2d, torch.nn.Conv2d): ConvReluFusionhandler
        },

        # Additional quantization patterns
        "additional_quant_pattern": {
           torch.nn.Conv2d: ConvReluQuantizeHandler,
           (torch.nn.ReLU, torch.nn.Conv2d): ConvReluQuantizeHandler,
        }

        # By default, inputs and outputs of the graph are assumed to be in
        # fp32. Providing `input_quantized_idxs` will set the inputs with the
        # corresponding indices to be quantized. Providing
        # `output_quantized_idxs` will set the outputs with the corresponding
        # indices to be quantized.
        "input_quantized_idxs": [0],
        "output_quantized_idxs": [0],

        # Attributes that are not used in forward function will
        # be removed when constructing GraphModule, this is a list of attributes
        # to preserve as an attribute of the GraphModule even when they are
        # not used in the code, these attributes will also persist through deepcopy
        "preserved_attributes": ["preserved_attr"],
      }
      `equalization_qconfig_dict`: equalization_qconfig_dict is a dictionary
      with a similar structure as qconfig_dict except it will contain
      configurations specific to equalization techniques such as input-weight
      equalization.
      `backend_config_dict`: a dictionary that specifies how operators are quantized
       in a backend, this includes how the operaetors are observed,
       supported fusion patterns, how quantize/dequantize ops are
       inserted, supported dtypes etc. The structure of the dictionary is still WIP
       and will change in the future, please don't use right now.


    Return:
      A GraphModule with observer (configured by qconfig_dict), ready for calibration

    Example:
    ```python
    import torch
    from torch.quantization import get_default_qconfig
    from torch.quantization import prepare_fx

    float_model.eval()
    qconfig = get_default_qconfig('fbgemm')
    def calibrate(model, data_loader):
        model.eval()
        with torch.no_grad():
            for image, target in data_loader:
                model(image)

    qconfig_dict = {"": qconfig}
    prepared_model = prepare_fx(float_model, qconfig_dict)
    # Run calibration
    calibrate(prepared_model, sample_inference_data)
    ```
    z'quantization_api.quantize_fx.prepare_fxz-prepare_fx only works for models in eval mode©r&   rp   rq   rr   rl   )r   rZ   r[   r\   r]   r#   r#   r$   Ú
prepare_fx  s     !ûrw   c                 C   s*   t j d¡ | jsJ dƒ‚t| |||d�S )aÒ   Prepare a model for quantization aware training
    Args:
      `model`: torch.nn.Module model, must be in train mode
      `qconfig_dict`: see :func:`~torch.quantization.prepare_fx`
      `prepare_custom_config_dict`: see :func:`~torch.quantization.prepare_fx`
      `backend_config_dict`: see :func:`~torch.quantization.prepare_fx`

    Return:
      A GraphModule with fake quant modules (configured by qconfig_dict), ready for
      quantization aware training

    Example:
    ```python
    import torch
    from torch.quantization import get_default_qat_qconfig
    from torch.quantization import prepare_fx

    qconfig = get_default_qat_qconfig('fbgemm')
    def train_loop(model, train_data):
        model.train()
        for image, target in data_loader:
            ...

    float_model.train()
    qconfig_dict = {"": qconfig}
    prepared_model = prepare_fx(float_model, qconfig_dict)
    # Run calibration
    train_loop(prepared_model, train_loop)
    ```
    z+quantization_api.quantize_fx.prepare_qat_fxz3prepare_qat_fx only works for models in  train mode)r]   rv   rn   r#   r#   r$   Úprepare_qat_fxº  s    "ürx   T)r-   Úis_referenceÚconvert_custom_config_dictr^   Ú_remove_qconfigr   c                 C   sZ   |du ri }t | ƒ t|ƒ t| ||||d�}| dg ¡}|D ]}t||t| |ƒƒ q>|S )zb `is_standalone_module`: see docs in :func:`~torch.quantization.prepare_standalone_module_fx`
    N)Z_remove_qconfig_flagre   )r%   r   r
   rf   rh   ri   )r-   ry   rz   r^   r{   r(   re   rj   r#   r#   r$   Ú_convert_fxå  s    þr|   )r-   ry   rz   r{   r   c                 C   s   t j d¡ t| |||d�S )aw   Convert a calibrated or trained model to a quantized model
    Args:
        `graph_module`: A prepared and calibrated/trained model (GraphModule)
        `is_reference`: flag for whether to produce a reference quantized model,
        which will be a common interface between pytorch quantization with
        other backends like accelerators
        `convert_custom_config_dict`: dictionary for custom configurations for convert function:
        convert_custom_config_dict = {

          # addtional object (module/operator) mappings that will overwrite the default
          # module mappingn
          "additional_object_mapping": {
             "static": {
                FloatModule: QuantizedModule,
                float_op: quantized_op
             },
             "dynamic": {
                FloatModule: DynamicallyQuantizedModule,
                float_op: dynamically_quantized_op
             },
          },

          # 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": {
             "static": {
                 ObservedCustomModule: QuantizedCustomModule
             },
             "dynamic": {
                 ObservedCustomModule: QuantizedCustomModule
             },
             "weight_only": {
                 ObservedCustomModule: QuantizedCustomModule
             }
          },

          # Attributes that are not used in forward function will
          # be removed when constructing GraphModule, this is a list of attributes
          # to preserve as an attribute of the GraphModule even when they are
          # not used in the code
          "preserved_attributes": ["preserved_attr"],
        }
        `_remove_qconfig`: Option to remove the qconfig attributes in the model after convert.

    Return:
        A quantized model (GraphModule)

    Example:
    ```python
    # prepared_model: the model after prepare_fx/prepare_qat_fx and calibration/training
    quantized_model = convert_fx(prepared_model)
    ```
    z'quantization_api.quantize_fx.convert_fx)r{   )r&   rp   rq   r|   )r-   ry   rz   r{   r#   r#   r$   Ú
convert_fxû  s    :r}   )r-   ry   rz   r   c                 C   s   t | ||dd�S )ay   [Internal use only] Convert a model produced by :func:`~torch.quantization.prepare_standalone_module_fx`
    and convert it to a quantized model

    Returns a quantized standalone module, whether input/output is quantized is
    specified by prepare_custom_config_dict, with
    input_quantized_idxs, output_quantized_idxs, please
    see docs for prepare_fx for details
    Trm   )r|   )r-   ry   rz   r#   r#   r$   Ú_convert_standalone_module_fx8  s    r~   )N)NNNF)NN)N)NNN)NN)NFT)FNT)FN)7r&   Ztorch.fxr   Ztorch.fx._symbolic_tracer   Ztorch.fx.noder   r   r   rs   r   r	   r
   r   r   Zfx.utilsr   r   Zfx.graph_moduler   r   Zfx.qconfig_utilsr   r   r   r   Ztorch.nn.intrinsicr   Útypingr   r   r   r   r   r   r   r'   rG   r%   r*   r!   r/   Úobjectr0   r>   rH   rY   rl   ro   ru   rw   rx   r|   r}   r~   r#   r#   r#   r$   Ú<module>   s¬   $ þþ'    ûûC  ü
ü ÿÿ'   üü -  ýý-   ü
ü   ý
ý>  þþ