Ë
    –\;j�V  ã                   óÞ  — d dl Z d dlZd dlZd dlZd dlZddl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	eej&                  ¬«      Zdd	lmZ dd
lmZ ddl
mZmZmZmZ g d¢ZdgZg d¢ZddgZ dgZ! e"ejF                  jI                  «       «      Z% e"ejL                  jI                  «       «      Z'g d¢Z(dZ)dddddgg d¢dddddddddœZ*d„ Z+d„ Z,d„ Z-ddddddddddi dddddfd„Z.d!d „Z/y)"é    Né   )ÚIrGraphÚcoreé   )Ú
get_loggeré   )ÚAddQuantDequantForResidualÚAddQuantDequantPassÚConvertToInt8PassÚOutScaleForInferencePassÚOutScaleForTrainingPassÚQuantizationFreezePassÚQuantizationTransformPass)Úlevel)Úquant_config)ÚPostTrainingQuantizationProgram)ÚAddQuantDequantForInferencePassÚAddQuantDequantPassV2ÚQuantizationTransformPassV2ÚQuantWeightPass)Úabs_maxÚchannel_wise_abs_maxÚrange_abs_maxÚmoving_average_abs_maxr   )r   r   r   r   r   Úint8)ÚmulÚconv2dÚpool2dÚdepthwise_conv2dÚelementwise_addÚ
leaky_reluz*./mapping_table_for_saving_inference_modelé   Ú
skip_quant)r   r   r   i'  gÍÌÌÌÌÌì?FT)Úweight_quantize_typeÚactivation_quantize_typeÚweight_bitsÚactivation_bitsÚnot_quant_patternÚquantize_op_typesÚdtypeÚwindow_sizeÚmoving_rateÚfor_tensorrtÚis_full_quantizeÚonnx_formatÚquant_post_firstÚscale_trainablec                  óœ   — t        t        d«      5 } | j                  «       }t        j                  |«      }|cd d d «       S # 1 sw Y   y xY w)NÚr)ÚopenÚVARS_MAPPING_TABLEÚreadÚjsonÚloads)ÚfileÚdatas     úkG:\00. PROJECTS\API\Inventory\templateJSON\kerjaOCR\Lib\site-packages\paddle/static/quantization/quanter.pyÚ	load_dictr<   u   s7   € Ü	Ô  #Ô	&¨$Ø�y‰y‹{ˆÜ�z‰z˜$ÓˆØ÷ 
'×	&Ò	&ús   ‘'AÁAc                 ó–   — t        t        d«      5 }|j                  t        j                  | «      «       d d d «       y # 1 sw Y   y xY w)NÚw)r4   r5   Úwriter7   Údumps)Útabler9   s     r;   Ú	save_dictrB   |   s0   € Ü	Ô  #Ô	&¨$Ø�
‰
”4—:‘:˜eÓ$Ô%÷ 
'×	&Ñ	&ús	   ‘%?¿Ac                 óh  — t        j                  t        «      }|j                  | «       t	        |d   t
        «      rt	        |d   t
        «      sJ d«       ‚|d   rt        }t        }d}nt        }t        }d}|d   |v sJ dj                  |d   ||«      «       ‚|d   |v sJ d	j                  |d   ||«      «       ‚t	        |d
   t        «      sJ d«       ‚|d
   dk\  r|d
   dk  sJ d«       ‚t	        |d   t        «      sJ d«       ‚|d   dk\  r|d   dk  sJ d«       ‚t	        |d   t        t        f«      sJ d«       ‚t	        |d   t        «      sJ d«       ‚|d   r
t        |d<   nS|d   rt        t        z   |d<   n=|d   D ]5  }|t        v rŒ|t        v rŒJ dj                  |t        t        z   «      «       ‚ t	        |d   t        «      sJ d«       ‚|d   t         v sJ ddj#                  t         «      z   «       ‚t	        |d   t        «      sJ d«       ‚t	        |d   t$        «      sJ d«       ‚|S )zŸ
    check if user's configs are valid.
    Args:
        user_config(dict): user's config.
    Return:
        configs(dict): final configs will be used.
    r-   r.   z8'for_tensorrt' and 'is_full_quantize' must both be bool'ÚTensorRTÚ
