
    ёi͋                        S SK r S SKrS SKrS SKr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
  S SKJrJrJrJr  S SKJrJr  S SKJrJr  S SKJrJr  S SKJr  S SKJrJrJr  S	S
KJ r J!r!J"r"J#r#J$r$  \" \%\RL                  SS9r'S r(S r)S r*S r+S r,S r-SS jr.S r/\   SS j5       r0   SS jr1\SS j5       r2\SS j5       r3\S 5       r4\S 5       r5g)    N)pir)ValueSetget_real_op_inputsget_real_op_outputssome_in_set)coredefault_main_program)Executorglobal_scope)dygraph_not_supportstatic_only)
get_logger)_pack_loaded_dict_pickle_loads_mac_unpack_saved_dict   )_check_args_check_vars_get_valid_program_normalize_path_prefix_safe_load_picklez&%(asctime)s-%(levelname)s: %(message)s)fmtc                 Z   / n/ nU R                  5        H  nUR                  (       d"  UR                  5       R                  5       S:X  a  UR	                  U5        MI  UR
                  (       d  M\  UR                  5       R                  5       S:X  d  M  UR	                  U5        M     X4$ )z
Get parameters and optimizer variables from program.
    Args:
        program(Program): The program to get parameters and optimizer variables.
zbuiltin.parameter
pd_op.data)	list_varsis_parameterget_defining_opnameappendpersistable)programparamsoptsvars       T/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/static/pir_io.pyget_pir_parametersr&   >   s     FD  """$))+/BBMM#___!4!4!6!;!;!=!MKK # <    c                 P   / n/ nU R                  5       R                   H  nUR                  5       S:X  d  UR                  5       S:X  a"  UR                  UR	                  5       S   5        UR                  5       S:X  d  Mc  UR                  UR                  5       5        M     X4$ )Nr   
pd_op.feedr   pd_op.fetch)global_blockopsr   r   attrsextendoperands_source)r!   feed_name_listfetch_targetsops       r%   get_pir_feed_and_fetchr3   Q   s    NM""$((779$	\(A!!"((*V"45779%  !3!3!56	 )
 ((r'   c                    [        5       R                  U 5      R                  5       nUR                  5       nUR	                  5       (       a   [
        R                  R                  5       nGOUR                  5       (       a   [
        R                  R                  5       nGOUR                  5       (       av  [
        R                  R                  R                  5       nUR                  UR                  5       5        [
        R                  R                  UR                  5       5      nGO-UR!                  5       (       a  [
        R                  R                  R                  5       nUR                  UR                  5       5        [
        R                  R#                  [
        R$                  R'                  5       R)                  S5      S   UR+                  5       5      nOt[
        R                  R                  R                  5       nUR                  UR                  5       5        [
        R                  R-                  UR/                  5       5      nUR1                  X5        g )N:r   )r   find_var
get_tensor_placeis_cpu_placepaddlebaseCPUPlaceis_cuda_pinned_placeCUDAPinnedPlaceis_xpu_placer   Place	set_placeXPUPlacexpu_device_idis_custom_placeCustomPlacedevice
get_devicesplitcustom_device_id	CUDAPlacegpu_device_idset)r   ndarraytpplaces        r%   set_varrQ   \   s   %002A	
A~~$$&	
			!	!++-	
		KK""$	AHHJ$$Q__%67	
				KK""$	AHHJ''MM$$&,,S1!4a6H6H6J
 KK""$	AHHJ%%aoo&78EE'r'   c                    [        U5       H  u  p#UR                  5       nUR                  5       S:w  d  M+  UR                  5       S:w  d  MA  [        R                  R                  S[        U5      -   UR                  UR                  [        R                  R                  R                  5       5      nUR                  U5        UR                  5       R                  U5        M     [        U5       H`  u  p#UR                  5       nUR                  5       S:w  d  M+  UR                  5       S:w  d  MA  UR                  5       R                  U5        Mb     g)z
Append feed ops to the program.
Args:
    program(Program): Specify a program you want to append fetch op.
    feed_vars(Value | list[Value]): Values should be feed.
Returns:
    modify program
r)   r   
feed_name_N)	enumerater   r   r:   _pir_opsdatastrshapedtyper;   r   r@   replace_all_uses_withmove_beforeget_parent_block	remove_op)r!   	feed_varsir$   orig_opvalues         r%   append_pir_feed_opsrb   u   s     I&%%'<<>\)glln.LOO((s1v%				  &&(	E %%e,!!#//8 ' I&%%'<<>\)glln.L$$&009 'r'   c                     [        U5       H/  u  nu  p4[        R                  R                  X4U5      nSUl        M1     g)z
Append fetch ops to the program.
Args:
    program(Program): Specify a program you want to append fetch op.
    fetch_vars(Tensor | list[Tensor]): Values returned by inference.
Returns:
    modify program
TN)rT   r:   rU   fetchr    )r!   fetch_name_var_mapsr_   r$   r   outs         r%   append_pir_fetch_opsrg      s7     $$78;Coo##Cq1 9r'   c                    [        U [        R                  R                  5      (       d  [	        S[        U 5       S35      eU R                  5       R                  nS/[        U5      -  n[        U5      n[        [        [        U5      5      5       HH  u  pg[        [        U5      U5      (       a%  [        U5       H  nUR!                  U5        M     MD  SXF'   MJ     [        [        [        U5      5      5       Ho  u  pgXF   (       a  M  [        [        U5      [        U5      5      (       a  [#        SUR%                  5        S35      eU R                  5       R'                  U5        Mq     g)a  
Prune a program according to feed_vars and target_vars.
Args:
    program(Program): Specify a program you want to prune.
    feed_vars(Tensor | list[Tensor]): Values needed by inference.
    target_vars(Tensor | list[Tensor]): Values returned by inference.
Returns
    modify program
<program type must be `paddle.static.Program`, but received ``TFzThe feed_var create by: 'zQ' is not involved in the target_vars calculationPlease remove it from feed_vars .N)
isinstancer:   staticProgram	TypeErrortyper+   r,   lenr   reversedlistrT   r   r   r   add
ValueErrorr   r]   )	r!   r^   target_vars	total_opsintersection_op_flagstarget_vars_r_   r2   operands	            r%   pir_prune_with_inputrz      s>    gv}}4455J4PW=/YZ[
 	
 $$&**I!FS^3 K(L$y345*2.==-b1  ) 2 (-!$ 6 $y345$''.r2HY4GHH /	{ ;8 9    ",,R0 6r'   c                     U(       a   U R                    HT  nUR                   HA  nUR                  S5      (       a  UR                  SS5        UR	                  5       S:X  d  MA  MC     MV     g)a6  
This method will create a new program and do following adjustments on it:
1. Remove all reader variables and their creator ops if exist.

2. Remove the :code:`read_op` if exists.

3. change the :code:`is_test`
attribute of operators to :code:`True`. All the :code:`Parameter`
information will be lost.

Args:
    prune_read_op(bool): remove the read ops that are added by py_reader
                         for cpp inference library

Notes: This API is a very low level API. Use
:code:`Program.clone(for_test=True)` instead.

Returns:
    Program: The new program.
is_testTzpd_op.batch_normN)blocksr,   has_attrset_bool_attrr   )r!   prune_read_opblockr2   s       r%   _inference_optimizer      sY    .  ))B{{9%%  D1wwy..   r'   c                    [        U [        R                  R                  5      (       d  [	        S[        U 5       S35      e[        U[        5      (       d  U/n[        S U 5       5      (       d  [	        S5      e[        U[        5      (       d  U/n[        S U 5       5      (       d  [	        S5      e[        U R                  5       R                  5      S:X  a  [        S5      eU R                  5       R                   H/  nUR                  5       S	:X  d  M  [        R                  " S
5          O   [        R                  R!                  5       nU R#                  U5      nUR                  5       nU Vs/ s H  oR%                  U5      PM     n	nU Vs/ s H  oR%                  U5      PM     n
nUR                   H*  nUR                  5       S:X  d  M  UR'                  U5        M,     UR)                  SS5      nU(       d  [+        XiU
5        [-        USS9  / n[/        U
5       H  u  pUR1                  5       nUnUR                  5       S:X  a]  UR3                  S5      R1                  5       nUR5                  S5      (       a(  UR7                  5       S   S:X  a  UR3                  S5      nUR8                  (       a  UR;                  UUR                  45        M  UR;                  US[=        U5      -   45        M     [        R                  R?                  U5         [A        Xi5        [C        Xl5        SSS5        U$ s  snf s  snf ! , (       d  f       U$ = f)a'  

Normalize/Optimize a program according to feed_vars and fetch_vars.

Args:
    program(Program): Specify a program you want to optimize.
    feed_vars(Tensor | list[Tensor]): Values needed by inference.
    fetch_vars(Tensor | list[Tensor]): Values returned by inference.
    kwargs: Supported keys including ``skip_prune_program``.
        - skip_prune_program(bool): whether to skip pruning program. Defaults to False.

Returns:
    Program: Normalized/Optimized program.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> paddle.enable_static()

        >>> path_prefix = "./infer_model"

        # User defined network, here a softmax regression example
        >>> image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32')
        >>> label = paddle.static.data(name='label', shape=[None, 1], dtype='int64')
        >>> predict = paddle.static.nn.fc(image, 10, activation='softmax')

        >>> loss = paddle.nn.functional.cross_entropy(predict, label)

        >>> exe = paddle.static.Executor(paddle.CPUPlace())
        >>> exe.run(paddle.static.default_startup_program())

        # normalize main program.
        >>> program = paddle.static.default_main_program()
        >>> normalized_program = paddle.static.normalize_program(program, [image], [predict])

ri   rj   c              3   V   #    U  H  n[        U[        R                  5      v   M!     g 7fNrk   r   Value.0vs     r%   	<genexpr>(normalize_pir_program.<locals>.<genexpr>  s     ;Az!SYY''   ')z2feed_vars type must be a Value or a list of Value.c              3   V   #    U  H  n[        U[        R                  5      v   M!     g 7fr   r   r   s     r%   r   r     s     <Az!SYY''r   z3fetch_vars type must be a Value or a list of Value.r   z=program must not be empty. at least one operator is required!z	pd_op.auczHBe sure that you have set auc states to 0 before saving inference model.r*   skip_prune_programFT)r   zpd_op.scaler   ra   g      ?fetch_name_N)"rk   r:   rl   rm   rn   ro   rr   allrp   r+   r,   rt   r   warningswarnr   	IrMappingclonelook_upr]   getrz   r   rT   r   operand_sourcer~   r-   has_namer   rW   program_guardrb   rg   )r!   r^   
fetch_varskwargsr2   	value_mapcopy_programr+   r   clone_feed_varsclone_fetch_varsr   fetch_vars_tupler_   r$   scale_oporig_varfull_ops                     r%   normalize_pir_programr      s   N gv}}4455J4PW=/YZ[
 	
 i&&K	;;;;LMMj$'' \
<<<<MNN
7!%%&!+K
 	

 ""$((779#MMZ  ) 

$$&I==+L,,.L5>?Y((+YO?6@Aj))!,jA779%""2& 
  $8%@\<LMD9,-&&(==?m+--a0@@BG((W]]_W-E-L#2215##Xx}}$=>##S-#a&*@$AB . 
	$	$\	2L:\< 
3 = @A2 
3	2 s   8MM
$M
Mc                 x   SnU c  Uc  Sn[        U5      nUc@  [        U5      u  pVXV-   n[        UU U Vs/ s H  oR                  (       d  M  UPM     snUS9$ Sn	[	        [        U5      5      S:X  a  [        R                  " S5        g0 n
U H  n[        5       R                  UR                  5      nUc  USL a{  [        R                  R                  [        R                  R                  U 5      UR                  5      n[        R                   " UR#                  5       UR                  USS5        M  UR#                  5       XR                  '   M     Uc  U(       a  / n/ n[%        U
R'                  5       5       H'  nUR)                  X   5        UR)                  U5        M)     SnUSL a=  [        R                  R                  [        R                  R                  U 5      U5      n[        R*                  " UUUSSU5        U(       a'  [        5       R                  U	5      R-                  5       $ gs  snf )	a  
Save specific variables in the `Program` to files.

There are two ways to specify the variables to be saved: set variables in
a list and assign it to the `vars`, or use the `predicate` function to select
variables that make `predicate(variable) == True`. The first way has a higher priority.

The `dirname` is used to specify the folder where to save variables.
If you prefer to save variables in separate files in the `dirname` folder,
do not set `filename`. If you prefer to save all variables in a single file,
use `filename` to specify it.

Args:
    dirname(str, optional): The folder to save variables.
                        When you need to save the parameter to the memory, set it to None.
    main_program(Program, optional): The program whose variables will be saved.
                                If it is None, the default main program will
                                be used automatically.
                                Default: None
    vars(list[Variable], optional): The list contains all variables to be saved.
                                    Default: None
    filename(str, optional): If you prefer to save all variables in a single file,
                             use `filename` to specify it. Otherwise, let `filename` be None.
                             Default: None

Returns:
    str: When saving parameters to a file, returns None.
         When saving parameters to memory, returns a binary string containing parameters.
FNT)main_programdirnamevarsfilenamesaved_paramsr   zVno variable in your model, please ensure there are any variables in your model to save )r   r&   save_vars_pirr    rp   rr   r   r   r   r6   r   ospathjoinnormpathr   	save_funcr7   sortedkeysr   save_combine_func	get_bytes)r   r   r   r   save_to_memoryparamopt	vars_listr$   params_var_namesave_var_mapr   save_file_pathsave_var_listsave_var_namesr   	save_paths                    r%   r   r   M  s   J N8+%l3L|'5
K	%!*>#oo#>	
 	
 )tDz?aMMh A.))!&&1CNe$;!#bgg.>.>w.G!PNN$affndE (+~~'7VV$  >MN|0023$$\%78%%d+ 4 I&GGLL)9)9')BHM	"" >**?;EEGG W ?s   H7H7c           
         U b  [        U [        5      (       d   eSnUb  [        R                  R	                  U5      nUS:X  a  SnUc  Uc
  [        5       n[        U[        R                  R                  5      (       d  [        S[        U5       35      e[        U5      u  pgXg-   n[        R                  R                  R                  R                  U[!        5       U R"                  5        [%        U UUU Vs/ s H  oR&                  (       d  M  UPM     snUS9  gUc
  [        5       n[        U[        R                  R                  5      (       d  [        S[        U5       35      e0 n	U H  n
[!        5       R)                  U
R*                  5      n[        U[        R                  R                  R,                  5      (       d   eUcz  Uc  [/        S5      e[        R                  R1                  XR*                  5      n[2        R4                  " US/ SUR7                  5       U R"                  R9                  5       5        M  XU
R*                  '   M     Ub  / n/ n[;        U	R=                  5       5       H5  nUR?                  X   R7                  5       5        UR?                  U5        M7     USL a  [        R                  R1                  X5      n[2        R@                  " UUUSU R"                  R9                  5       5        [C        X5       H%  u  p[E        U[F        RH                  " U5      5        M'     ggs  snf )a7  
:api_attr: PIR Static Graph

This API loads variables from files by C++ function.

There are two ways to specify the variables to be loaded: the first way, set
variables in a list and assign it to the `vars`; the second way, use the
`predicate` function to select variables that make `predicate(variable) == True`.
The first way has a higher priority.

The `dirname` is used to specify the folder where to load variables.
If variables were saved in separate files in the folder `dirname`,
set `filename` None. If all variables were saved in a single file,
use `filename` to specify it.

Args:
    executor(Executor): The executor to create variables in scope.
    dirname(str): The folder where to load the variables.
    main_program(Program, optional): The program whose variables will be loaded.
                                If it is None, the default main program will
                                be used automatically.
                                Default: None
    vars(list[Variable], optional): The list that contains all variables to be loaded.
                               Default: None
    filename(str, optional): The file which saved all required variables. If variables
                            were saved in separate files, set it to be None.
                            Default: None

Returns:
    None
NFr   z`The type of input main_program is invalid, expected type is paddle.static.Program, but received )r   r   r   r   z>The directory path and params cannot be None at the same time.)%rk   r
   r   r   r   r	   r:   rl   rm   rn   ro   r&   r;   	libpaddler   create_loaded_parameterr   _default_executorload_vars_pirr    r6   r   Variablert   r   r   	load_funcr7   	get_placer   r   r   load_combine_funcziprQ   nparray)executorr   r   r   r   vars_from_memoryr   r   r$   load_var_mapr   	file_pathload_var_listload_var_namesr   s                  r%   r   r     s   L z(H====''""7+ 2~|/1L,(=(=>>rsw  yE  tF  sG  H  (5
{!!99,.("<"<	
 	%!%9##9	
 /1L,(=(=>>rsw  yE  tF  sG  H 
 A.))!&&1Cc6;;#8#8#A#ABBBB?$X  GGLL&&9	NN$..88: (+QVV$% ( MN|0023$$\%7%B%B%DE%%d+ 4  5(77<<:""**446 !?	bhhsm, @#  G :s   ;M M c           
        ^^ [         R                  R                  U5      nUS:w  d   S5       eSU;   a  US   n[        R                  " S5        [        U[        5      (       d  [        S[        U5       35      eUS:  d  US:  a  [        SU 35      e[         R                  R                  U5      nU(       a:  [         R                  R                  U5      (       d  [         R                  " U5        S	 n[        U 5      u  pxU V	s0 s H(  oR                  (       d  M  U	R                  U" U	5      _M*     n
n	U V	s0 s H)  n	U	R                  (       d  M  U	R                  U" U	5      _M+     nn	[        X5      n
[         R"                  S
:X  a}  [         R$                  R&                  S:X  a_  [(        R*                  " XS9m[-        US-   S5       nSmUR/                  UU4S j[1        S[3        T5      T5       5       5        SSS5        O-[-        US-   S5       n[(        R4                  " XUS9  SSS5        [-        US-   S5       n[(        R4                  " XUS9  SSS5        [6        R8                  R;                  XS-   5        gs  sn	f s  sn	f ! , (       d  f       Nh= f! , (       d  f       Ny= f! , (       d  f       N]= f)a   
This function saves parameters, optimizer information and network description to model_path.

The parameters contain all the trainable Tensor, and save to a file with suffix ".pdparams".
The optimizer information contains all the Tensor used by optimizer. For Adam optimizer, contains beta1, beta2, momentum etc. All the information will be saved to a file with suffix ".pdopt". (If the optimizer has no Tensor to save (like SGD), the file will not be generated).
The network description is the description of the program. It's only used for deployment. The description will be saved to a file with a suffix ".pdmodel".

Args:
    program(Program) : The program to be saved.
    model_path(str): The file prefix to save the program. The format is "dirname/file_prefix". If file_prefix is an empty str, an exception will be raised.
    protocol(int, optional): The protocol version of pickle module must be greater than 1 and less than 5.
                             Default: 4
    configs(dict, optional) : Optional keyword arguments.

Returns:
    None
r   zThe input model_path MUST be format of dirname/filename [dirname\filename in Windows system], but received model_path is empty string.pickle_protocolzJ'pickle_protocol' is a deprecated argument. Please use 'protocol' instead.z+The 'protocol' MUST be `int`, but received       z/Expected 1<'protocol'<5, but received protocol=c                     [        5       R                  U R                  5      R                  5       n[        R
                  " U5      $ r   )r   r6   r   r7   r   r   )r$   rN   s     r%   r7   save_pir.<locals>.get_tensorR  s/    N##CHH-88:xx{r'   darwin   )protocol	.pdparamswbi   @c              3   2   >#    U  H  nTXT-    v   M     g 7fr    )r   r_   	max_bytespickle_bytess     r%   r   save_pir.<locals>.<genexpr>i  s!      ?A QY/?s   r   N.pdopt.json)r   r   basenamer   r   rk   intrt   ro   r   existsmakedirsr&   r    r   r   sysplatformversion_infomajorpickledumpsopen
writelinesrangerp   dumpr:   r   serialize_pir_program)r!   
model_pathr   configs	base_namedir_namer7   parameter_listoptimizer_param_listr$   
param_dictopt_dictfr   r   s                @@r%   save_pirr   &  sb   (   ,I?  	R? G#,-X	
 h$$9$x.9IJ
 	
 !|x!|=hZH
 	
 wwz*Hx00
H
 ,>g+F(N-;-;c!*S/!^  
 ('C?? 	"*S/!'   $J9J ||xC$4$4$:$:a$?||JB*{*D1QILL q#l"3Y?  21 *{*D1QKK
9 2 
j8#T	*aH(3 
+ KK%%gG/CD= 21 21 
+	*s<   
J
"J
?JJ3JJ%	J6
J"%
J36
Kc                 n   Ub  [        U[        5      (       d   eUS-   n[        U 5      u  pV[        US5       n[        R
                  S:X  a*  [        R                  R                  S:X  a  [        XG5      nO
[        USS9n[        U5      nSSS5        U H`  n	U	R                  (       d  M  U	R                  W;   d   SU	R                   S	U S
35       e[        U	R                  XR                     5        Mb     [        U5      S:  Ga  US-   n
[        R                   R#                  U
5      (       d   SU
 S35       eU(       aG  [$        R&                  R(                  R*                  R-                  U[/        5       UR0                  5        [        U
S5       n[        USS9nSSS5        U H`  n	U	R                  (       d  M  U	R                  W;   d   SU	R                   S	U
 S
35       e[        U	R                  XR                     5        Mb     gg! , (       d  f       GN= f! , (       d  f       N= f)a  
:api_attr: PIR Static Graph

This function gets parameters and optimizer information from program, and then gets corresponding value from file.
An exception will be thrown if shape or dtype of the parameters does not match.

This function can also load model file saved with [ save_params, save_persistables, save_vars ].
var_list can not be None when loading a single model file
( filename is not None when save_params, save_persistables or save_vars is called ).

Args:
    program(Program): The program to be loaded
    model_prefix(str): The file prefix to store the program
    executor(Executor, optional): The executor used for initializing the parameter
                                  when startup program is not run.
    var_list(list|tuple, optional): The Tensor list/tuple to load a single model file saved with
                              [ save_params, save_persistables, save_vars ].
                              Default: None

Returns:
    None
Nr   rbr   r   latin1)encodingzCan not find [z] in model file []r   r   zOptimizer file [z] not exits)rk   r
   r&   r   r   r   r   r   r   r   r   r    r   rQ   rp   r   r   r   r:   r;   r   r   r   r   r   )r!   model_prefixr   var_listparameter_file_namer   r   r   	load_dictr$   opt_file_names              r%   load_pirr	  y  s   2 z(H====&4 ,>g+F(N	!4	(A<<8#(8(8(>(>!(C)*=AI)!h?I%i0	 
) ???88y(  
*;<O;PPQR( CHHi12   1$$x/ww~~m,, 	
}o[9	
, KK!!%%==$lnh6P6P -&!)!h?I ''Cxx9, $SXXJ.?aP, )HH"56 ( % 
)	(2 '&s   AHH&
H#&
H4c           	      l   [        U 5      n  [        R                  R                  U 5      n[        R                  " U5        U S-   nU S-   n[        R                  R                  U5      (       a  [        SU S35      e[        R                  R                  U5      (       a  [        SU S35      e[        SU5        [        SU5        [        UR                  SS5      5      n	[        U	UUUR                  S	S
5      S9n	UR                  SS
5      n
UR                  SS5      n[        R                  R!                  U	UR                  SS
5      (       a=  [        R                  R#                  [        R                  R                  U5      S5      OUSU
U5        [        R                  R                  U5      n[        R                  R%                  U5      n['        UU	UR                  SS
5      (       a  SOUS9  g! [
         a*  nUR                  [        R                  :w  a  e  SnAGNSnAff = f)a  
Save current model and its parameters to given path. i.e.
Given ``path_prefix = "PATH/modelname"``, after invoking
``save_inference_model(path_prefix, feed_vars, fetch_vars, executor)``,
you will find two files named ``modelname.pdmodel`` and ``modelname.pdiparams``
under ``PATH``, which represent your model and parameters respectively.

Args:
    path_prefix(str): Directory path to save model + model name without suffix.
    feed_vars(Tensor | list[Tensor]): Variables needed by inference.
    fetch_vars(Tensor | list[Tensor]): Variables returned by inference.
    executor(Executor): The executor that saves the inference model. You can refer
                        to :ref:`api_guide_executor_en` for more details.
    kwargs: Supported keys including 'program' and "clip_extra". Attention please, kwargs is used for backward compatibility mainly.

        - program(Program): specify a program if you don't want to use default main program.

        - clip_extra(bool): the flag indicating whether to clip extra information for every operator. Default: True.

        - legacy_format(bool): whether to save inference model in legacy format. Default: False.

Returns:
    None
Nr   
.pdiparams'z' is an existing directory.r^   r   r!   r   F)r   readable	trainableTseparate_parametersz__model__.jsonr   r   r   )r   r   r   r   r   OSErrorerrnoEEXISTisdirrt   r   r   r   r   r:   r   r   r   r   r   )path_prefixr^   r   r   r   r   er   params_pathr!   r  r  save_dirnameparams_filenames                 r%   save_inference_model_pirr    s   : )5K''//+.
G
 w&J,K	ww}}Z  1ZL(CDEE	ww}}[!!1[M)DEFF Y'j) It!<=G#!::&:EB	G zz*e,H

;-I
KK%% zz/77 GGLL46FG
 77??;/Lgg&&{3O zz/77  U  77ell" #s   5G? ?
H3	H..H3c                    SnSn[         R                  " 5       R                  R                  n[	        XRX45        U c  [
        R                  S5        UR                  SS5      nUR                  SS5      nUc  [        S5      e[        R                  R                  5       n[        R                  R                  R                  Xh5        [        U5      u  pX-   nU Vs/ s H  oR                   (       d  M  UPM     nn[#        U5      S:  a  [%        USUUS	9  GO['        U 5      n [(        R*                  R-                  U 5      n[(        R*                  R/                  U5      (       d  [        S
U 35      eU(       d  U S-   nU S-   nGOQUR                  SS5      nUR                  SS5      nUc!  [(        R*                  R1                  U S5      nOe[(        R*                  R1                  XS-   5      n[(        R*                  R3                  U5      (       d  [(        R*                  R1                  X5      nUc!  [(        R*                  R1                  U S5      nOe[(        R*                  R1                  XS-   5      n[(        R*                  R3                  U5      (       d  [(        R*                  R1                  X5      n[
        R                  SU SU 35        [        R                  R                  5       n[        R                  R                  R                  X5        [        U5      u  pX-   nU Vs/ s H  oR                   (       d  M  UPM     nn[#        U5      S:  aJ  [(        R*                  R-                  U5      n[(        R*                  R5                  U5      n[%        UUUUS	9  [7        U5      u  nnUUU/$ s  snf s  snf )a  

Load inference model from a given path. By this API, you can get the model
structure(Inference Program) and model parameters.

Args:
    path_prefix(str | None): One of the following:
      - Directory path to save model + model name without suffix.
      - Set to None when reading the model from memory.
    executor(Executor): The executor to run for loading inference model.
                        See :ref:`api_guide_executor_en` for more details about it.
    kwargs: Supported keys including 'model_filename', 'params_filename'. Attention please, kwargs is used for backward compatibility mainly.

        - model_filename(str): specify model_filename if you don't want to use default name.

        - params_filename(str): specify params_filename if you don't want to use default name.

Returns:
    list: The return of this API is a list with three elements:
    (program, feed_target_names, fetch_targets). The `program` is a
    ``Program`` (refer to :ref:`api_guide_Program_en`), which is used for inference.
    The `feed_target_names` is a list of ``str``, which contains names of variables
    that need to feed data in the inference program. The `fetch_targets` is a list of
    ``Variable`` (refer to :ref:`api_guide_Program_en`). It contains variables from which
    we can get inference results.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import numpy as np

        >>> paddle.enable_static()

        # Build the model
        >>> startup_prog = paddle.static.default_startup_program()
        >>> main_prog = paddle.static.default_main_program()
        >>> with paddle.static.program_guard(main_prog, startup_prog):
        ...     image = paddle.static.data(name="img", shape=[64, 784])
        ...     w = paddle.create_parameter(shape=[784, 200], dtype='float32')
        ...     b = paddle.create_parameter(shape=[200], dtype='float32')
        ...     hidden_w = paddle.matmul(x=image, y=w)
        ...     hidden_b = paddle.add(hidden_w, b)
        >>> exe = paddle.static.Executor(paddle.CPUPlace())
        >>> exe.run(startup_prog)

        # Save the inference model
        >>> path_prefix = "./infer_model"
        >>> paddle.static.save_inference_model(path_prefix, [image], [hidden_b], exe)

        >>> [inference_program, feed_target_names, fetch_targets] = (
        ...     paddle.static.load_inference_model(path_prefix, exe))
        >>> tensor_img = np.array(np.random.random((64, 784)), dtype=np.float32)
        >>> results = exe.run(inference_program,
        ...               feed={feed_target_names[0]: tensor_img},
        ...               fetch_list=fetch_targets)

        # In this example, the inference program was saved in file
        # "./infer_model.pdmodel" and parameters were saved in file
        # " ./infer_model.pdiparams".
        # By the inference program, feed_target_names and
        # fetch_targets, we can use an executor to run the inference
        # program to get the inference result.
)model_filenamer  )pserver_endpointsNzKLoad inference model from memory is deprecated. Please specify path_prefix.r  r  z8params_filename cannot be None when path_prefix is None.r   r  zThere is no directory named r   r  	__model__r   z[The old way to load inference model is deprecated. Please specify path_prefix. model path: z, params path: )inspectcurrentframef_codeco_namer   _loggerwarningr   rt   r:   rl   rm   r;   r   deserialize_pir_programr&   r    rp   r   r   r   r   r   r  r   r   r   r3   )r  r   r   supported_argsdeprecated_argscallerr  r  r!   r"   r#   r   r$   dir_pathr   r  load_dirname
feed_namesr1   s                      r%   load_inference_model_pirr,    s   F ;N,O!!#**22F@ Y	
  $4d; **%6="J 
 --'')00I)'2}#7tt7t9q=$( -[977??;/ww}}X&&;H:FGG $w.J%4K $ZZ(8$?N$jj):DAO%WW\\+{C
WW\\+7OP
ww~~j11!#k!JJ& ggll;; ggll<!? ww~~k22"$'',,{"LKOO  *|?;-I --'')00E)'2}#7tt7t9q=77??;7L gg..{;O$$(	 !7w ?JZ//G 8l 8s    O8O9O
O
)T)NNN)r   )NN)6r  r  loggingr   r   r   r   numpyr   r:   r   paddle.autograd.backward_utilsr   r   r   r   paddle.baser   r	   paddle.base.executorr
   r   paddle.base.frameworkr   r   paddle.base.log_helperr   paddle.framework.io_utilsr   r   r   io_utilsr   r   r   r   r   __name__INFOr#  r&   r3   rQ   rb   rg   rz   r   r   r   r   r   r	  r  r,  r   r'   r%   <module>r8     s.      	  
      8 .   gll H
&)2:6"1J!HcL  		\H \HD 	v-r OE OEd @7 @7F S Sl \0 \0r'   