
    Αi"^                         S SK r S SKrS SKJrJr  S SKJrJr  S
S jr\SS j5       r	S r
S r\SS j5       r\   SS	 j5       rg)    N)Programstatic_only)coredygraph_not_supportc                    S nS n[        U[        5      (       d  [        S5      eUR                  (       d  [	        S5      eUR
                  (       d  [	        S5      eUR                  R                  UR
                  5      nU" XU5        g)a  
customized load_persistables for distributed training.
it should be used on parameter server,

Args:
    executor(Executor): The executor to run for saving parameters.
    dirname(str): The load directory path.
    main_program(Program): The program whose parameters will be
                        loaded. the main_program must be the pserver_program
                        get after transpiler.

Returns:
    None

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env: DISTRIBUTED)
        >>> import paddle
        >>> import paddle.base as base

        >>> paddle.enable_static()
        >>> exe = base.Executor(base.CPUPlace())
        >>> param_path = "./my_paddle_model"
        >>> t = paddle.distributed.transpiler.DistributeTranspiler()
        >>> t.transpile(...)
        >>> pserver_prog = t.get_pserver_program(...)
        >>> _load_distributed_persistables(executor=exe, dirname=param_path, main_program=pserver_prog)
c                 \    U R                  S5      nU R                  S5      nU=(       d    U$ )Nz	.trainer_z.block)find)varnametrainer_idx	block_idxs      U/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/distributed/io.py__is_distributed_part_varA_load_distributed_persistables.<locals>.__is_distributed_part_var5   s)    ll;/LL*	'i'    c                    [        5       nUR                  5       n/ nU GH<  nUR                  nUR                  nUR                  n	UR
                  n
U	(       a  UR                  UR                  UR                  UR                  UR                  SS9nUR                  S0 SU/0[        R                  R                  XR                  5      U
UR                  S.S9  M  UR                  UR                   UR                  UR                  UR                  SS9nUR                  S0 SU/0S[        R                  R                  XR                  5      0S9  GM?     U R                  U5        g )NT)nametypeshapedtypepersistableloadOut)	file_pathseekr   r   inputsoutputsattrsr   )r   global_blockoriginsliceis_sliceoffset
create_varr   r   r   r   	append_opospathjoinrun)executordirnameneed_load_vars	load_prog
load_blockneed_delete_varsparam
origin_var	slice_varr"   r#   r!   r    s                r   __load_persistable_vars?_load_distributed_persistables.<locals>.__load_persistable_vars:   sU   I	++-
#EJI~~H\\F"--""#//#// $ .  $$"UG,%'WW\\'??%K &!&	 % 	 $..&OO,#$**$** $ /  $$"VH-&Woo(NO	 % C $P 	Yr   0'main_program' should be an instance of Program.zK'_load_distributed_persistables' just be designed for distributed training.z\'_load_distributed_persistables' need current_endpoint set in DistributeTranspiler.transpileN)
isinstancer   	TypeError_is_distributed
ValueError_ps_endpoint_parameters_on_pserversget_distributed_vars_by_ep)r*   r+   main_programr   r3   r,   s         r   _load_distributed_persistablesr>      s    >(
- ^ lG,,JKK''Y
 	
 $$j
 	

 	,,GG%%	
 
 H~>r   c                     U(       a  UR                   (       a  [        XUS9  g[        R                  R                  R                  U UU[        US9  g)a  
:api_attr: Static Graph

This API filters out all variables with ``persistable==True`` from the
given ``main_program`` and then tries to load these variables from the
directory ``dirname`` or the file ``filename``.

Use the ``dirname`` to specify the directory where persistable variables
(refer to :ref:`api_guide_model_save_reader_en`) were saved. If variables
were saved in separate files, set ``filename`` as None; if all variables
were saved in a single file, use ``filename`` to specify the file name.

Args:
    executor(Executor): The executor used for loading persistable variables.
                        See :ref:`api_guide_executor_en` for more details about it.
    dirname(str): The directory path.
    main_program(Program, optional): The program whose persistable variables will
                                be loaded. If it is None, the ``default_main_program``
                                will be used automatically. See :ref:`api_guide_Program_en`
                                for more about ``Program``.
                                Default: None.
    filename(str, optional): The file which saved all persistable variables. If variables
                             were saved in separated files, set it to None.
                             Default: None.

Returns:
    None

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import paddle.base as base

        >>> paddle.enable_static()
        >>> exe = base.Executor(base.CPUPlace())
        >>> param_path = "./my_paddle_model"
        >>> prog = base.default_main_program()
        >>> paddle.distributed.io.load_persistables(executor=exe, dirname=param_path,
        ...                             main_program=None)
r+   r=   )r+   r=   	predicatefilenameN)r8   r>   paddlestaticio	load_varsis_persistabler*   r+   r=   rB   s       r   load_persistablesrI   ~   sK    X 44&L	
 	""%$ 	# 	
r   c                    S nS n/ 4S jn[        U[        5      (       d  [        S5      eUR                  (       d  [	        S5      eUR
                  R                  SS/SS	9n/ nU(       a  UR                  UR                  5       5        UR                  (       aV  [        UR                  [        5      (       a  UR                  UR                  5        OUR                  UR                  5        [        [        U" U5      UR                  5       5      5      n[        R                  R!                  XXS
9  UR"                  (       aB  U(       a	  U" XU5        UR                  (       a   U" U UUR                  UR$                  5        ggg)a  
save_persistables for distributed training.
the method will do things listed below:
1.save part of persistable variables on trainer.
2.receive "remote prefetch variables" from parameter servers and merge them.
3.save "distributed lookup table" on parameter servers.
4.receive "optimizer variables" from parameter servers and merge them.

Args:
    executor(Executor): The executor to run for saving parameters.
    dirname(str): The saving directory path.
    main_program(Program): The program whose parameters will be
                        saved. the main_program must be the trainer_program
                        get after transpiler.

Returns:
    None

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env: DISTRIBUTED)
        >>> import paddle
        >>> import paddle

        >>> paddle.enable_static()
        >>> exe = paddle.static.Executor(paddle.CPUPlace())
        >>> param_path = "./my_paddle_model"
        >>> t = paddle.distributed.transpiler.DistributeTranspiler()
        >>> t.transpile(...)
        >>> train_program = t.get_trainer_program()
        >>> _save_distributed_persistables(executor=exe, dirname=param_path, main_program=train_program)
c                    U(       d  g[         R                  R                  5       nUR                  5       nUR	                  5        GHi  u  pVUS   R
                  nUS   R                  nS/[        U5      -  n	S/[        U5      -  n
S/[        U5      -  nS/[        U5      -  n[        U5       Ha  u  pUR                  nUR                  nUR                  nU(       a  UOUnUU	U'   UR                   SU 3U
U'   UR                  UU'   UUU'   Mc     / nU	 HH  nUR                   Vs/ s H  n[        U5      PM     nnUR                  SR!                  U5      5        MJ     UR#                  SSUR                  UU
UU[$        R&                  R!                  XR                  5      S.S9  GMl     U R)                  U5        gs  snf )zl
receive params on pserver through rpc.
if the params are be sliced, will concat them to one, then save it.
Nr   z.slice.,	recv_save)
trainer_idr   slice_shapesslice_varnamesremote_varnames	endpointsr   )r   r   )rC   rD   r   r   itemsr    r"   len	enumerateblock_idr!   endpointr   r   strappendr(   r%   r&   r'   r)   )r*   r+   remote_params_mapprogblockr   remote_paramsr    r"   slicesrP   rQ   rR   idx	optimizerrV   r!   rW   indexrO   dimtmps                         r   __save_remote_params<_save_distributed_persistables.<locals>.__save_remote_params   s   
 !}}$$&!!# $5#:#:#<D"1%,,F$Q'00HVc-00F"Vc-&88N#fs='99O]!33I"+M":$--!$--$,# %u+0::,gcU(Cu%).&#+	%  #; L+0;;7;Cs3x;7##CHHSM2   OO "##\\$0&4'6!*!#g{{!C  3 $=L 	T! 8s   ,Gc                    [         R                  R                  5       nUR                  5       n[        R
                  R                  US5      n0 nX7S'   XgS'   X'S'   UR                  S0 0 US9  U R                  U5        g)z
because the distributed lookup table may too huge to merge and save at one place,
it will be saved at parameter server independent respectively.

the save directory is dirname/"__lookup_table__".

__lookup_table__epmapdirlookup_tablecheckpoint_notifyr   N)	rC   rD   r   r   r&   r'   r(   r%   r)   )r*   r+   distributed_lookup_tablerR   r[   r\   lookup_table_filenamer   s           r    __save_distributed_lookup_tablesH_save_distributed_persistables.<locals>.__save_distributed_lookup_tables  s     }}$$&!!# !#W6H I"g,e 8n$R5 	 	
 	Tr   c                    ^  U 4S jnU$ )Nc                   > U R                   T;   a  gU R                  R                  5       [        R                  R
                  R                  :X  d  U R                  R                  5       [        R                  R
                  R                  :X  d@  U R                  R                  5       [        R                  R
                  R                  :X  a  gU R                  $ )NF)
r   descr   r   VarDescVarTypeFEED_MINIBATCH
FETCH_LISTREADERr   )varexclude_var_namess    r   is_validH_save_distributed_persistables.<locals>.__exclude_vars.<locals>.is_valid(  s    xx,,4<<#7#7#F#FF88==?dll&:&:&E&EE88==?dll&:&:&A&AA??"r    )ry   rz   s   ` r   __exclude_vars6_save_distributed_persistables.<locals>.__exclude_vars'  s    		# r   r5   zK'_save_distributed_persistables' just be designed for distributed training.	OptimizerRemotePrefetchT)groupby)r=   r+   varsN)r6   r   r7   r8   r9   r;   get_distributed_vars_by_vtypesextendkeys_distributed_lookup_tablelistrY   filter	list_varsrC   rD   	save_vars	_is_chief
_endpoints)	r*   r+   r=   rd   rn   r}   rZ   ry   
local_varss	            r   _save_distributed_persistablesr      sl   F2h0 *,  lG,,JKK''Y
 	

 	,,KK*+T 	L 	
    !2!7!7!9:--l<<dCC$$\%K%KL$$\%K%KL~/0,2H2H2JKJ MMW    4EF11,66''	 2 r   c                    U R                   R                  5       [        R                  R                  R
                  :X  d  U R                   R                  5       [        R                  R                  R                  :X  d@  U R                   R                  5       [        R                  R                  R                  :X  a  gU R                  $ )a  
Check whether the given variable is persistable.

Args:
    var(Variable): The variable to be checked.

Returns:
    bool: True if the given `var` is persistable
    False if not.

Examples:
    .. code-block:: python


        >>> import paddle
        >>> paddle.enable_static()
        >>> image = paddle.static.data(
        ...     name='image', shape=[None, 28], dtype='float32')
        >>> bias_attr = paddle.ParamAttr('fc.b')
        >>> fc = paddle.static.nn.fc(image, size=10, bias_attr=bias_attr)
        >>> param = paddle.static.default_main_program().global_block().var('fc.b')
        >>> res = paddle.distributed.io.is_persistable(param)

F)	rr   r   r   rs   rt   ru   rv   rw   r   )rx   s    r   rG   rG   `  sw    4 	4<<//>>>88==?dll22===88==?dll22999??r   c           	          U(       a  UR                   (       a
  [        XUS9$ [        R                  R	                  U UUS[
        US9$ )a
  
Save all persistable variables from :code:`main_program` to
the folder :code:`dirname` or file :code:`filename`. You can refer to
:ref:`api_guide_model_save_reader_en` for more details. And then
saves these persistables variables to the folder :code:`dirname` or file
:code:`filename`.

The :code:`dirname` is used to specify the folder where persistable variables
are going to be saved. If you would like to save variables in separate
files, set :code:`filename` None; if you would like to save all variables in a
single file, use :code:`filename` to specify the file name.

Args:
    executor(Executor): The executor to run for saving persistable variables.
                        You can refer to :ref:`api_guide_executor_en` for
                        more details.

    dirname(str, optional): The saving directory path.
                        When you need to save the parameter to the memory, set it to None.
    main_program(Program, optional): The program whose persistable variables will
                                     be saved. You can refer to
                                     :ref:`api_guide_Program_en` for more details.
                                     If it is None, the default main program will
                                     be used.
                                     Default: None.
    filename(str, optional): The file to save all variables. If you prefer to
                             save variables in different files, set it to None.
                             Default: None.

Returns:
    str: When saving parameters to a file, returns None.
         When saving parameters to memory, returns a binary string containing parameters.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> paddle.enable_static()
        >>> dir_path = "./my_paddle_model"
        >>> file_name = "persistables"
        >>> image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32')
        >>> label = paddle.static.data(name='label', shape=[None, 1], dtype='int64')
        >>> feeder = paddle.base.DataFeeder(feed_list=[image, label], place=paddle.CPUPlace())

        >>> predict = paddle.static.nn.fc(x=image, size=10, activation='softmax')
        >>> loss = paddle.nn.functional.cross_entropy(input=predict, label=label)
        >>> avg_loss = paddle.mean(loss)
        >>> exe = paddle.static.Executor(paddle.CPUPlace())
        >>> exe.run(paddle.static.default_startup_program())
        >>> paddle.distributed.io.save_persistables(executor=exe, dirname=dir_path, filename=file_name)
        >>> # The persistables variables weights and bias in the fc layer of the network
        >>> # are going to be saved in the same file named "persistables" in the path
        >>> # "./my_paddle_model"
r@   N)r+   r=   r   rA   rB   )r8   r   rC   rD   r   rG   rH   s       r   save_persistablesr     sR    r 44-L
 	
 }}&&%$ ' 
 	
r   c                    SnU b  [         R                  R                  U 5      n[         R                  R                  U5      (       d  [	        SU  S35      eUc  Sn[         R                  R                  U[         R                  R                  U5      5      nUb  [         R                  R                  U5      n[        US5       nUR                  5       nSSS5        OSnUc  [	        S5      eU nUnUn[        R                  " W5      n	[        R                  " U	R                  5       5      (       d  [	        S	U	R                  5        S
35      e[        XX5        U	R                  R!                  5       n
U	R                  R#                  5       nU Vs/ s H!  oR%                  5       R'                  U5      PM#     nnXU/$ ! , (       d  f       N= fs  snf )a  
Load the inference model from a given directory. By this API, you can get the model
structure(Inference Program) and model parameters.
You can refer to :ref:`api_guide_model_save_reader_en` for more details.

Args:
    dirname(str): One of the following:
      - The given directory path.
      - 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.
    model_filename(str, optional): One of the following:
      - The name of file to load the inference program.
      - If it is None, the default filename ``__model__`` will be used.
      - When ``dirname`` is ``None``, it must be set to a string containing model.
      Default: ``None``.
    params_filename(str, optional): It is only used for the case that all
        parameters were saved in a single binary file. One of the following:
      - The name of file to load all parameters.
      - When ``dirname`` is ``None``, it must be set to a string containing all the parameters.
      - If parameters were saved in separate files, set it as ``None``.
        Default: ``None``.

    pserver_endpoints(list, optional): It is only needed by the distributed inference.
                                If using a distributed look up table during the training,
                                this table is also needed by the inference process. Its value is
                                a list of pserver endpoints.

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 paddle.base as base
        >>> import numpy as np

        >>> paddle.enable_static()
        >>> # Build the model
        >>> main_prog = paddle.static.Program()
        >>> startup_prog = paddle.static.Program()
        >>> with paddle.static.program_guard(main_prog, startup_prog):
        ...     data = paddle.static.data(name="img", shape=[64, 784], append_batch_size=False)
        ...     w = paddle.create_parameter(shape=[784, 200], dtype='float32')
        ...     b = paddle.create_parameter(shape=[200], dtype='float32')
        ...     hidden_w = paddle.matmul(x=data, y=w)
        ...     hidden_b = base.layers.elementwise_add(hidden_w, b)
        >>> place = base.CPUPlace()
        >>> exe = base.Executor(place)
        >>> exe.run(startup_prog)

        >>> # Save the inference model
        >>> path = "./infer_model"
        >>> base.io.save_inference_model(dirname=path, feeded_var_names=['img'],
        ...                 target_vars=[hidden_b], executor=exe, main_program=main_prog)
        ...
        >>> # Demo one. Not need to set the distributed look up table, because the
        >>> # training doesn't use a distributed look up table.
        >>> [inference_program, feed_target_names, fetch_targets] = (
        ...     paddle.distributed.io.load_inference_model_distributed(dirname=path, executor=exe))
        >>> tensor_img = np.array(np.random.random((1, 64, 784)), dtype=np.float32)
        >>> results = exe.run(inference_program,
        ...                 feed={feed_target_names[0]: tensor_img},
        ...                 fetch_list=fetch_targets)
        ...
        >>> # Demo two. If the training uses a distributed look up table, the pserver
        >>> # endpoints list should be supported when loading the inference model.
        >>> # The below is just an example.
        >>> endpoints = ["127.0.0.1:2023","127.0.0.1:2024"]
        >>> [dist_inference_program, dist_feed_target_names, dist_fetch_targets] = (
        ...     paddle.distributed.io.load_inference_model_distributed(dirname=path,
        ...                                     executor=exe,
        ...                                     pserver_endpoints=endpoints))
        ...
        >>> # In this example, the inference program was saved in the file
        >>> # "./infer_model/__model__" and parameters were saved in
        >>> # separate files under the directory "./infer_model".
        >>> # By the inference program, feed_target_names and
        >>> # fetch_targets, we can use an executor to run the inference
        >>> # program for getting the inference result.
FNzThere is no directory named ''	__model__rbTzBThe path of params cannot be None when the directory path is None.zUnsupported program version: 
)r&   r'   normpathisdirr9   r(   basenameopenreadr   parse_from_stringr   _is_program_version_supported_versionrI   rr   get_feed_target_namesget_fetch_target_namesr   rx   )r+   r*   model_filenameparams_filenamepserver_endpointsload_from_memoryload_dirnamefprogram_desc_strprogramfeed_target_namesfetch_target_namesr   fetch_targetss                 r    load_inference_model_distributedr     s   B ww''0ww}}\**<WIQGHH!(N"''**>:
 & gg..?O.$'1 vvx ('  "T  ))''(89G--g.>.>.@AA89I9I9K8LBOPPhgG::< <<>5G5GT""4(5G   661 ('(s   G(G
G)N)NN)NNN)r&   rC   paddle.base.frameworkr   r   paddle.frameworkr   r   r>   rI   r   rG   r   r   r|   r   r   <module>r      st    
  6 6e?P 6
 6
rePD D
 D
N  H7 H7r   