
    ёiiT                        S SK r S SKrS SKrS SKrS SKrSSKJrJr  SSKJ	r	  SSK
JrJrJrJrJrJrJr  \	" \\R&                  S9rSS	KJr  SS
KJr  SSK
JrJrJrJr  / SQrS/r/ SQrSS/r S/r!\"" \RF                  RI                  5       5      r%\"" \RL                  RI                  5       5      r'/ SQr(Sr)SSSSS// SQSSSSSSSSS.r*S r+S r,S r-SSSSSSSSSS0 SSSSS4S jr.S!S  jr/g)"    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                      [        [        S5       n U R                  5       n[        R                  " U5      nUsS S S 5        $ ! , (       d  f       g = f)Nr)openVARS_MAPPING_TABLEreadjsonloads)filedatas     b/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/static/quantization/quanter.py	load_dictr<   u   s7    	 #	&$yy{zz$ 
'	&	&s   (A
Ac                     [        [        S5       nUR                  [        R                  " U 5      5        S S S 5        g ! , (       d  f       g = f)Nw)r4   r5   writer7   dumps)tabler9   s     r;   	save_dictrB   |   s0    	 #	&$

4::e$% 
'	&	&s   &A  
Ac                    [         R                  " [        5      nUR                  U 5        [	        US   [
        5      (       a  [	        US   [
        5      (       d   S5       eUS   (       a  [        n[        nSnO[        n[        nSnUS   U;   d   SR                  US   XB5      5       eUS   U;   d   S	R                  US   XC5      5       e[	        US
   [        5      (       d   S5       eUS
   S:  a	  US
   S::  d   S5       e[	        US   [        5      (       d   S5       eUS   S:  a	  US   S::  d   S5       e[	        US   [        [        45      (       d   S5       e[	        US   [        5      (       d   S5       eUS   (       a
  [        US'   OTUS   (       a  [        [        -   US'   O9US    H0  nU[        ;   a  M  U[        ;   a  M   U S[        [        -    35       e   [	        US   [        5      (       d   S5       eUS   [         ;   d   SSR#                  [         5      -   5       e[	        US   [        5      (       d   S5       e[	        US   [$        5      (       d   S5       eU$ )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 listzB 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    mm12GNN;gn-t44"#T: : BAB 
 ~9A04)*l: @GG*+X	
: -.2BB CJJ./	
B gm,c22 (2 =!Q&7=+AR+G 1G g/0#66 ,6
 	!"a'G4E,F",L545L g12T3K@@ /@ g12D99 *9 ~'8#$	#	$#&AA 	#$ 23G::22 ) 22ILg2g1hj  4 gg&,,D.DD,7|+ -ACHHE . + gm,c22 h2 gm,e44 c4 N    c           
         U(       d  [         R                  R                  5       OUnUc  [        nO'[	        U[
        5      (       d   S5       e[        U5      n[        R                  SU 35        / n/ nU(       a  SO	US   (       + nUS   (       a  U(       a|  SU;  a  US   US'   U
c  [         R                  R                  5       OU
n[        UU 4SUUS	USS
.UD6nUR                  5       nUR                  n[        UR                  5       5      nGO[        [         R"                  " U R$                  5      US9n[        UR                  5       5      n/ n/ nUR'                  S5      (       a  US   R(                  nUS   R*                  nOFUS    H=  nU[,        ;   a  UR/                  U5        M   U[0        ;   d  M,  UR/                  U5        M?     [3        U5      S:  a  US   (       a  [4        O[6        nU" S(0 SU_SU_SUS   _SUS   _SUS   _SUS   _SUS   _SUS   _SU_SUS   _SU_SU_SU_SU_SU	_SU
_SU_6nU H  nUR9                  U5        M     [;        UUUS   US 9nU H  n UR9                  W5        M     [3        U5      S:  aE  US   (       a  [<        O[>        n!U!" UUUS   US   US   UUS!9n"U H  nU"R9                  U5        M     [A        UUUS   UUS"9n#U H  nU#R9                  U5        M     Uc  Uba  U(       dZ  US   (       dP  [        R                  S#5        [        R                  S$[B         S%35        U H  n[E        URF                  5        M     U(       a  URI                  S&S'5        U(       d  U(       a  URK                  5       n$O)[         R                  RM                  URN                  5      n$U(       a  U$UUU4$ U$$ ))ad  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): Function 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get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 16FMM&&(5E~&&$''>)>>''LL&vh/0d/@(A$AG !h 4289L2ML./*2*:fmm$$&%D
&
 -#9!
&
 
&
" 088:
/;;
*3356
TZZ5I
*3356
::n%%!'"**  !'!..  ""5655&--g6 ;;%,,W5	 7
 !"Q& -( ,. 
 ,  #=1 !''8 9	
 *00J)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	
 	67I6J"MN#Ii667 $ k*>"--/55j6F6FGj*kAArb   c                 t   U(       d  [         R                  R                  5       OUnUc  [        nO'[	        U[
        5      (       d   S5       e[        U5      n[        R                  SU 35        [        [        R                  " U R                  5      SS9nUS   (       ai  [        X15      nUR                  5        H  nUR                  U5        M     [!        X1US   S9nUR                  5        H  nUR                  U5        M     O[#        US9nUR                  5        H  nUR                  U5        M     [%        UUUS	   US   US
   S9n	[&        R(                  R+                  [,        5      (       a  [/        5       Ul        UR                  5        H  nU	R                  U5        M     UR3                  5       n
U
R5                  5       nUR6                   H  nUR8                  S:X  d  M  UR;                  S5      R<                  nU
R?                  U5      n/ nUR@                  RC                  5        H;  u  nnURD                  (       d  M  URG                  U5        URI                  U5        M=     U H  nURK                  U5        M     URM                  URO                  S5      5        UR                  RQ                  SU5        M     U(       a  US   (       a   S5       eU(       aE  [S        X1S9nUR                  5        H  nUR                  U5        M     UR3                  5       nU
U4$ U
$ )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 16FMM&&(5E~&&$''>)>>''LL?6(+,GLL1DAJm+E9#224I##I. 5>8I1J 
 $224I &&y1 5  8eD#224I &&y1 5 -}-"#45!'(>!?
 77>>,--09J-#224Ii( 5 !++-O #//1L88w-00I$**95FL%{{002t### 006 ''.  3 &""5) &		#/HHsL1   f]3 [4 -EG#224I##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       	  + #   XW\\
2  G   '=%= "!  * &
 x4499;  #11668   B  3 8&>9 @&
Z@ 
%Xv]rb   