U
    ,-e9                  	   @   s2  d dl Z d dlmZ d dlmZ d dlmZ ddddd	d
dddg	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ejfddZd0ddZd1dd	Zd2ddZddejdfdd Zddejfd!d"Zd3d#d
Zd4d$dZd5d%d&Zd6d'd(Zddddejfd)d*Zd7d+dZd8d,dZd9d-d.ZdS ):    N)QConfig)	QuantType)wrap_cpp_modulescript_qconfigscript_qconfig_dictfuse_conv_bn_jitprepare_jitprepare_dynamic_jitconvert_jitconvert_dynamic_jitquantize_jitquantize_dynamic_jitc                 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   c/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/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   r      s    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   r   $   s    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   r   +   s    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>>   s     z_prepare_jit.<locals>.<genexpr>4qconfig_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_typescripted_qconfig_dictr*   r   r   r   _prepare_jit;   s     

r4   r   c                 C   s   t |  tdd | D s&tdt|}| j|j}tj	
| t| |} tj	| j||||}|rx| | nt|} | S )Nc                 s   s   | ]}t |tV  qd S r   r+   r,   r   r   r   r.   O   s     z(_prepare_ondevice_jit.<locals>.<genexpr>r/   )r   r0   r1   r   r   r   Z_get_methodgraphr   r&   Z_jit_pass_inliner   Z1_jit_pass_insert_observer_method_for_ondevice_ptqr(   r   )r   r%   method_namer)   r2   r3   Zmethod_graphr*   r   r   r   _prepare_ondevice_jitM   s"    

r7   c                 C   s   t jd t| ||tjdS )Nz)quantization_api.quantize_jit.prepare_jitr2   )r   r&   r'   r4   r   STATICr   r%   r)   r   r   r   r   `   s    c                 C   s   t jd t| ||tjdS )Nz1quantization_api.quantize_jit.prepare_dynamic_jitr8   )r   r&   r'   r4   r   DYNAMICr:   r   r   r   r	   d   s    c                 C   s   t | |||tjdS Nr8   )r7   r   r;   r   r%   r6   r)   r   r   r   _prepare_ondevice_dynamic_jiti   s    r>   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.   s   s     z_convert_jit.<locals>.<genexpr>)r   evalr   r   r&   Z_jit_pass_insert_quant_dequantr0   
parameterscpuZ_jit_pass_quant_finalizer(   r   _jit_pass_constant_propagationr5   _jit_pass_dce)r   r)   debugr2   preserved_attrsr*   Zis_xpur   r   r   _convert_jitl   s"    rG   c                 C   s   t |  |tjkstd|dr,tdd| }d| }| j}tj| j|||tj}tj	|tj|}|r|| 
| nt|} | S )NzOThis API, while should work for static quant, is only tested for dynamic quant.Zobserve_z2Pass in valid method to be quantized, e.g. forwardZ	quantize_)r   r   r;   AssertionError
startswithr   r   r&   Z/_jit_pass_insert_quant_dequant_for_ondevice_ptqZ)_jit_pass_quant_finalize_for_ondevice_ptqr(   r   )r   r6   r)   rE   r2   Zobserve_method_nameZquantize_method_namer*   r   r   r   _convert_ondevice_jit   s$        rJ   c                 C   s    t jd t| ||tj|dS )Nz)quantization_api.quantize_jit.convert_jitr2   rF   )r   r&   r'   rG   r   r9   r   r)   rE   rF   r   r   r   r
      s    c                 C   s    t jd t| ||tj|dS )Nz1quantization_api.quantize_jit.convert_dynamic_jitrK   )r   r&   r'   rG   r   r;   rL   r   r   r   r      s    c                 C   s   t | |||tjdS r<   )rJ   r   r;   )r   r6   r)   rE   r   r   r   _convert_ondevice_dynamic_jit   s    rM   c                 C   s   t | |||} t| ||} | S r   )r>   rM   r=   r   r   r   #_quantize_ondevice_dynamic_jit_impl   s    rN   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;   r	   r   rH   r   r
   r   r&   rC   r5   rD   )r   r%   run_fnrun_argsr)   rE   r2   r   r   r   _quantize_jit   s    
rQ   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_jitr8   )r   r&   r'   rQ   r   r9   )r   r%   rO   rP   r)   rE   r   r   r   r      s    2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_dynamic_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)   rE   r2   )r   r&   r'   rQ   r   r;   )r   r%   r)   rE   r   r   r   r      s    &c                 C   s   t | |||dS )a	  Prepares the input float TorchScript model with
    *on-device* 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
        `method_name`: Name of the method within the model, to be prepared for quantization
        descriptions in :func:`~torch.ao.quantization.quantize_jit`
        `inplace`: carry out model transformations in-place, the original module is
        mutated

    Return:
        TorchScript model that is ready for on device quantization.
        This means that the returned
        model has:
        - Method is inlined.
        - Model has observer modules inserted in the model.
        - Model has packed params inserted in the model. However they are empty as in they dont
          contain valid quantized weights.
        - observe_<method_name> is added that observe the values to be quantized.
        - reset_observers_<method_name> to reset observers.
        - quantize_<method_name> is added to the model.
          - This method extract scale, zero points.
          - Quantizes observed weights.
          - Creates packed params from it and update the attribute of the model with the new values
            for the packed params.
          - Reset the original fp32 weights with empty tensor using SetAttr.
        - quantized_<method_name> is added to the model.
          - This method uses quantized weights and quantized linear ops instead of fp32 op.
          - This method should be used for inference post PTQ.
        - Note that all method's signatures should be the same as method_name.

        Later on device:
        - Run reset_observers_<method_name>
        - Run observe_<method_name>
        - Run quantize_<method_name>
        - Now model can be saved and loaded later.
        - Run model with quantized_<method_name>

    Example:
    ```python
    import torch
    from torch.ao.quantization import per_channel_dynamic_qconfig
    from torch.ao.quantization.quantize_jit import _quantize_ondevice_dynamic_jit

    ts_model = torch.jit.script(float_model.eval())  # or torch.jit.trace(float_model, input)
    qconfig = get_default_qconfig('fbgemm')
    quant_ready_model = _quantize_ondevice_dynamic_jit(
        ts_model,
        {'': qconfig},
        'forward',
        True)
    ```
    )r)   )rN   r=   r   r   r   _quantize_ondevice_dynamic_jit  s    9rR   )F)F)F)r   F)FFN)FFN)FF)F)FF)FF)r   F)r   Ztorch.ao.quantization.qconfigr   Z torch.ao.quantization.quant_typer   Ztorch.jit._recursiver   __all__r   r   r   r   r   r9   r4   r7   r   r	   r>   rG   rJ   r
   r   rM   rN   rQ   r   r   rR   r   r   r   r   <module>   sF   	









5
*