PaddleLiter$   z6Unknown weight_quantize_type: {}. {} only supports {} r%   z9Unknown activation_quantize_type: {}. {} only supports {}r&   zweight_bits must be int value.r   é   z'weight_bits should be between 1 and 16.r'   z"activation_bits must be int value.z+activation_bits should be between 1 and 16.r(   z%not_quant_pattern must be list or strr)   z quantize_op_types must be a listzF{} is not support,                         now support op types are {}r*   zdtype must be a str.zdtype can only be Ú r+   z^window_size must be int value, window size for 'range_abs_max' quantization, default is 10000.r,   zYmoving_rate must be float value, The decay coefficient of moving average, default is 0.9.)ÚcopyÚdeepcopyÚ_quant_config_defaultÚupdateÚ
isinstanceÚboolÚ"WEIGHT_QUANTIZATION_TYPES_TENSORRTÚ&ACTIVATION_QUANTIZATION_TYPES_TENSORRTÚWEIGHT_QUANTIZATION_TYPESÚformatÚintÚlistÚstrÚTENSORRT_OP_TYPESÚTRANSFORM_PASS_OP_TYPESÚQUANT_DEQUANT_PASS_OP_TYPESÚVALID_DTYPESÚjoinÚfloat)Úuser_configÚconfigsÚweight_typesÚactivation_typesÚplatformÚop_types         r;   Ú_parse_configsra   �   s
  € ô �m‰mÔ1Ó2€GØ‡N�N�;Ôä�g˜nÑ-¬tÔ4¼ØÐ"Ñ#¤Tô:ð BàAóBð ð
 ˆ~ÒÜ9ˆÜAÐØ‰ä0ˆÜ4ÐØˆàÐ&Ñ'¨<Ñ7ðà?×FÑFØÐ&Ñ'¨°<óóØ7ð 	Ð*Ñ+Ð/?Ñ?ðàB×IÑIØÐ*Ñ+¨XÐ7GóóØ?ô
 Ø�Ñ¤ôð (à'ó(ð ð
 	�Ñ !Ò#¨°Ñ(>À"Ò(Dð1à0ó1ØDô ØÐ!Ñ"¤Côð ,à+ó,ð ð
 	Ð!Ñ" aÒ'¨GÐ4EÑ,FÈ"Ò,Lð5à4ó5ØLô ØÐ#Ñ$¤t¬S kôð /à.ó/ð ô ØÐ#Ñ$¤dôð *à)ó*ð ð ˆ~ÒÜ'8ˆÐ#Ò$Ø	Ð#Ò	$ä#Ô&AÑAð 	Ð#Ò$ð Ð2Ô3ˆGØÔ:Ò:ØÔ2Ò2ðð5ß5;±VØÔ0Ô3NÑNó6óð ð 4ô �g˜gÑ&¬Ô,ÐDÐ.DÓDÐ,à�7Ñœ|Ñ+ð Ð-AÀCÇHÁHÜóEñ .ó Ð+ô Ø�Ñ¤ôð hàgóhð ô Ø�Ñ¤ôð càbócð ð €Nó    c           
      óþ  — |st         j                  j                  «       n|}|€t        }n"t	        |t
        «      sJ d«       ‚t        |«      }t        j                  d|› �«       g }g }|rdn|d    }|d   r{|ryd|vr|d   |d<   |
€t         j                  j                  «       n|
}t        || fd||d	|dd
œ|¤Ž}|j                  «       }|j                  }t        |j                  «       «      }�n«t        t!        j"                  | j$                  «      |¬«      }t        |j                  «       «      }g }g }d|v r$|d   r|d   j&                  }|d   j(                  }n>|d   D ]6  }|t*        v r|j-                  |«       Œ|t.        v sŒ&|j-                  |«       Œ8 t1        |«      dkD  r¡|d   rt2        nt4        } |d(i d|“d|“d|d   “d|d   “d|d   “d|d   “d|d   “d|d   “d|“d|d   “d|“d|“d|“d|“d|	“d|
“d|“Ž}|D ]  }|j7                  |«       Œ t9        |||d   |¬ «      }|D ]  } |j7                  «       Œ t1        |«      dkD  rA|d   rt:        nt<        }! |!|||d   |d   |d   ||¬!«      }"|D ]  }|"j7                  |«       Œ t?        |||d   ||¬"«      }#|D ]  }|#j7                  |«       Œ |€|�U|sS|d   sNt        j                  d#«       t        j                  d$t@        › d%�«       |D ]  }tC        |jD                  «       Œ |r|jG                  d&d'«       |s|r|jI                  «       }$n)t         j                  jK                  |jL                  «      }$|r|$|||fS |$S ))a7  Add quantization  and dequantization operators to "program"
    for quantization training or testing.
    Args:
        program(paddle.static.Program): training or testing ``program``.
        place(paddle.CPUPlace or paddle.CUDAPlace): This parameter represents
            the executor run on which device.
        config(dict, optional): configs for quantization. if None, will use default config.
            Default: None.
        scope(paddle.static.Scope): Scope records the mapping between variable names and variables,
            similar to brackets in programming languages. Usually users can use
            `paddle.static.global_scope <https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api_cn/executor_cn/global_scope_cn.html>`_.
            When ``None`` will use `paddle.static.global_scope() <https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api_cn/executor_cn/global_scope_cn.html>`_ .
            Default: ``None``.
        for_test(bool): If the 'program' parameter is a test program, this parameter should be set to ``True``.
            Otherwise, set to ``False``.Default: False
        weight_quantize_func(function): Function that defines how to quantize weight. Using this
                can quickly test if user's quantization method works or not. In this function, user should
                both define quantization function and dequantization function, that is, the function's input
                is non-quantized weight and function returns dequantized weight. If None, will use
                quantization op defined by 'weight_quantize_type'.
                Default is None.
        act_quantize_func(function): Function that defines how to quantize activation. Using this
                can quickly test if user's quantization method works or not. In this function, user should
                both define quantization and dequantization process, that is, the function's input
                is non-quantized activation and function returns dequantized activation. If None, will use
                quantization op defined by 'activation_quantize_type'.
                Default is None.
        weight_preprocess_func(function): Function that defines how to preprocess weight before quantization. Using this
                can quickly test if user's preprocess method works or not. The function's input
                is non-quantized weight and function returns processed weight to be quantized. If None, the weight will
                be quantized directly.
                Default is None.
        act_preprocess_func(function): Function that defines how to preprocess activation before quantization. Using this
                can quickly test if user's preprocess method works or not. The function's input
                is non-quantized activation and function returns processed activation to be quantized. If None, the activation will
                be quantized directly.
                Default is None.
        optimizer_func(function): Fuction return a optimizer. When 'is_test' is False and user want to use self-defined
            quantization function and preprocess function, this function must be set. Default is None.
        exe(paddle.static.Executor): If user want to use self-defined quantization function and preprocess function, exe must be set for
                initialization. Default is None.
        return_program(bool): If user want return value is a Program rather than Compiled Program, This argument should be set True.
                Default is False.
        draw_graph(bool): whether to draw graph when quantization is initialized. In order to prevent cycle,
                the ERNIE model needs to be set to True. Default is False.
        return_scale_dict(bool): If user want to return scale dict, model_type and pattern_ops, this argument should be set True.
                Default is False.
        scale_dict(dict): Use scale dict to initialize scales in program. Default is None.
        model_type(str): Model type can be 'transformer' or 'non-transformer'. If model type is transformer, patterns will be analyzed.
                Default is None.
        pattern_ops(dict): Pattern_ops contain pattern name and corresponding ops. Default is None.
    Returns:
        paddle.static.CompiledProgram | paddle.static.Program: Program with quantization and dequantization ``operators``
    úconfig must be dictzquant_aware config Tr1   r0   Úquantizable_op_typer)   Fé
   )Úfreeze_modelÚskip_tensor_listÚsame_scale_tensor_listÚ
