a
    Þñh¥   ã                   @   s¸   d dl mZ d dl mZ ddlmZ d dlmZ dd„ Zd"d	d
„Zdd„ Z	d#dd„Z
d$dd„Zd%dd„Zd&dd„Zdd„ Zd'dd„ZeZeZd(dd„Zd)dd„Zd*dd„Zd+d d!„ZdS ),é   )ÚFuser)Ú	Quantizeré    )ÚGraphModule)Úgraph_pretty_strc                 C   s"   t | tƒstdtt| ƒƒ ƒ‚d S )Nzxinput model must be a GraphModule, please run torch._fx.symbolic_trace on your model before using quantize_fx. Got type:)Ú
isinstancer   Ú
ValueErrorÚstrÚtype)Úmodel© r   ú^/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/quantization/quantize_fx.pyÚ_check_is_graph_module   s    

þÿr   Fc                 C   s   t | ƒ tƒ }| | |¡S )z— Fuse modules in preparation for quantization

    Args:
        graph_module: GraphModule object from symbolic tracing (torch._fx.symbolic_trace)
    )r   r   Zfuse)Úgraph_moduleÚinplaceZfuserr   r   r   Úfuse_fx   s    r   c                 C   s:   t | ƒ t| |ƒ} tƒ }|r"|jn|j}|| |dd�}|S )NT)r   )r   r   r   Zprepare_dynamicÚprepare)r   Úqconfig_dictr   Úis_dynamic_quantÚ	quantizerr   Úpreparedr   r   r   Ú_prepare_fx   s    
r   c                 C   s   t | ||dd�S )a¦   Prepare a model for post training static quantization or
    qantization aware training, not for public use.

    Args:
      graph_module: model from symbolic_tracing (torch._fx.symbolic_trace), must be
      an eval model
      qconfig_dict: see :func:`~torch.quantization.quantize_fx`

    Return:
      A GraphModule with observer or fake quant modules, ready for
      calibration or quantization aware training
    F©r   ©r   ©r   r   r   r   r   r   Ú
prepare_fx   s    r   c                 C   s   | j rJ dƒ‚t| ||ƒS )Nz4prepare_static_fx only works for models in eval mode©Útrainingr   r   r   r   r   Úprepare_static_fx.   s    r   c                 C   s   | j sJ dƒ‚t| ||ƒS )ah   Prepare a model for quantization aware training
    Args:
      graph_module: model from symbolic_tracing (torch._fx.symbolic_trace), must be
      a train model
      qconfig_dict: see :func:`~torch.quantization.quantize_fx`

    Return:
      A GraphModule with observer or fake quant modules, ready for
      calibration or quantization aware training
    z2prepare_qat_fx only works for models in train moder   r   r   r   r   Úprepare_qat_fx3   s    r   c                 C   s   t | ||dƒS )z< Prepare a model for post training dynamic quantization
    Tr   r   r   r   r   Úprepare_dynamic_fxB   s    r    c                 C   s   t | ƒ tƒ }| | |||¡S )N)r   r   Úconvert)r   r   Údebugr   r   r   r   r   Ú_convert_fxG   s    r#   c                 C   s   t | ||dd�S )z@ Convert a calibrated or trained model to a quantized model
    Fr   ©r#   ©r   r   r"   r   r   r   Ú
convert_fxL   s    r&   c                 C   s   t | ||dd�S )NTr   r$   r%   r   r   r   Úconvert_dynamic_fxT   s    r'   Nc                 C   st   | j rJ dƒ‚|r.t| ||ƒ} t| d|d�} nB|s:J dƒ‚|sFJ dƒ‚t| ||ƒ} || g|¢R Ž  t| d|d�} | S )Nz‘quantize_fx is only used for post training quantization(eval mode), for quantization aware training please use prepare_qat_fx and convert_qat_fx.T)r   r"   zGMust provide calibration function for post training static quantizationzFMust provide calibration dataset for post training static quantization)r   r    r'   r   r&   )r   r   Úrun_fnÚrun_argsr   r"   r   r   r   r   Ú_quantize_fxW   s    r*   c              	   C   s   t | |||||dd�S )a¶  Quantize the input float symbolically traced GraphModule 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 TorchScript model
        `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?)
          ...,
        ]
        # priority (in increasing order): global, object_type, module_name_regex, module_name
        # qconfig == None means fusion and quantization should be skipped for anything
        # matching the rule
        }
        `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
        `debug`: flag for producing a debug friendly model (preserve weight attribute)

    Return:
        Quantized TorchSciprt model.

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

    graph_module = torch._fx.symbolic_trace(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)

    quantized_model = quantize_fx(
        graph_module,
        {'': qconfig},
        calibrate,
        [data_loader_test])
    ```
    Fr   ©r*   )r   r   r(   r)   r   r"   r   r   r   Úquantize_static_fxl   s    Dÿr,   c                 C   s   t | |||dd�S )aû  Quantize the input float symbolically traced GraphModule model with
    post training dynamic quantization.
    Currently only qint8 quantization of torch.nn.Linear is supported.

    Args:
        `model`: input float TorchScript model
        `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and
        qconfig for that module as value, please see detailed
        descriptions in :func:`~torch.quantization.quantize_fx`
        `inplace`: carry out model transformations in-place, the original module is
        mutated
        `debug`: flag for producing a debug friendly model (preserve weight attribute)

    Return:
        Quantized TorchSciprt model.

    Example:
    ```python
    import torch
    from torch.quantization import per_channel_dynamic_qconfig
    from torch.quantization import quantize_dynmiac_fx

    graph_module = torch._fx.symbolic_trace(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)

    quantized_model = quantize_dynamic_fx(
        graph_module,
        {'': qconfig},
        calibrate,
        [data_loader_test])
    ```
    T)r   r"   r   r+   )r   r   r   r"   r   r   r   Úquantize_dynamic_fx³   s    &
ÿr-   )F)F)F)F)F)FF)FF)NNFFF)FF)FF)Zfxr   r   Z	torch._fxr   Zfx.utilsr   r   r   r   r   r   r   r    r#   r&   Zconvert_static_fxZconvert_qat_fxr'   r*   r,   r-   r   r   r   r   Ú<module>   s(   







  ÿ

G