U
    di#                     @   s   d dl Z d dlmZ d dlmZ d dlmZ dd Zdd Zd	d
 Z	dd Z
d"ddZdejfddZd#ddZd$ddZddejdfddZd%ddZd&ddZddddejfddZd'ddZd(d d!ZdS ))    N)QConfig)	QuantType)wrap_cpp_modulec                 C   s&   t | tjjs"tdtt|  d S )Nz$input must be a script module, got: )
isinstancetorchjitZScriptModule
ValueErrorstrtypemodel r   F/tmp/pip-unpacked-wheel-ua33x9lu/torch/ao/quantization/quantize_jit.py_check_is_script_module   s    r   c                 C   s   | j dstdd S )Nforwardz0input script module does not have forward method)_cZ_has_methodr   r   r   r   r   _check_forward_method   s    r   c                 C   s(   t tj|  jtj|  jdS )zInstantiate the activation and weight observer modules and script
    them, these observer module instances will be deepcopied during
    prepare_jit step.
    )
activationweight)r   r   r   scriptr   r   r   )Zqconfigr   r   r   script_qconfig   s    r   c                 C   s   dd |   D S )z~Helper function used by `prepare_jit`.
    Apply `script_qconfig` for all entries in `qconfig_dict` that is
    not None.
    c                 S   s"   i | ]\}}||rt |nd qS N)r   ).0kvr   r   r   
<dictcomp>   s      z'script_qconfig_dict.<locals>.<dictcomp>)items)qconfig_dictr   r   r   script_qconfig_dict   s    r   Fc                 C   s:   t jd | j}t j|}|r.| | nt|} | S )z Fuse conv - bn module
    Works for eval model only.

    Args:
        model: TorchScript model from scripting or tracing
    z.quantization_api.quantize_jit.fuse_conv_bn_jit)r   _C_log_api_usage_oncer   Z_jit_pass_fold_convbn_reconstructr   )r   inplacemodel_cr   r   r   fuse_conv_bn_jit   s    r$   c                 C   sr   t |  t|  tdd | D s.tdt|}t| |} tj	| j
d|||}|rf| | nt|} | S )Nc                 s   s   | ]}t |tV  qd S r   )r   r	   )r   xr   r   r   	<genexpr>2   s     z_prepare_jit.<locals>.<genexpr>z4qconfig_dict should only contain names(str) as keys.r   )r   r   allkeysr   r   r$   r   r   Z_jit_pass_insert_observersr   r!   r   )r   r   r"   
quant_typeZscripted_qconfig_dictr#   r   r   r   _prepare_jit/   s     

r*   c                 C   s   t jd t| ||tjdS )Nz)quantization_api.quantize_jit.prepare_jitr)   )r   r   r    r*   r   STATICr   r   r"   r   r   r   prepare_jitA   s    r.   c                 C   s   t jd t| ||tjdS )Nz1quantization_api.quantize_jit.prepare_dynamic_jitr+   )r   r   r    r*   r   DYNAMICr-   r   r   r   prepare_dynamic_jitE   s    r0   c                 C   s   t |  |   | j}tj|d|||}|sltdd |  D }|sP|   |d kr\g }tj	|||}|r|| 
| nt|} tj| j tj| j | S )Nr   c                 s   s   | ]}|j jd kV  qdS )ZxpuN)Zdevicer
   )r   pr   r   r   r&   P   s     z_convert_jit.<locals>.<genexpr>)r   evalr   r   r   Z_jit_pass_insert_quant_dequantr'   
parameterscpuZ_jit_pass_quant_finalizer!   r   _jit_pass_constant_propagationgraph_jit_pass_dce)r   r"   debugr)   preserved_attrsr#   Zis_xpur   r   r   _convert_jitI   s"    r:   c                 C   s    t jd t| ||tj|dS )Nz)quantization_api.quantize_jit.convert_jitr)   r9   )r   r   r    r:   r   r,   r   r"   r8   r9   r   r   r   convert_jit`   s    r=   c                 C   s    t jd t| ||tj|dS )Nz1quantization_api.quantize_jit.convert_dynamic_jitr;   )r   r   r    r:   r   r/   r<   r   r   r   convert_dynamic_jitd   s    r>   c                 C   s   |t jkr$t| ||} t| d|} n>|s0td|s<tdt| ||} || f|  t| d|} tj	| j
 tj| j
 | S )NTzGMust provide calibration function for post training static quantizationzFMust provide calibration dataset for post training static quantization)r   r/   r0   r>   AssertionErrorr.   r=   r   r   r5   r6   r7   )r   r   run_fnrun_argsr"   r8   r)   r   r   r   _quantize_jith   s    
rB   c              	   C   s$   t jd t| |||||tjdS )a  Quantize the input float TorchScript 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 names of sub modules as key and
        qconfig for that module as value, empty key means the qconfig will be applied
        to whole model unless it's overwritten by more specific configurations, the
        qconfig for each module is either found in the dictionary or fallback to
         the qconfig of parent module.

        Right now qconfig_dict is the only way to configure how the model is quantized,
        and it is done in the granularity of module, that is, we only support one type
        of qconfig for each torch.nn.Module, and the qconfig for sub module will
        override the qconfig for parent module, empty string means global configuration.
        `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.ao.quantization import get_default_qconfig
    from torch.ao.quantization import quantize_jit

    ts_model = torch.jit.script(float_model.eval())  # or torch.jit.trace(float_model, input)
    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_jit(
        ts_model,
        {'': qconfig},
        calibrate,
        [data_loader_test])
    ```
    z*quantization_api.quantize_jit.quantize_jitr+   )r   r   r    rB   r   r,   )r   r   r@   rA   r"   r8   r   r   r   quantize_jity   s    2rC   c                 C   s    t jd t| |||tjdS )a  Quantize the input float TorchScript 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.ao.quantization.quantize_jit`
        `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.ao.quantization import per_channel_dynamic_qconfig
    from torch.ao.quantization import quantize_dynmiac_jit

    ts_model = torch.jit.script(float_model.eval())  # or torch.jit.trace(float_model, input)
    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_jit(
        ts_model,
        {'': qconfig},
        calibrate,
        [data_loader_test])
    ```
    z2quantization_api.quantize_jit.quantize_dynamic_jit)r"   r8   r)   )r   r   r    rB   r   r/   )r   r   r"   r8   r   r   r   quantize_dynamic_jit   s    &rD   )F)F)F)FFN)FFN)FF)FF)r   Ztorch.ao.quantization.qconfigr   Z torch.ao.quantization.quant_typer   Ztorch.jit._recursiver   r   r   r   r   r$   r,   r*   r.   r0   r:   r=   r>   rB   rC   rD   r   r   r   r   <module>   s&   	






5