
    ёi5                      S SK J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
JrJrJr  S SKrS SKrS SKJrJrJrJrJr  S SKJrJr  S SKJrJrJr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)J*r*  S	S
K+J,r,J-r-J.r.J/r/J0r0  S	SK1J2r2J3r3J4r4J5r5J6r6J7r7J8r8J9r9  \
(       a^  S SK:J;r;J<r<  S SK=J	r>  S SK?J@r@JArA  S SKJBrB   " S S\5      rC " S S\5      rD " S S\5      rE " S S\5      rF " S S\5      rG " S S\5      rH/ rI\!" \J\R                  SS9rLS rM S4       S5S jjrN S6       S7S jjrO          S8S  jrP\        S9S! j5       rQS:S;S" jjrR\          S<S# j5       rSS=S$ jrTS>S% jrU\            S?S& j5       rV\S@S' j5       rW\        SAS( j5       rXSBS) jrY\        SCS* j5       rZ\\    SD             SES+ jj5       5       r[\\    SD             SFS, jj5       5       r[\    SGS- j5       r[    SG             SHS. jjr\\ SI         SJS/ jj5       r]\  SK         SLS0 jj5       r^\      SMS1 j5       r_\SNS2 j5       r` SO     SPS3 jjrag)Q    )annotationsN)TYPE_CHECKINGAny	TypedDictoverload)ProgramVariablecoredefault_main_programunique_name)Executorglobal_scope)	Parameterdygraph_not_supportin_pir_modeprocess_type_promotionstatic_only)
get_logger)_clone_var_in_block__load_program_scope_pack_loaded_dict_pickle_loads_mac_unpack_saved_dictis_belong_to_optimizeris_parameteris_persistable   )_check_args_check_vars_get_valid_program_normalize_path_prefix_safe_load_pickle)get_pir_parametersload_inference_model_pirload_pirload_vars_pirnormalize_pir_programsave_inference_model_pirsave_pirsave_vars_pir)CallableSequence)NotRequiredUnpack)Tensorc                       \ rS rSr% S\S'   Srg)_NormalizeProgramKwargsQ   NotRequired[bool]skip_prune_program N__name__
__module____qualname____firstlineno____annotations____static_attributes__r5       P/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/static/io.pyr1   r1   Q   s    --r=   r1   c                  *    \ rS rSr% S\S'   S\S'   Srg)_SerializeProgramKwargsT   NotRequired[Program]programr3   legacy_formatr5   Nr6   r5   r=   r>   r@   r@   T   s    %%((r=   r@   c                       \ rS rSr% S\S'   Srg)_SerializePersistablesKwargsX   rB   rC   r5   Nr6   r5   r=   r>   rF   rF   X   s    %%r=   rF   c                  4    \ rS rSr% S\S'   S\S'   S\S'   Srg)	_SaveInferenceModelKwargs[   rB   rC   r3   
clip_extrarD   r5   Nr6   r5   r=   r>   rI   rI   [   s    %%%%((r=   rI   c                  *    \ rS rSr% S\S'   S\S'   Srg)_LoadInferenceModelKwargs`   zNotRequired[str]model_filenameparams_filenamer5   Nr6   r5   r=   r>   rM   rM   `   s    (())r=   rM   c                       \ rS rSr% S\S'   Srg)_SaveKwargsd   zNotRequired[int]pickle_protocolr5   Nr6   r5   r=   r>   rR   rR   d   s    ))r=   rR   z&%(asctime)s-%(levelname)s: %(message)s)fmtc           	        [        U[        5      (       d   eUR                  R                  5       [        R
                  R                  R                  :X  aF  U R                  UR                  UR                  UR                  UR                  UR                  SS9$ U R                  UR                  UR                  UR                  UR                  SS9$ )NTnameshapedtypetype	lod_levelpersistable)rX   rY   rZ   r[   r]   )
isinstancer	   descr[   r
   VarDescVarTypeDENSE_TENSOR
create_varrX   rY   rZ   r\   blockvars     r>   _clone_var_in_blockrg   o   s    c8$$$$
xx}}$,,..;;;))))mm   
 	
 ))))   
 	