batch_numsÚ
scale_dictÚreturn_graph©Úfor_testr   r   r/   ÚscopeÚplacer&   r'   r%   r$   r+   r,   Úskip_patternr(   Úweight_quantize_funcÚact_quantize_funcÚweight_preprocess_funcÚact_preprocess_funcÚoptimizer_funcÚexecutorÚis_test)ro   rp   Ú
quant_bitsrx   )ro   rp   r,   ry   rq   re   rx   )ro   rp   r,   rx   rk   zyWhen a preprocess_func is used in quant_aware, Need to save a mapping table to match variable names in the convert phase.zThe mapping table is saved as 'z'.z./z	graph.pdf© )'ÚpaddleÚstaticÚglobal_scoperJ   rL   Údictra   Ú_loggerÚinfoÚExecutorr   ÚquantizeÚ_scale_dictrS   Úall_sub_graphsr   r   ÚGraphÚdescÚweight_quant_operation_typesÚ activation_quant_operation_typesrV   ÚappendrW   Úlenr   r   Úapplyr	   r   r
   r   r5   rB   Úout_node_mapping_tableÚdrawÚ
to_programÚCompiledProgramÚgraph)%Úprogramrp   Úconfigro   rn   rr   rs   rt   ru   rv   rw   Úreturn_programÚcalib_configÚ
draw_graphÚreturn_scale_dictrk   Ú
model_typeÚpattern_opsrh   ri   rx   ÚexeÚpost_training_quantizationÚ
main_graphÚ
sub_graphsÚtransform_pass_opsÚquant_dequant_opsr`   Útransform_funcÚtransform_passÚ	sub_graphÚresidual_passÚsubgraphÚqdq_funcÚquant_dequant_passÚout_scale_training_passÚquant_programs%                                        r;   Úquant_awarer¨   Þ   s�  € ñV 16ŒF�M‰M×&Ñ&Ô(¸5€EØ€~Ü&‰ä˜&¤$Ô'Ð>Ð)>Ó>Ð'Ü Ó'ˆÜ‡L�LÐ& v hÐ/Ô0àÐØÐá‰d¨Ð/@Ñ(AÐ$A€GØÐ Ò!¡hØ ¨Ñ4Ø28Ð9LÑ2MˆLÐ.Ñ/Ø*2Ð*:Œf�m‰m×$Ñ$Ô&ÀˆÜ%DØØð
&
ð Ø-Ø#9ØØ!Øñ
&
ð ñ
&
Ð"ð 0×8Ñ8Ó:ˆ
Ø/×;Ñ;ˆ
Ü˜*×3Ñ3Ó5Ó6Š
äœTŸZ™Z¨¯©Ó5ÀÔIˆ
Ü˜*×3Ñ3Ó5Ó6ˆ
ØÐØÐØ˜VÑ#¨¨~Ò(>Ø!'Øñ"ç*Ñ*ð ð !'Øñ!ç.Ñ.ñ ð "Ð"5Ô6�ØÔ5Ñ5Ø&×-Ñ-¨gÕ6ØÔ ;Ò;Ø%×,Ñ,¨WÕ5ð	 7ô
 Ð!Ó" QÒ&ð ˜-Ò(õ ,ä.ð ñ
 ,ò Ùðáðð # =Ò1ðð !'Ð'8Ò 9ð	ð
 *0Ð0JÒ)Kðð &,Ð,BÒ%Cðð # =Ò1ðð # =Ò1ðñ %7ðð $Ð$7Ò8ðñ &:ðñ #4ðñ (>ðñ %8ðñ  .ðñ  "ð!ñ"  ð#ˆNó( (�	Ø×$Ñ$ YÕ/ð (ô 7ØØØ!Ð"3Ñ4Øô	ˆMó '�Ø×#Ñ# IÕ.ð 'ô Ð Ó! AÒ%ð ˜-Ò(õ &ä(ð ñ
 "*ØØØ" =Ñ1Ø!Ð"3Ñ4Ø#Ð$7Ñ8Ø$5Øô"Ðó (�	Ø"×(Ñ(¨Õ3ð (ô 6ØØØ˜=Ñ)ØØôÐó  ˆ	Ø×%Ñ% iÕ0ð  ð 
 Ð	+Ð/BÐ/NÙØ�}Ò%ä�‰ð Hô	
ô 	�‰Ð6Ô7IÐ6JÈ"ÐMÔNÛ#ˆIÜ�i×6Ñ6Õ7ð $ñ Ø�‰˜˜kÔ*á‘>Ø"×-Ñ-Ó/‰äŸ™×5Ñ5°j×6FÑ6FÓGˆáØ˜j¨*°kÐAÐAàÐrb   c                 ó  — |st         j                  j                  «       n|}|€t        }n"t	        |t
        «      sJ d«       ‚t        |«      }t        j                  d|› �«       t        t        j                  | j                  «      d¬«      }|d   rjt        ||«      }|j                  «       D ]  }|j                  |«       Œ t!        |||d   ¬«      }|j                  «       D ]  }|j                  |«       Œ n£t#        |¬«      }|j                  «       D ]  }|j                  |«       Œ t%        |||d	   |d   |d
   ¬«      }	t&        j(                  j+                  t,        «      rt/        «       |_        |j                  «       D ]  }|	j                  |«       Œ |j3                  «       }
|
j5                  «       }|j6                  D ]å  }|j8                  dk(  sŒ|j;                  d«      j<                  }|
j?                  |«      }g }|j@                  jC                  «       D ]4  \  }}|jD                  sŒ|jG                  |«       |jI                  |«       Œ6 |D ]  }|jK                  |«       Œ |jM                  |jO                  d«      «       |j                  jQ                  d|«       Œç |r|d   rJ d«       ‚|rGtS        ||¬«      }|j                  «       D ]  }|j                  |«       Œ |j3                  «       }|
|fS |
S )a�  
    convert quantized and well-trained ``program`` to final  quantized
    ``program``that can be used to  save ``inference model``.

    Args:
        program(paddle.static.Program): quantized and well-trained ``test program``.
        place(paddle.CPUPlace or paddle.CUDAPlace): This parameter represents
                the executor run on which device.
        config(dict, optional): configs for convert. if set None, will use
                default config. It must be same with config that used in
                'quant_aware'. Default is None.
        scope(paddle.static.Scope, optional):  Scope records the mapping between
                variable names and variables, similar to brackets in
                programming languages. Usually users can use
                `paddle.static.global_scope <https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api_cn/executor_cn/global_scope_cn.html>`_.
                When ``None`` will use
                `paddle.static.global_scope() <https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api_cn/executor_cn/global_scope_cn.html>`_
                . Default: ``None``.
        save_int8: Whether to return ``program`` which model parameters'
                dtype is ``int8``. This parameter can only be used to
                get model size. Default: ``False``.
    Returns:
        Tuple : freezed program which can be used for inference.
                when ``save_int8`` is False, return ``freezed_program(paddle.static.Program)``.
                when ``save_int8`` is True, return ``freezed_program(paddle.static.Program)``
                and ``freezed_program_int8(paddle.static.Program)``
    rd   zconvert config Trm   r/   r'   )ro   rp   ry   )ro   r&   r$   )ro   rp   r&   r'   r$   ÚwhileÚ	sub_blockÚXzQWhen onnx_format=True, already saved int8 weight,so you can't set save_int8=True.)ro   rp   )*r{   r|   r}   rJ   rL   r~   ra   r   r€   r   r   r…   r†   r   r„   r‹   r   r   r   ÚosÚpathÚexistsr5   r<   rŒ   rŽ   Úglobal_blockÚopsÚtypeÚattrÚidÚblockÚvarsÚitemsÚpersistableÚ_clone_variabler‰   Ú_remove_varÚextendÚinputÚ	set_inputr   )r‘   rp   r’   ro   Ú	save_int8Ú
test_graphÚquant_weight_passr¡   Úout_scale_infer_passÚfreeze_passÚfreezed_programr°   Ú_opÚ	_block_idÚ_blockÚpersistablesÚ_nameÚ_varÚconvert_int8_passÚfreezed_program_int8s                       r;   ÚconvertrÌ   ¹  sÖ  € ñ8 16ŒF�M‰M×&Ñ&Ô(¸5€Eà€~Ü&‰ä˜&¤$Ô'Ð>Ð)>Ó>Ð'Ü Ó'ˆÜ‡L�L�? 6 (Ð+Ô,ÜœŸ™ G§L¡LÓ1¸DÔA€JàˆmÒÜ+¨E°5Ó9ÐØ#×2Ñ2Ö4ˆIØ×#Ñ# IÕ.ð 5ä>Ø˜u°Ð8IÑ1Jô 
Ðð $×2Ñ2Ö4ˆIØ ×&Ñ& yÕ1ñ 5ô  8¸eÔDÐØ#×2Ñ2Ö4ˆIØ ×&Ñ& yÕ1ð 5ô -ØØØ˜}Ñ-Ø"Ð#4Ñ5Ø!'Ð(>Ñ!?ô
ˆô �7‰7�>‰>Ô,Ô-Ü09³ˆJÔ-Ø#×2Ñ2Ö4ˆIØ×Ñ˜iÕ(ð 5ð !×+Ñ+Ó-€Oð #×/Ñ/Ó1€LØ×ÔˆØ�8‰8�wÓØŸ™ Ó-×0Ñ0ˆIØ$×*Ñ*¨9Ó5ˆFØˆLØ%Ÿ{™{×0Ñ0Ö2‘��tØ×#Ó#Ø ×0Ñ0°Ô6Ø ×'Ñ'¨Õ.ð  3ó &�Ø×"Ñ" 5Õ)ð &à×Ñ §	¡	¨#£Ô/Ø�H‰H×Ñ˜s LÕ1ð  ñ 	�f˜]Ò+ð[àZó[ð ñ Ü-°EÀÔGÐØ#×2Ñ2Ö4ˆIØ×#Ñ# IÕ.ð 5à)×4Ñ4Ó6ÐØÐ 4Ð4Ð4àÐrb   )NNF)0rH   r7   Úloggingr­   r{   Úbase.frameworkr   r   Ú
log_helperr   Úquantization_passr	   r
   r   r   r   r   r   Ú__name__ÚINFOr   Ú r   rš   r   r   r   r   r   rP   rN   ÚACTIVATION_QUANTIZATION_TYPESrO   rX   rS   Ú#SUPPORT_WEIGHT_QUANTIZATION_OP_DICTÚkeysrV   Ú SUPPORT_ACT_QUANTIZATION_OP_DICTrW   rU   r5   rJ   r<   rB   ra   r¨   rÌ   rz   rb   r;   Ú<module>rØ      sU  ðó  Û Û Û 	ã ç +Ý #÷÷ ñ ñ �X W§\¡\Ô
2€å Ý G÷ó òÐ ð '=Ð%=Ð "ò!Ð ð Øð*Ð &ð
 ˆx€áØ×4Ñ4×9Ñ9Ó;óÐ ñ #Ø×1Ñ1×6Ñ6Ó8óÐ òÐ ð BÐ ð 3à 8ààà&˜â>ààààààààñ9Ð ò@ò&ò
Zð@ Ø
ØØØØØØØØØØØØØØó%Xôv]rb   