
    [Th
9                     |   S SK r S SKJr  S SKJr  S SKJr  / SQrS rS r	S r
S	 rSS jrS
\R                  4S jrSS
\R                  4S jrSS jrSS jr SS jrS
S
\R                  S4S jrS
S
\R                  4S jrSS jrSS jrSS jr SS jrSSS
S
\R                  4S jrSS jrSS jr SS jrg)     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                     [        U [        R                  R                  5      (       d   [	        S[        [        U 5      5      -   5      eg )Nz$input must be a script module, got: )
isinstancetorchjitScriptModule
ValueErrorstrtypemodels    Z/var/www/auris/envauris/lib/python3.13/site-packages/torch/ao/quantization/quantize_jit.py_check_is_script_moduler      s8    eUYY3344?#d5kBRRSS 5    c                 Z    U R                   R                  S5      (       d  [        S5      eg )Nforwardz0input script module does not have forward method)_c_has_methodr   r   s    r   _check_forward_methodr       s(    88	**KLL +r   c                     [        [        R                  R                  U R	                  5       5      R
                  [        R                  R                  U R                  5       5      R
                  S9$ )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#   )qconfigs    r   r   r       sQ    
 99##G$6$6$89<<yy 0144 r   c                 |    U R                  5        VVs0 s H  u  pX(       a  [        U5      OS_M     snn$ s  snnf )zrHelper function used by `prepare_jit`.
Apply `script_qconfig` for all entries in `qconfig_dict` that is
not None.
N)itemsr   )qconfig_dictkvs      r   r   r   +   s8    
 =I<N<N<PQ<PDAAA~a 4/<PQQQs    8Fc                     [         R                  R                  S5        U R                  n[         R                  R	                  U5      nU(       a  U R                  U5        U $ [        U5      n U $ )zoFuse 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   _jit_pass_fold_convbn_reconstructr   )r   inplacemodel_cs      r   r   r   3   s]     
HH  !QRhhGhh,,W5G7# L  (Lr   c                 `   [        U 5        [        U 5        [        S UR                  5        5       5      (       d  [	        S5      e[        U5      n[        X5      n [        R                  R                  U R                  SXBU5      nU(       a  U R                  U5        U $ [        U5      n U $ )Nc              3   B   #    U  H  n[        U[        5      v   M     g 7fNr   r   .0xs     r   	<genexpr>_prepare_jit.<locals>.<genexpr>G        ?+>az!S!!+>   4qconfig_dict should only contain names(str) as keys.r   )r   r    allkeysr   r   r   r   r,   _jit_pass_insert_observersr   r/   r   )r   r(   r0   
quant_typescripted_qconfig_dictr1   s         r   _prepare_jitrC   D   s    E"% ?<+<+<+>???OPP/=U,Ehh11)2ZG 7# L  (Lr   r   c                    [        U 5        [        S UR                  5        5       5      (       d  [        S5      e[	        U5      nU R
                  R                  U5      R                  n[        R                  R                  U5        [        X5      n [        R                  R                  U R
                  X%X45      nU(       a  U R                  U5        U $ [        U5      n U $ )Nc              3   B   #    U  H  n[        U[        5      v   M     g 7fr4   r5   r6   s     r   r9   (_prepare_ondevice_jit.<locals>.<genexpr>]   r;   r<   r=   )r   r>   r?   r   r   r   _get_methodgraphr   r,   _jit_pass_inliner   1_jit_pass_insert_observer_method_for_ondevice_ptqr/   r   )r   r(   method_namer0   rA   rB   method_graphr1   s           r   _prepare_ondevice_jitrM   U   s     E"?<+<+<+>???OPP/=88''4::L	HHl+U,EhhHH+gG 7# L  (Lr   c                 r    [         R                  R                  S5        [        XU[        R
                  S9$ )Nz)quantization_api.quantize_jit.prepare_jitrA   )r   r,   r-   rC   r   STATICr   r(   r0   s      r   r	   r	   m   s*    	HH  !LMWAQAQRRr   c                 r    [         R                  R                  S5        [        XU[        R
                  S9$ )Nz1quantization_api.quantize_jit.prepare_dynamic_jitrO   )r   r,   r-   rC   r   DYNAMICrQ   s      r   r
   r
   r   s*    	HH  !TUWARARSSr   c                 4    [        XX#[        R                  S9$ NrO   )rM   r   rS   r   r(   rK   r0   s       r   _prepare_ondevice_dynamic_jitrW   w   s     ![i>O>O r   c                 J   [        U 5        U R                  5         U R                  n[        R                  R                  USXU5      nU(       d\  [        S U R                  5        5       5      nU(       d  U R                  5         Uc  / n[        R                  R                  XSU5      nU(       a  U R                  U5        O[        U5      n [        R                  R                  U R                  5        [        R                  R                  U R                  5        U $ )Nr   c              3   R   #    U  H  oR                   R                  S :H  v   M     g7f)xpuN)devicer   )r7   ps     r   r9   _convert_jit.<locals>.<genexpr>   s     H5GXX]]e+5Gs   %')r   evalr   r   r,   _jit_pass_insert_quant_dequantr>   
parameterscpu_jit_pass_quant_finalizer/   r   _jit_pass_constant_propagationrH   _jit_pass_dce)r   r0   debugrA   preserved_attrsr1   is_xpus          r   _convert_jitrh      s     E"	JJLhhGhh55GJG HU5E5E5GHH IIK" O((33
 7#(	HH++EKK8	HH5;;'Lr   c                    [        U 5        U[        R                  :X  d   S5       eUR                  S5      (       a   S5       eSU-   nSU-   nU R                  n[
        R                  R                  U R                  XRU[        R                  5      n[
        R                  R                  U[        R                  U5      nU(       a  U R                  U5        U $ [        U5      n U $ )NzOThis API, while should work for static quant, is only tested for dynamic quant.observe_z2Pass in valid method to be quantized, e.g. forward	quantize_)r   r   rS   
startswithr   r   r,   /_jit_pass_insert_quant_dequant_for_ondevice_ptq)_jit_pass_quant_finalize_for_ondevice_ptqr/   r   )r   rK   r0   re   rA   observe_method_namequantize_method_namer1   s           r   _convert_ondevice_jitrq      s     E"i'''YXY'%%  <;<  %{2&4hhGhhFF%y7H7HG hh@@""$8G 7# L  (Lr   c                 v    [         R                  R                  S5        [        U UU[        R
                  US9$ )Nz)quantization_api.quantize_jit.convert_jitrA   rf   )r   r,   r-   rh   r   rP   r   r0   re   rf   s       r   r   r      s7    	HH  !LM##' r   c                 v    [         R                  R                  S5        [        U UU[        R
                  US9$ )Nz1quantization_api.quantize_jit.convert_dynamic_jitrs   )r   r,   r-   rh   r   rS   rt   s       r   r   r      s7    	HH  !TU$$' r   c                 4    [        XX#[        R                  S9$ rU   )rq   r   rS   )r   rK   r0   re   s       r   _convert_ondevice_dynamic_jitrw      s     Gy7H7H r   c                 6    [        XX#5      n [        XU5      n U $ r4   )rW   rw   rV   s       r   #_quantize_ondevice_dynamic_jit_implry      s!     *%{TE)%gFELr   c                    U[         R                  :X  a  [        XU5      n [        U SU5      n O>U(       d   S5       eU(       d   S5       e[	        XU5      n U" U /UQ76   [        U SU5      n [        R                  R                  U R                  5        [        R                  R                  U R                  5        U $ )NTzGMust provide calibration function for post training static quantizationzFMust provide calibration dataset for post training static quantization)r   rS   r
   r   r	   r   r   r,   rc   rH   rd   )r   r(   run_fnrun_argsr0   re   rA   s          r   _quantize_jitr}      s     Y&&&#EA#E47 	UT	U 	TS	TE9u x E4/	HH++EKK8	HH5;;'Lr   c           
      z    [         R                  R                  S5        [        U UUUUU[        R
                  S9$ )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_jitrO   )r   r,   r-   r}   r   rP   )r   r(   r{   r|   r0   re   s         r   r   r      s@    d 
HH  !MN## r   c                 r    [         R                  R                  S5        [        XX#[        R
                  S9$ )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)r0   re   rA   )r   r,   r-   r}   r   rS   )r   r(   r0   re   s       r   r   r   6  s2    L 
HH  !UVWiFWFW r   c                     [        XX#S9$ )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)
```
)r0   )ry   rV   s       r   _quantize_ondevice_dynamic_jitr   b  s    v /[ r   )F)r   F)FFN)FF)r   torch.ao.quantization.qconfigr    torch.ao.quantization.quant_typer   torch.jit._recursiver   __all__r   r    r   r   r   rP   rC   rM   r	   r
   rW   rh   rq   r   r   rw   ry   r}   r   r   r    r   r   <module>r      s     1 6 0
T
M
R" /4	@P@P ( 0S
T 9> )2B2BTX< !&Uy?O?O4 /4 
<;|)Z 9>=r   