r=   c                   [        U5      S:X  a  g U R                  5       nUR                  U[        R                  R
                  R                  SS9n[        U5       H^  u  pVUR                  U5      (       d  [        SU SU SU SU S3	5      eUR                  U5      nUR                  S	S
U/0SU/0SU0S9  M`     g )Nr   TrX   r[   r]   zThe feeded_var_names[z]: 'zC' doesn't exist in pruned inference program. Please check whether 'zC' is a valid feed_var name, or remove it from feeded_var_names if 'z1' is not involved in the target_vars calculation.feedXOutcolr[   inputsoutputsattrs)lenglobal_blockrc   r
   r`   ra   FEED_MINIBATCH	enumeratehas_var
ValueErrorrf   _prepend_op)inference_programfeed_target_namesfeed_holder_namers   feed_varirX   outs           r>   prepend_feed_opsr      s    
 "$113L&&\\!!00 ' H ./##D))'s$tf 5))- /fMO 
 t$  ($SEN!*	 	! 	
 0r=   c                    U R                  5       nUR                  U[        R                  R                  R
                  SS9n[        U5       H  u  pVUR                  SSU/0SU/0SU0S9  M!     g )NTri   fetchrk   rl   rm   rn   )rs   rc   r
   r`   ra   
FETCH_LISTru   	append_op)ry   fetch_target_namesfetch_holder_namers   	fetch_varr}   rX   s          r>   append_fetch_opsr      s    
 %113L''\\!!,, ( I /0$=YK(!*	 	 	
 1r=   c                   [        5       (       a  [        XU40 UD6$ [        U [        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[        R                  R                  5       nUR                  US	5        UR
                  S
:X  d  ME  [         R"                  " S5          O   U R%                  5       nUR                  5       n/ n['        UR                  5       H  u  pUR(                  R+                  S5        UR
                  S:X  d  UR
                  S:X  a  UR-                  U	5        UR
                  S:X  d  Mc  UR/                  S5      n
[        U
5      S:  d  M  U
S   nUR0                  R3                  U5        / nU
SS  H#  nUR-                  UR5                  U5      5        M%     UR7                  SU5        M     USSS2    H  nUR9                  U5        M     UR(                  R;                  5         U Vs/ s H  oR<                  PM     nnUR?                  SS5      nU(       d  URA                  UUS9nURC                  SS9nU Vs/ s H  oR<                  PM     nn[E        UU5        [G        UU5        UR(                  RI                  5         U$ s  snf s  sn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]): Variables needed by inference.
    fetch_vars(Tensor | list[Tensor]): Variables 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])

3program type must be `base.Program`, but received ``c              3  B   #    U  H  n[        U[        5      v   M     g 7fNr^   r	   .0vs     r>   	<genexpr>$normalize_program.<locals>.<genexpr>   s     :	1z!X&&	   z8feed_vars type must be a Variable or a list of Variable.c              3  B   #    U  H  n[        U[        5      v   M     g 7fr   r   r   s     r>   r   r      s     ;
1z!X&&
r   z9fetch_vars type must be a Variable or a list of Variable.r   z=program must not be empty. at least one operator is required! auczHBe sure that you have set auc states to 0 before saving inference model.Frj   r   pylayerblocksr   Nr4   )feeded_var_namestargetsT)prune_read_op)%r   r'   r^   r   	TypeErrorr[   listallrr   rs   opsrw   r
   op_proto_and_checker_makerkOpDeviceAttrName	_set_attrwarningswarncloneru   r_   set_is_targetappend_blocks_attr_idsr   popre   _update_desc_attr
_remove_opflushrX   get_prune_with_input_inference_optimizer   r   _set_version)rC   	feed_vars
fetch_varskwargsopdevice_attr_namecopy_programrs   remove_op_idxr}   sub_blocks_idsbackward_block_idreserved_blocksblock_ididxrf   feed_var_namesr4   fetch_var_namess                      r>   normalize_programr      s   X }}$WNvNNgw''A$w-PQR
 	
 i&&K	:	:::F
 	
 j$'' \
;
;;;G
 	
 7!%%&!+K
 	

 ""$((::LLN
%r*77eMMZ  ) ==?L,,.LM<++,
e$77f7 2  #77i00:N>"Q&$22$6!##''(9:"$ .s 3H#**<+=+=h+GH !4$$X?! -$ TrT"$ #*34)3hh)N4$8%@#55+Z 6 
  33$3GL+56:Cxx:O6\>2\?3""$ 5 7s   M%M*c                    [        SU 5        [        SU5        [        UR                  SS5      5      n[        X0U5      nUR                  SS5      n[	        X4S9$ )a  

Serialize default main program according to feed_vars and fetch_vars.

Args:
    feed_vars(Tensor | list[Tensor]): Tensor needed by inference.
    fetch_vars(Tensor | list[Tensor]): Tensor returned by inference.
    kwargs: Supported keys including ``program``. Attention please, kwargs is used for backward compatibility mainly.

        - program(Program): specify a program if you don't want to use default main program.
        - legacy_format(bool): whether to save inference program in legacy format. Defaults to False.

Returns:
    bytes: serialized 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())

        # serialize the default main program to bytes.
        >>> serialized_program = paddle.static.serialize_program([image], [predict])

        # deserialize bytes to program
        >>> deserialized_program = paddle.static.deserialize_program(serialized_program)

r   r   rC   NrD   FrD   )r   r    r   r   _serialize_program)r   r   r   rC   rD   s        r>   serialize_programr   0  sU    ^ Y'j) It!<=GJ?GJJ6MgCCr=   c                4    U R                   R                  US9$ )z#
serialize given program to bytes.
r   )r_   serialize_to_string)rC   rD   s     r>   r   r   i  s     <<++-+HHr=   c                    [        SU 5        [        SU5        [        UR                  SS5      5      n[        X@U5      n[	        XB5      $ )a  

Serialize parameters using given executor and default main program according to feed_vars and fetch_vars.

Args:
    feed_vars(Tensor | list[Tensor]): Tensor needed by inference.
    fetch_vars(Tensor | list[Tensor]): Tensor returned by inference.
    kwargs: Supported keys including ``program``. Attention please, kwargs is used for backward compatibility mainly.

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

Returns:
    bytes: serialized 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())

        # serialize parameters to bytes.
        >>> serialized_params = paddle.static.serialize_persistables([image], [predict], exe)

        # deserialize bytes to parameters.
        >>> main_program = paddle.static.default_main_program()
        >>> deserialized_params = paddle.static.deserialize_persistables(main_program, serialized_params, exe)

r   r   rC   N)r   r    r   r   _serialize_persistables)r   r   executorr   rC   s        r>   serialize_persistablesr   p  sE    ` Y'j) It!<=GJ?G"755r=   c                r   [        [        [        U R                  5       5      5      n[	        U5      S:X  a  [
        R                  " S5        g[        5       nUR                  5       n0 nU HP  nUR                  [        R                  R                  R                  :w  d  M7  [        XF5      nXeUR                  '   MR     / n[!        UR#                  5       5       H  n	UR%                  XY   5        M     [&        R(                  " S5      n
UR+                  [        R                  R                  R                  U
S9nUR,                  R/                  S5        UR1                  SSU0S	U0S
SS.S9  UR3                  5         UR5                  U5        [7        5       R9                  U
5      R;                  5       $ )z8
Serialize parameters using given program and executor.
r   Vno variable in your model, please ensure there are any variables in your model to saveNout_varr[   rX   Tsave_combinerk   Yr   	file_pathsave_to_memoryrn   )r   filterr   	list_varsrr   r   r   r   rs   r[   r
   r`   ra   RAWrg   rX   sortedkeysr   r   generaterc   r_   set_persistabler   _sync_with_cpprunr   find_var	get_bytes)rC   r   vars_save_program
save_blocksave_var_maprf   var_copyin_varsrX   out_var_namer   s               r>   r   r     su    (9(9(;<=E
5zQ.	
 9L**,JL88t||++///*:;H*-'  G|((*+|)* , ''	2L##\\!!%%L $ G LL  &W~g$7	   !LL>""<0::<<r=   c                    [        U[        5      (       d  [        S5      e[        U S5       nUR	                  U5        SSS5        g! , (       d  f       g= f)u:  
Save content to given path.

Args:
    path(str): Path to write content to.
    content(bytes): Content to write.

Returns:
    None

Examples:
    .. code-block:: python

        >>> import paddle
        >>> paddle.enable_static()
        >>> path_prefix = "./infer_model"

        # 用户自定义网络，此处用 softmax 回归为例。
        >>> 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())

        # 序列化参数
        >>> serialized_params = paddle.static.serialize_persistables([image], [predict], exe)

        # 将序列化之后的参数保存到文件
        >>> params_path = path_prefix + ".params"
        >>> paddle.static.save_to_file(params_path, serialized_params)
z'content' type should be bytes.wbN)r^   bytesrw   openwrite)pathcontentfs      r>   save_to_filer     sB    D gu%%:;;	dD	Q	 
		s   A
Ac           
        [        5       (       a  [        XX#40 UD6  g[        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	5      n	UR                  S	S
5      n
[!        U	UUUR                  SS5      S9n	UR                  SS5      n[#        U	R%                  U
S9US9n['        UR                  SS5      (       a=  [        R                  R)                  [        R                  R                  U5      S5      OUU5        [+        [-        [.        U	R1                  5       5      5      n[3        [+        U5      5      S:X  a  [4        R6                  " S5        [3        U5      S:  ai  [        R                  R                  U5      n[        R                  R9                  U5      n[;        UUU	[.        UR                  SS5      (       a  SOUS9  gg! [         a*  nUR                  [        R                  :w  a  e  SnAGNbSnAff = f)aa	  
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

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())

        # Feed data and train process

        # Save inference model. Note we don't save label and loss in this example
        >>> paddle.static.save_inference_model(path_prefix, [image], [predict], exe)

        # In this example, the save_inference_mode inference will prune the default
        # main program according to the network's input node (img) and output node(predict).
        # The pruned inference program is going to be saved in file "./infer_model.pdmodel"
        # and parameters are going to be saved in file "./infer_model.pdiparams".

N.pdmodel
.pdiparams'z' is an existing directory.r   r   rC   rK   Tr4   F)r4   rD   )rK   r   separate_parameters	__model__r   r   dirnamemain_program	predicatefilename)r   r(   r!   osr   r   makedirsOSErrorerrnoEEXISTisdirrw   r   r    r   r   r   r   _remove_training_infor   joinr   r   r   r   rr   r   r   basename	save_vars)path_prefixr   r   r   r   r   e
model_pathparams_pathrC   rK   rD   program_bytesvarssave_dirnamerP   s                   r>   save_inference_modelr     si   ~ }} J	
<B	
 	 )5K''//+.
G
 z)J,K	ww}}Z  1ZL(CDEE	ww}}[!!1[M)DEFF Y'j) It!<=G %W-GL$/J  !::&:EB	G JJ6M&%%%<#M
  zz/77 GGLL4kB ~w'8'8':;<D
4:!d	
 4y1}ww{3''**;7  $ ::3U;; $
	
 i  77ell" #s   5J 
KKKc                    [         R                  " U 5      n[        R                  " UR	                  5       5      (       d  [        SUR	                  5        S35      eU$ )a  

Deserialize given data to a program.

Args:
    data(bytes): serialized program.

Returns:
    Program: deserialized 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())

        # serialize the default main program to bytes.
        >>> serialized_program = paddle.static.serialize_program([image], [predict])

        # deserialize bytes to program
        >>> deserialized_program = paddle.static.deserialize_program(serialized_program)

zUnsupported program version: 
)r   parse_from_stringr
   _is_program_version_supported_versionrw   )datarC   s     r>   deserialize_programr    sS    L ''-G--g.>.>.@AA89I9I9K8LBOPPNr=   c           
        [        U [        5      (       d  [        S[        U 5       S35      e[        5       nUR	                  5       n[        [        [        U R                  5       5      5      n0 n0 n/ n/ n	U GH  n
[        U
[        5      (       d   eU
R                  [        R                  R                  R                  :X  a  MO  [        U
[        5      (       a/  [        U
R                   R#                  5       5      XjR$                  '   U
R                  [        R                  R                  R&                  :X  a  U	R)                  U
5        M  [+        XJ5      nUR)                  U
5        XUR$                  '   GM     Uc  [-        U5      S:X  d   S5       eg/ n[/        UR1                  5       5       H  nUR)                  X}   5        M     UR3                  S0 SU0USS	.S
9  UR5                  U5        U H  n
[        U
[        5      (       d  M  [6        R8                  R;                  5       R=                  U
R$                  5      nUc   SU
R$                  -   5       e[>        R@                  " URC                  5       5      RD                  nU
R$                  U;   d   U
R$                  S-   5       eURG                  U
R$                  5      nUU:w  d  M  [I        SU SU
R$                   SU S35      e   g)a#  

Deserialize given data to parameters according to given program and executor.

Args:
    program(Program): program that contains parameter names (to deserialize).
    data(bytes): serialized parameters.
    executor(Executor): executor used to run load op.

Returns:
    Program: deserialized 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())

        # serialize parameters to bytes.
        >>> serialized_params = paddle.static.serialize_persistables([image], [predict], exe)

        # deserialize bytes to parameters.
        >>> main_program = paddle.static.default_main_program()
        >>> deserialized_params = paddle.static.deserialize_persistables(main_program, serialized_params, exe)


r   r   Nr   z]Required 'data' shall be not None if program contains parameter, but received 'data' is None.load_combinerl   Tr   model_from_memoryrn   can't not find var: z MUST in var list.z6Shape mismatch, program needs a parameter with shape (z), but the loaded parameter ('z') has a shape of ().)%r^   r   r   r[   rs   r   r   r   r   r	   r
   r`   ra   r   r   tupler_   	get_shaperX   SELECTED_ROWSr   rg   rr   r   r   r   r   paddlebaser   r   nparray
get_tensorrY   r   RuntimeError)rC   r  r   load_program
load_blockr   origin_shape_mapload_var_map
check_varssparse_varsrf   r   load_var_listrX   var_tmp	new_shapeorigin_shapes                    r>   deserialize_persistablesr,    s   X gw''A$w-PQR
 	
 9L**,J(9(9(;<=ELJK#x((((88t||++///c9%%).sxx/A/A/C)DXX&88t||++999s#&z7#&.X]]#  |#$) 	
k	
) 	 M|((*+\/0 ,& t<   LL#y))++**,55chh?"E$:SXX$EE"XXg0023::	xx++LSXX8L-LL+'++CHH5$H W..1hhZ7J9+UWY  r=   c                t    [        U S5       nUR                  5       nSSS5        U$ ! , (       d  f       W$ = f)u  
Load file in binary mode.

Args:
    path(str): Path of an existed file.

Returns:
    bytes: Content of file.

Examples:

    .. code-block:: python

        >>> import paddle
        >>> paddle.enable_static()
        >>> path_prefix = "./infer_model"

        # 用户自定义网络，此处用 softmax 回归为例。
        >>> 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())

        # 序列化参数
        >>> serialized_params = paddle.static.serialize_persistables([image], [predict], exe)

        # 将序列化之后的参数保存到文件
        >>> params_path = path_prefix + ".params"
        >>> paddle.static.save_to_file(params_path, serialized_params)

        # 从文件加载序列化之后的参数
        >>> serialized_params_copy = paddle.static.load_from_file(params_path)
rbN)r   read)r   r   r  s      r>   load_from_filer0  $  s4    H 
dD	Qvvx 
K 
	Ks   (
7c           	     X   [        5       (       a  [        X40 UD6$ 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Un[        U5      n	[        U	5      n	[        [        [        U	R!                  5       5      5      n
[#        U
5      S:  a  [%        USU	[        US	9  GOf['        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        [5        U5      n[        U5      n	[        U	5      n	[        [        [        U	R!                  5       5      5      n
[#        U
5      S:  aO  [(        R*                  R-                  U5      n[(        R*                  R7                  U5      n[%        UUU	[        US	9  U	R8                  R;                  5       n[<        R>                  RA                  5       (       Ga  [<        RB                  RE                  5          [<        RF                  RI                  U	R8                  5      n	U	RK                  5       n/ n/ nURL                   H  nURO                  5       S:X  d  M  URQ                  5       S   nURS                  S5      nU   [<        RT                  RW                  UURX                  URZ                  S9nUR]                  U5        UR_                  5       Ra                  U5        SSS5        URc                  U5        M     U H  nURe                  U5        M     URL                   H9  nURO                  5       S:X  d  M  URc                  URg                  S5      5        M;     SSS5        OIU	R8                  Ri                  5       nU Vs/ s H"  nU	RK                  5       Rk                  U5      PM$     nnXW/$ ! , (       d  f       N= f! , (       d  f       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.
)rO   rP   )pserver_endpointsNzKLoad inference model from memory is deprecated. Please specify path_prefix.rO   rP   z8params_filename cannot be None when path_prefix is None.r   r   zThere is no directory named r   r   r   r   z[The old way to load inference model is deprecated. Please specify path_prefix. model path: z, params path: z
pd_op.feedrX   )rX   rY   rZ   zpd_op.fetch)6r   r$   inspectcurrentframef_codeco_namer   _loggerwarningr   rw   r  r   r   r   r   r   rr   	load_varsr!   r   r   r   r   r  existsr0  r  r_   get_feed_target_namesr  	frameworkin_pir_executor_mode	pir_utilsIrGuardpirtranslate_to_pirrs   r   rX   rq   resultstaticr  rY   rZ   replace_all_uses_withget_defining_opmove_beforer   	remove_opoperand_sourceget_fetch_target_namesrf   )r  r   r   supported_argsdeprecated_argscallerrO   rP   r  rC   r	  dir_pathr  r  load_dirnamerz   re   remove_op_listfetch_targetsr   var_name	org_valuevaluer   rX   s                            r>   load_inference_modelrT  M  s   L }}'HHH:N,O!!#**22F@ Y	
  $4d; **%6="J  '%m4 )1F>7+<+<+>?@t9q=$(( -[977??;/ww}}X&&;H:FGG $z1J%4K $ZZ(8$?N$jj):DAO%WW\\+{C
WW\\*!<
 ww~~j11!#k!JJ& ggll;; ggll<!? ww~~k22"$'',,{"LKOO  *|?;-I
 'z2 &m4 )1F>7+<+<+>?@t9q=77??;7L gg..{;O$$((  ::<,,..%%'jj11',,?G((*ENMii779,!xxz&1H "		!I & 2 2!)"+//"+// !3 !
 "77>--/;;B?  #))"-   %# %ii779-!(():):1)=>  ) ('2 %\\@@B9K
9KG  "&&t,9K 	 
 66)  ('4
s9   AV%&VA$V/AV$V)V'
VV
V$c                    g r   r5   r   r   r   r	  r   r   s         r>   r  r    s     r=   c                    g r   r5   rV  s         r>   r  r  !  s     r=   c                   [        5       (       a  [        XX55      $ SnUc  Uc  Sn[        U5      nUc-  [        U UU[	        [        XBR                  5       5      5      US9$ Sn[        [	        U5      5      S:X  a  [        R                  " S5        g[        5       nUR                  5       n	0 n
U H  nUR                  [        R                  R                  R                   :X  a  M7  [#        X5      nUc  USL a}  [$        R&                  R)                  [$        R&                  R+                  U5      UR,                  5      nU	R/                  SS	U/00 S
[$        R&                  R+                  U5      0S9  M  XUR,                  '   M     Uc  U(       a  / n[1        U
R3                  5       5       H  nUR5                  X   5        M     SnUSL a=  [$        R&                  R)                  [$        R&                  R+                  U5      U5      nU	R7                  [        R                  R                  R                   US9nUR8                  R;                  S5        U	R/                  SS	U0SU0UUS.S9  UR=                  5         U R?                  5         U RA                  U5        U(       a'  [C        5       RE                  U5      RG                  5       $ g)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:
    executor(Executor): The executor to run for saving variables.
    dirname(str, optional): The folder where 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
    predicate(function, optional): The function selects the variables that make
                                   `predicate(variable) == True`.
                                   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.

Raises:
    TypeError: If `main_program` is not an instance of Program nor None.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()
        >>> main_prog = static.Program()
        >>> startup_prog = static.Program()
        >>> with static.program_guard(main_prog, startup_prog):
        ...     data = paddle.static.data(name="img", shape=[64, 784])
        ...     w = paddle.create_parameter(shape=[784, 200], dtype='float32', name='fc_w')
        ...     b = paddle.create_parameter(shape=[200], dtype='float32', name='fc_b')
        ...     hidden_w = paddle.matmul(x=data, y=w)
        ...     hidden_b = paddle.add(hidden_w, b)
        >>> place = static.CPUPlace()
        >>> exe = static.Executor(place)
        >>> exe.run(startup_prog)

        # The first usage: use `vars` to set the saved variables.
        >>> var_list = [w, b]
        >>> path = "./my_paddle_vars"

        # w and b will be save in a file named "var_file".
        >>> paddle.static.io.save_vars(executor=exe, dirname=path, vars=var_list,
        ...                 filename="vars_file")

        # The second usage: use `predicate` to select the saved variable.
        >>> def name_has_fc(var):
        ...     res = "fc" in var.name
        ...     return res
        >>> param_path = "./my_paddle_model"

        # all variables whose names contain "fc " are saved.
        >>> paddle.static.io.save_vars(executor=exe, dirname=param_path, main_program=main_prog, vars=None, predicate = name_has_fc)


FNT)r   r   r	  r   saved_paramsr   r   saverk   r   rn   r   r   r   r   r   )$r   r*   r    r  r   r   r   rr   r   r   r   rs   r[   r
   r`   ra   r   r   r   r   r  normpathrX   r   r   r   r   rc   r_   r   r   r   r   r   r   r   )r   r   r   r	  r   r   r   params_var_namer   r   r   each_varnew_varsave_file_pathsave_var_listrX   	save_pathrY  s                     r>   r  r  -  s   f }}WDCCN8+%l3L|%fY(>(>(@AB
 	
 )tDz?aMMh y!..0
H}} 4 4 8 88*:@GNe$;!#GG$$W-w||" $$'+&(8(8(HI	 %  .5W\\*! $ >M|0023$$\%78 4 I&GGLL)9)9')BHM	%00\\))--O 1 L --d3  #]+l+!*&4	 !  	##%\">**?;EEGG r=   c                   [        5       (       a  [        XX#U5      $ SnUb   [        R                  R	                  U5      nOSnUS:X  a  SnUcg  Uc
  [        5       n[        U[        5      (       d  [        S[        U5       35      e[        U UU[        [        XBR                  5       5      5      US9  g[        5       nUR                  5       nUc
  [        5       n[        U[        5      (       d  [        S[        U5       35      e0 n	0 n
/ n/ nU GHT  n[        U[        5      (       d   eUR                  [         R"                  R$                  R&                  :X  a  MO  [        U[(        5      (       a/  [+        UR,                  R/                  5       5      XR0                  '   UR                  [         R"                  R$                  R2                  :X  a  UR5                  U5        M  [7        X5      nUR5                  U5        UcO  Uc  [9        S5      eUR;                  S0 S	U/0S
[        R                  R=                  XR0                  5      0S9  GMF  XUR0                  '   GMW     U GH  n[        U[        5      (       d   eUb  [9        S5      e[7        X5      n[        R                  R=                  XR0                  5      n[        R                  R?                  U5      (       d  [9        SUR0                   SU 35      e[        R                  RA                  U5      (       aA  UR;                  S0 S	U/0S
[        R                  R=                  XR0                  5      0S9  GM  / n[        RB                  " U5      nU H6  nURE                  UR0                  5      (       d  M%  UR5                  U5        M8     / nU H}  nURG                  UUR                  URH                  URJ                  SS9nUR5                  U5        [        R                  R=                  UUS5      nUR;                  S0 S	U/0S
U0S9  M     UR;                  SSU0S	U00 S9  GM     Ubq  / n[M        U
RO                  5       5       H  nUR5                  U
U   5        M     USL a  [        R                  R=                  X5      nUR;                  S0 S	U0UUS.S9  U RQ                  U5        U H  n[        U[(        5      (       d  M  [R        RT                  RW                  5       RY                  UR0                  5      nUc   SUR0                  -   5       e[Z        R\                  " UR_                  5       5      RH                  nUR0                  U	;   d   UR0                  S-   5       eU	Ra                  UR0                  5      nUU:w  d  M  [c        SU SUR0                   SU S35      e   g)a  
:api_attr: Static Graph

This API loads variables from files by executor.

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 run for loading variables.
    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
    predicate(function, optional): The function selects variables that make
                                    `predicate(variable) == True`.
                                    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

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()
        >>> main_prog = static.Program()
        >>> startup_prog = static.Program()
        >>> with static.program_guard(main_prog, startup_prog):
        ...     data = paddle.static.data(name="img", shape=[64, 784])
        ...     w = paddle.create_parameter(shape=[784, 200], dtype='float32', name='fc_w')
        ...     b = paddle.create_parameter(shape=[200], dtype='float32', name='fc_b')
        ...     hidden_w = paddle.matmul(x=data, y=w)
        ...     hidden_b = paddle.add(hidden_w, b)
        >>> place = paddle.CPUPlace()
        >>> exe = static.Executor(place)
        >>> exe.run(startup_prog)

        # The first usage: using `vars` to specify the variables.
        >>> path = "./my_paddle_vars"
        >>> var_list = [w, b]
        >>> paddle.static.io.save_vars(executor=exe, dirname=path, vars=var_list,
        ...                    filename="vars_file")
        >>> paddle.static.io.load_vars(executor=exe, dirname=path, vars=var_list,
        ...                    filename="vars_file")

        # w and b will be loaded, and they are supposed to
        # be saved in the same file named 'var_file' in the path "./my_paddle_vars".

        # The second usage: using the `predicate` function to select variables
        >>> param_path = "./my_paddle_model"
        >>> def name_has_fc(var):
        ...     res = "fc" in var.name
        ...     return res
        >>> paddle.static.io.save_vars(executor=exe, dirname=param_path, main_program=main_prog,
        ...                    vars=None, predicate=name_has_fc)
        >>> paddle.static.io.load_vars(executor=exe, dirname=param_path, main_program=main_prog,
        ...                    vars=None, predicate=name_has_fc)

        # Load All variables in the `main_program` whose name includes "fc".
        # And all the variables are supposed to be saved in separate files.

FNTr   zWThe type of input main_program is invalid, expected type is base.Program, but received )r   r   r	  r   z>The directory path and params cannot be None at the same time.loadrl   r   rn   z.SelectedRows can not be load with load_combinezSelectedRows var z can not find at )rX   r[   rY   rZ   r]   Paramlookup_sparse_table_mergerk   r  r  r  zMUST in var listzUVariable's shape does not match, the Program requires a parameter with the shape of ((), while the loaded parameter (namely [  ]) has a shape of  (r  )2r   r&   r   r   r[  r   r^   r   r   r[   r9  r   r   r   rs   r	   r
   r`   ra   r   r   r  r_   r  rX   r  r   r   rw   r   r  r:  isfilelistdir
startswithrc   rY   rZ   r   r   r   r  r  r   r   r  r  r   r   r!  )r   r   r   r	  r   r   vars_from_memory	load_progr#  orig_para_shaper%  r&  r'  r]  r^  var_pathr   block_pathsre   slicesslicer   r(  rX   var_tempr*  
orig_shapes                              r>   r9  r9    s   l }}XHMM''""7+2~|/1L,00ijno{j|i}~  	%fY(>(>(@AB	
 I	++-
/1L,00ijno{j|i}~ 
 
Hh1111}} 4 4 8 88(I..16MM++-2. }} 4 4 B BB""8,*:@Gh'?$X  $$"WI.&Wll(KL	 %  .5W\\*= @ $Hh1111# D  +:@Gww||G\\:H77>>(++ '~5FxjQ  ww~~h''$$"WI.&Wll(KL	 %   jj2(E''55e, ) #E&11"$\\%mm%mm$) 2 E MM%( "Xug FI((#!!& 0*I6	 )  $$ $$4="G,	 % e $r M|0023$$\$%78 4  5(77<<:  #.!))9	 !  	Y #Hh	22{{//1::8==IH'O)?(--)OO'("5"5"78??I==O3  223 ),,X]];JJ&"klvkw x<<DMM?J_`i_jjln  #r=   c           
       ^^ [        5       (       a  [        XU40 UD6$ [        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 R#                  5       5      5      nU Vs0 s H  oR$                  U" U5      _M     n	n['        X5      n	[(        R*                  S
:X  a}  [(        R,                  R.                  S:X  a_  [0        R2                  " XS9m[5        US-   S5       n
SmU
R7                  UU4S j[9        S[;        T5      T5       5       5        SSS5        O-[5        US-   S5       n
[0        R<                  " XUS9  SSS5        [        [        [>        U R#                  5       5      5      nU Vs0 s H  oR$                  U" U5      _M     nn[5        US-   S5       n
[0        R<                  " XUS9  SSS5        U RA                  5       nU RB                  RE                  5         [5        US-   S5       n
U
RG                  U RB                  RI                  5       5        SSS5        gs  snf ! , (       d  f       N= f! , (       d  f       GN= fs  snf ! , (       d  f       N= f! , (       d  f       g= f)a  

This function save parameters, optimizer information and network description to model_path.

The parameters contains all the trainable Tensor, will 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 save to a file with suffix ".pdopt". (If the optimizer have no Tensor need to save (like SGD), the fill will not generated).
The network description is the description of the program. It's only used for deployment. The description  will save to a file with a suffix ".pdmodel".

Args:
    program(Program) : The program to saved.
    model_path(str): the file prefix to save the program. The format is "dirname/file_prefix". If file_prefix is empty str. A 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

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> x = static.data(name="x", shape=[10, 10], dtype='float32')
        >>> y = static.nn.fc(x, 10)
        >>> z = static.nn.fc(y, 10)

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

        >>> static.save(prog, "./temp")
r   zThe input model_path MUST be format of dirname/filename [dirname\filename in Windows system], but received model_path is empty string.rT   zJ'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   r   rX   r   r  r  )rf   ts     r>   r   save.<locals>.get_tensor  s/    N##CHH-88:xx{r=   darwin   )protocol	.pdparamsr   i   @c              3  2   >#    U  H  nTXT-    v   M     g 7fr   r5   )r   r}   	max_bytespickle_bytess     r>   r   save.<locals>.<genexpr>)  s!      ?A QY/?s   r   N.pdoptr   )%r   r)   r   r   r  r   r   r^   intrw   r[   r   r:  r   r   r   r   r   rX   r   sysplatformversion_infomajorpickledumpsr   
writelinesrangerr   dumpr   r   r_   r   r   r   )rC   r  r|  configs	base_namedir_namer   parameter_listp
param_dictr   optimizer_var_listopt_dictr   r  r  s                 @@r>   rZ  rZ    s   X }}XAAA  ,I?  	R? G#,-X	
 h$$9$x.9IJ
 	
 !|x!|=hZH
 	
 wwz*Hx00
H &w/@/@/BCDN1?@A&&*Q-'J@#J9J ||xC$4$4$:$:a$?||JB*{*D1QILL q#l"3Y?  21 *{*D1QKK
9 2 %w'8'8':; 0BB/A!
1%/AHB	j8#T	*aH(3 
+ ==?LLL	j:%t	,	0023 
-	,9 A 21 21 C	*	* 
-	,s<    L	>3L	LL1?L6*M
L
L.6
M
Mc           	        Ub  [        U[        5      (       d   eUnUR                  S5      (       a  USS nOSUR                  S5      (       a  USS nO7UR                  S5      (       a  USS nOUR                  S5      (       a  USS	 n[        5       (       a  [	        XX#5      $ US-   n[
        R                  R                  U5      (       Gd  [        R                  U S
35        Uc  [        S5      eUb  U Vs/ s H  ofR                  PM     nnOSn[
        R                  R                  U5      (       Ga  [        5       n[
        R                  " USS9 HM  u  pnU HA  nUR                  [
        R                  R!                  X5      R#                  SS5      5        MC     MO     [%        U R'                  5       5      n/ nU H  n[
        R                  R!                  XR                  5      R#                  SS5      nUSL =(       d    UR                  U;   nX;   d  M]  U(       d  Mf  UR)                  U5        UR+                  U5        M     [-        U5      S:  aV  SR!                  [%        U5      5      n[        R/                  SR1                  SR!                  [%        U5      5      5      5         [3        X!US9  g[
        R                  R9                  U5      (       a  Uc  [        S5      eU R'                  5       nU Vs1 s H  ofR                  iM     nnU H  nUR                  U;  d  M  [;        S5      e   [
        R                  R=                  U5      u  nn [3        UUUUS9  gS n[%        [?        [@        U R'                  5       5      5      nU(       a=  [B        RD                  RF                  RI                  U[K        5       URL                  5        [O        US5       n[P        RR                  S:X  a*  [P        RT                  RV                  S:X  a  [Y        X\5      nO
[[        USS9n[]        U5      nSSS5        U HA  nUR                  W;   d   SUR                   S U S!35       eU" UUUR                     5        MC     [%        [?        [^        U R'                  5       5      5      n[-        U5      S:  a  US-   n[
        R                  R                  U5      (       d   S"U S#35       eU(       a=  [B        RD                  RF                  RI                  U[K        5       URL                  5        [O        US5       n[[        USS9nSSS5        U HA  nUR                  W;   d   S$UR                   S U S!35       eU" UUUR                     5        MC     ggs  snf ! [4         a  n[        R7                  U5        UeSnAf  [5        S5      e= fs  snf ! [4         a  n[        R7                  U5        UeSnAf  [5        S5      e= f! , (       d  f       GN= f! , (       d  f       N= f)%a  
:api_attr: Static Graph

This function get parameters and optimizer information from program, and then get corresponding value from file.
An exception will throw if shape or dtype of the parameters is not match.

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

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

Returns:
    None

 Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> x = static.data(name="x", shape=[10, 10], dtype='float32')
        >>> y = static.nn.fc(x, 10)
        >>> z = static.nn.fc(y, 10)

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

        >>> static.save(prog, "./temp")
        >>> static.load(prog, "./temp")
Nr}  r  r   z.json[ not found, try to load model file saved with [ save_params, save_persistables, save_vars ]zeexecutor is required when loading model file saved with [ save_params, save_persistables, save_vars ]Ftopdown\/r    zvariable file [ {} ] not used)r   r   r	  zFailed to load model file, please make sure model file is saved with the following APIs: save_params, save_persistables, save_varszevar_list is required when loading model file saved with [ save_params, save_persistables, save_vars ]z/loaded var [{}] is not in program variable listr   r   r	  r   zFailed to load model file , please make sure model file is saved with the the following APIs: [ save_params, save_persistables, save_vars ]. When these API called, filename CANNOT be Nonec                   [        5       R                  U R                  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R1                  5       5      nUR3                  X5        g )N:r   )r   r   rX   r   _placeis_cpu_placer  r  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)rf   ndarrayrx  r  places        r>   set_varload.<locals>.set_var  s   N##CHH-88:HHJ>>KK((*E##%%KK//1E^^  &&(AKK
#KK(():;E    &&(AKK
#KK++((*005a8!:L:L:NE   &&(AKK
#KK))!//*;<E	gr=   r.  rz  r{  latin1encodingzCannot find [z] in model file []zOptimizer file [z] not exitszCan not find [)0r^   r   endswithr   r%   r   r   r:  r7  debugrw   rX   r   r  walkaddr  replacer   r   r   removerr   r8  formatr9  r!  errorrh  LookupErrorr  r   r   r  r  r
   _create_loaded_parameterr   _default_executorr   r  r  r  r  r   r"   r   r   )rC   r  r   var_listmodel_prefixparameter_file_namerf   var_list_namesbinary_file_setrootdirsfilesr   program_var_listloaded_var_listrn  load_conditionunused_var_listr  program_var_name_setr  	file_namer  r  	load_dictr   r  opt_file_names                               r>   rc  rc  @  s   b z(H====L[))#CR(			x	(	(#CR(			z	*	*#CR(			w	'	'#CR(}}xBB&477>>-.. 	"##~	
 w  2:;(3hh(N;N!N77==$$!eO%'WWZ%G!EA#''T-55dC@  &H
  $G$5$5$78 O'77<<
HH=EEdCP"d*Hchh..H  .>>#**3/#**84 ( ?#a'"%((4+@"A3::o!67
% WW^^J'' {   '0028H#I8HHH8H #I  88#77%I    #%''--
";Hi%$!&	  0 &w/@/@/BCDN11LNH,F,F	
 
!4	(A<<8#(8(8(>(>!(C)*=AI)!h?I%i0	 
) vv" 	
AFF8#45H4IK	
" 	9QVV$%	  %w'8'8':; "$x/ww~~m,, 	
}o[9	
, KK55"LNH4N4N -&!)!h?I '#A66Y&  (9-J& Ay()	 $ #y <@   a "P  $J"   a "E L 
)	(8 '&sU   >V+<
V0 W$+W) 2AXX/0
W!:WW!)
X3X

X
X,/
X=c           	     b   [        U5      n[        5       (       a6  [        U 5      u  p#X#-   nU Vs/ s H  oUR                  (       d  M  UPM     nnO'[	        [        [        U R                  5       5      5      n0 nU GH  n[        R                  R                  5       R                  UR                  5      nUc   SUR                   S35       eUR                  U;   d  Me  [        R                  " UR                  5       5      n	XR                     n
U	R                   U
R                   :X  d/   SU	R                    SUR                   SU
R                    S35       eU	R"                  U
R"                  :X  d/   SU	R"                   SUR                   S	U
R"                   S35       eUR                  5       nUR%                  5       n[        R                  R'                  5       nUR)                  5       (       a  [        R                  R+                  5       nOUR-                  5       (       ag  [        R                  R.                  R1                  5       nUR3                  U5        [        R                  R5                  UR7                  5       5      nO{UR9                  5       (       af  [        R                  R.                  R1                  5       nUR3                  U5        [        R                  R;                  UR=                  5       5      nUR?                  X5        S
XgR                  '   GM     / nURA                  5        H  u  nnUU;  d  M  URC                  U5        M!     [E        U5      S:  a5  [F        RH                  " SRK                  SRM                  U5      5      5        ggs  snf )a  
Set program parameter from state_dict

An exception will throw if shape or dtype of the parameters is not match.

NOTICE: This function MUST called after run start_up_program

Args:
    program(Program): The program to be set
    state_dict(dict): the dict store Parameter and optimizer information
Returns:
    None

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> x = static.data(name="x", shape=[10, 10], dtype='float32')
        >>> y = static.nn.fc(x, 10)
        >>> z = static.nn.fc(y, 10)

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

        >>> static.save(prog, "./temp")
        >>> program_state = static.load_program_state("./temp")

        >>> static.set_program_state(prog, program_state)
NzVariable [ z2 ] Not found, Please make sure run startup programzVParameter's shape does not match, the Program requires a parameter with the shape of (rf  rg  r  zXParameter's data type does not match, the Program requires a parameter with a dtype of (z ]) has a dtype of  (r   r   zNThis list is not set, Because of Parameter not found in program. There are: {}r  )'r   r   r#   r]   r   r   r   r   r  r  r   r   rX   r  r  r   rY   rZ   r  r  r  r  is_gpu_placer
   r  r  r  r  r  r  r  r  itemsr   rr   r   r   r  r  )rC   
state_dictparamsoptsr  rf   used_para_listpararr  orig_para_npnew_para_npten	ten_placepy_placer  r  unused_para_listkr   s                      r>   set_program_stater    s   N #:.J}})'2)7K#??#Kf^W5F5F5HIJN;;++-66tyyA# 	
$))$VW	
# 99
"88H$7$7$9:L$YY/K%%):):: hiui{i{h| }88<		{BWXcXiXiWjjln:  %%):):: jkwk}k}j~ 88<		{BWXcXiXiWjjln:
 %%'C

I {{++-H--//335''))KK$$**,I&!;;001BC''))KK$$**,I&!;;//0ABGGK*()N99%K N   "1N"##A& # q \cc)*	
 !a Ls   N,N,c                P    [        [        [        U R                  5       5      5      $ )a  
Get all the persistable vars from Program.
Args:
    var(Program): The Program to get persistable vars
Returns:
    list: The list contains all persistable vars in the program
Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.static.io as io
        >>> paddle.enable_static()
        >>> data = paddle.static.data(name="img", shape=[64, 784])
        >>> w = paddle.create_parameter(shape=[784, 200], dtype='float32', name='fc_w')
        >>> b = paddle.create_parameter(shape=[200], dtype='float32', name='fc_b')
        >>> list_para  = io.get_program_persistable_vars(  paddle.static.default_main_program() )
)r   r   r   r   )rC   s    r>   get_program_persistable_varsr    s    & ~w'8'8':;<<r=   c           	        U nUR                  S5      (       a  USS nO7UR                  S5      (       a  USS nOUR                  S5      (       a  USS nUS-   n[        R                  R                  U5      (       Gd  [        R                  U S35        / nUc/  [        R                  R                  U 5      (       a  [        S	5      e[        R                  " U S
S9 Hp  u  pVnU Hd  n[        R                  R                  XX5      n	[        R                  R                  X5      n
U
R                  SS5      n
UR                  U
5        Mf     Mr     [        5          [        5       nUR                  5       nS n SS jn[         R"                  R%                  5       n[         R"                  R'                  U5      n/ n[        R                  R                  U 5      (       aO  [        R                  R)                  U 5      u  nnU H  nUR                  U" UU5      5        M     U" UUUU5        OnUb-  U H  nUR                  U" UU5      5        M     U" UU US5        O>U H8  nUR+                  USS9nU" UU U/SS
5      (       d  M'  UR                  U5        M:     0 nU Hi  n[,        R.                  " [         R"                  R1                  5       R3                  UR4                  5      R7                  5       5      UUR4                  '   Mk     UsSSS5        $ [        R                  R                  U5      (       d   SU S35       e[9        US5       n[:        R<                  S:X  a*  [:        R>                  R@                  S:X  a  [C        X85      nO
[E        USS9nSSS5        [G        W5      nUS-   n[        R                  R                  U5      (       a0  [9        US5       n[E        USS9nSSS5        URI                  W5        U$ ! , (       d  f       GN= f! , (       d  f       N= f! , (       d  f       ND= f)a6  

Load program state from local file

Args:
    model_path(str): The file prefix store the program
    var_list(list|tuple, optional): The Tensor list/tuple to load saved with
                              [ save_params, save_persistables, save_vars ].
                              Default: None.
                              The var_list is only used to get name,
                              will not be modified.
Returns:
    state_dict(dict): the dict store Parameter and optimizer information

Examples:

    .. code-block:: python

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> x = static.data(name="x", shape=[10, 10], dtype='float32')
        >>> y = static.nn.fc(x, 10)
        >>> z = static.nn.fc(y, 10)

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

        >>> static.save(prog, "./temp")
        >>> program_state = static.load_program_state("./temp")
r}  Nr  r  r  r   r  r  z7var_list can not be None when model_path is a file typeFr  r  r  c           	     X   [        U[        5      (       d  [        S5      eU R                  UR                  UR
                  UR                  UR                  UR                  R                  5       [        R                  R                  R                  :X  a  UR                  SS9$ S SS9$ )Nz"value in var_list must be variableTrW   )r^   r	   r   rc   rX   rY   rZ   r[   r_   r
   r`   ra   rb   r\   rd   s     r>   clone_var_to_block.load_program_state.<locals>.clone_var_to_block  s    !#x00#$HII'')))) 88==?dll.B.B.O.OO  !% (   " $ (  r=   Tc                     [        U UUUS9  g!   SnUc"  U Vs/ s H  ofR                  PM     Os  snf snOUnU(       a  [        XW-  5      e[        R                  " XW-  [
        5         g= f)Nr  TzFailed to load model/variables `%s`, please make sure model/variables file is saved with the following APIs: save_params, save_persistables, save_vars.F)r9  rX   r!  r   r   RuntimeWarning)exer   r	  r   raise_error	error_strrf   	filenamess           r>   _load_vars_with_try_catch5load_program_state.<locals>._load_vars_with_try_catch  s    M!$ '!!)	  ME  $+ .22TcT2% 
 #*9+@AA i&;^Ls    A-0<A-)rX   r]   zParameter file [z] does not existr.  rz  r{  r  r  )T)%r  r   r   r:  r7  r  rh  rw   r  r  relpathr  r   r   r   rs   r  r  r  r   r  rc   r  asarrayr   r   rX   r   r   r  r  r  r  r   r"   r   update)r  r  r  r  var_name_listr  r  r  r   r   var_temp_namerl  r#  r  r  r  r  r  r  r  rf   rQ  temp_varres_dict	para_dictr  	opti_dicts                              r>   load_program_stater     s   L L[))#CR(			x	(	(#CR(			z	*	*#CR(&477>>-.. 	"##~	
 z : :I  "$U!CDGGLL1	 "	 F - 5 5dC @$$]3	  "D !"	I"//1J" ;?8 KK((*E++&&u-C Oww~~j))&(ggmmJ&?#)#C#**+=j#+NO $)?I
 '''...z3?  ( .Z$ %2 $.#8#8!)t $9 $ 5hZu  ,228< %2 H&%'ZZKK,,.77ALLN&" '
 y #"| 77>>-.. 
.//?@. 
!4	(A<<8#(8(8(>(>!(C)*=AI)!h?I 
) "),I 8+M	ww~~m$$-&!)!h?I ' 	#c #"D 
)	( '&s-   D+PBPA	P#+P4
P #
P14
Q)rj   )ry   r   rz   Sequence[str]r{   strreturnNone)r   )ry   r   r   r  r   r  r  r  )
rC   r   r   Tensor | list[Tensor]r   r  r   zUnpack[_NormalizeProgramKwargs]r  r   )r   r  r   r  r   zUnpack[_SerializeProgramKwargs]r  r   )F)rC   r   rD   boolr  r   )
r   r  r   r  r   r   r   z$Unpack[_SerializePersistablesKwargs]r  r   )rC   r   r   r   r  r   )r   r  r   r   r  r  )r  r  r   r  r   r  r   r   r   z!Unpack[_SaveInferenceModelKwargs]r  r  )r  r   r  r   )rC   r   r  r   r   r   r  r   )r   r  r  r   )r  
str | Noner   r   r   z!Unpack[_LoadInferenceModelKwargs]r  z(list[Program | list[str] | list[Tensor]])....)r   r   r   r  r   Program | Noner	  list[Tensor] | Noner   Callable[[Tensor], bool] | Noner   r  r  r   )r   r   r   r  r   r  r	  r	  r   r
  r   r  r  r  )NNNN)r   r   r   r  r   r  r	  r	  r   r
  r   r  r  r  )rv  )
rC   r   r  r  r|  r  r  zUnpack[_SaveKwargs]r  r  )NN)
rC   r   r  r  r   zExecutor | Noner  Sequence[Tensor] | Noner  r  )rC   r   r  dict[str, npt.NDArray[Any]]r  r  )rC   r   r  zlist[Tensor]r   )r  r  r  r  r  r  )b
__future__r   r   r3  loggingr   r  r  r   typingr   r   r   r   numpyr  r  paddle.baser   r	   r
   r   r   paddle.base.executorr   r   paddle.base.frameworkr   r   r   r   r   paddle.base.log_helperr   paddle.framework.io_utilsr   r   r   r   r   r   r   r   io_utilsr   r   r    r!   r"   pir_ior#   r$   r%   r&   r'   r(   r)   r*   collections.abcr+   r,   numpy.typingnpttyping_extensionsr-   r.   r/   r1   r@   rF   rI   rM   rR   __all__r7   INFOr7  rg   r   r   r   r   r   r   r   r   r  r  r,  r0  rT  r  r9  rZ  rc  r  r  r   r5   r=   r>   <module>r     sk   #    	  
  : :    8  .	 	 	 	 	 	 25.) .)) )&y &)I )
*I **i * 
gll H

0 #

$
 
 
	
D %

%
 
 
	
*uu$u &u .	u
 up 5D$5D%5D .5D 	5D 5DpI 56$56%56 56 3	56
 56 56p,=^%P K
K
$K
 &K
 	K

 0K
 
K
 K
\ ( (X dd!d-5dd dN&R D7D7D7 0D7 .	D7 D7N 
 $' #14 ! 	
 /    
 
 $' #14 ! 	
 /  
  
  	aH aHN $( $15 ! 	
 /  
D  h4h4h4 h4 #	h4
 
h4 h4V  !%(,	Z*Z*Z* Z* &	Z*
 
Z* Z*z _
_
"=_
	_
 _
D = =, :>tt6t tr=   