
    ͑i                   
   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Jr  S SK	J
r
JrJrJr  S SKrS SKJr  S SKJr  S SKJr  SS	KJrJrJrJr  S
SK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(J)r)J*r*  S
SK+J,r-  S
SK.J/r/J0r0  S
SK1J2r2  \
(       a2  S SK3J4r4J5r5  S SK6J	r7  S SKJ8r8  S SK9J:r:  S SK;J<r<  S SK=J>r>  S SK?J>r@  S SKAJBrB  / rC\R                  " 5       qE\R                  rG\R                  rIS7S jrJS8S jrK\2S9S j5       rLS:S jrMS rNS rOS;S jrPS;S jrQS rR S<S  jrS S=S! jrT S:S" jrUS# rVS$ rWS% rXS>S& jrYS' rZS( r[S) r\S* r]S+ r^S?S, jr_S- r`\S. 5       ra " S/ S05      rb " S1 S25      rc " S3 S45      rd " S5 S65      reg)@    )annotationsN)	lru_cache)TYPE_CHECKINGAnyLiteraloverload)pir)in_cinn_mode)apply_cinn_pass   )ProgramValuetranslate_to_pirtranslate_to_pir_with_param_map   )compilercore	frameworkunique_name)convert_dtype)
Operatorr   Variableconvert_np_dtype_to_dtype_default_main_program	get_flagsin_pir_modepaddle_type_to_proto_typeprocess_type_promotion	set_flags)auto_checkpoint)FetchHandlerMonitorTrainerFactory)signature_safe_contextmanager)	GeneratorSequence)Tensor)	PlaceLike)_Place)DatasetBase)CompiledProgramc                     [         $ )a  
:api_attr: Static Graph

Get the global/default scope instance. There are a lot of APIs use
:code:`global_scope` as its default value, e.g., :code:`Executor.run`

Returns:
    Scope: The global/default scope instance.

Examples:
    .. code-block:: python

        >>> import paddle
        >>> import numpy

        >>> paddle.static.global_scope().var("data").get_tensor().set(numpy.ones((2, 2)), paddle.CPUPlace())
        >>> numpy.array(paddle.static.global_scope().find_var("data").get_tensor())
g_scope     T/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/base/executor.pyglobal_scoper1   L   s	    & Nr/   c                    [         nU q U$ Nr,   scopeexs     r0   _switch_scoper7   b   s    	BGIr/   c              #  b   #    [        U 5      n Sv   [        U5        g! [        U5        f = f7f)at  

This function switches scope through python `with` statement.
Scope records the mapping between variable names and variables ( :ref:`api_guide_Variable` ),
similar to brackets in programming languages.
If this function is not invoked, all variables and variable names are recorded in the default global scope.
When users need to create variables with the same name,
they need to switch scopes through this function
if they do not want the mapping of variables with the same name to be overwritten.
After switching through the `with` statement,
all variables created in the `with` block will be assigned to a new scope.

Parameters:
    scope: The new scope.

Returns:
    None

Examples:

    .. code-block:: python

        >>> import paddle
        >>> import numpy
        >>> paddle.enable_static()

        >>> new_scope = paddle.static.Scope()
        >>> with paddle.static.scope_guard(new_scope):
        ...         paddle.static.global_scope().var("data").get_tensor().set(numpy.ones((2, 2)), paddle.CPUPlace())
        >>> numpy.array(new_scope.find_var("data").get_tensor())
        array([[1., 1.],
               [1., 1.]])
N)r7   r4   s     r0   scope_guardr9   i   s*     H 
u	Bbbs   / /,/c                   [        U [        R                  5      (       a  U  Vs/ s H  n[        X!5      PM     sn$ [        U [        5      (       a  U  Vs/ s H  n[        X!5      PM     sn$ [        U [        R
                  5      (       d   eU R                  5       n[        U5      S:  a  [        S5      eU R                  5       (       a3  U(       a  [        R                  " U 5      $ [        R                  " U 5      $ gs  snf s  snf )a  
Convert a Tensor to a numpy.ndarray, its only support Tensor without LoD information.
For higher dimensional sequence data, please use DenseTensor directly.

Examples:
    .. code-block:: python

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

        >>> new_scope = base.Scope()
        >>> with base.scope_guard(new_scope):
        ...     base.global_scope().var("data").get_tensor().set(numpy.ones((2, 2)), base.CPUPlace())
        >>> tensor = new_scope.find_var("data").get_tensor()
        >>> base.executor.as_numpy(tensor) # or numpy.array(new_scope.find_var("data").get_tensor())

Args:
   tensor(Variable): a instance of Tensor
   copy(bool, optional): Whether to use deep copy.

Returns:
    numpy.ndarray
r   zSome of your fetched tensors hold LoD information.             They can not be completely cast to Python ndarray.             Please set the parameter 'return_numpy' as 'False' to             return DenseTensor itself directly.N)
isinstancer   DenseTensorArrayas_numpylistDenseTensorlodlenRuntimeError_is_initializednparrayasarray)tensorcopytr@   s       r0   r=   r=      s    0 &$//00+126a!622&$+126a!622fd..////
**,C
3x!|1
 	
 88F##::f%%% 32s   DDc                    [        U [        R                  R                  5      (       d  [	        U 5      n [        U[        R                  R                  5      (       d  [	        U5      nX:H  $ )z
Returns True if the first dtype can be compatible the second one.
Currently, we require the two dtype's have to be same.

Args:
    dtype (np.dtype|VarType|str): The type of data: float32, int64, etc.

Returns:
    True if the two types are same.
)r;   r   VarDescVarTyper   )firstseconds     r0   dtype_is_compatible_withrO      sN     eT\\1122*51fdll2233+F3?r/   c                    [        U 5      nU[        U5      :w  a  g[        U5       H-  nX   b  X   S:  a  M  X   b  X   S:  a  M!  X   X   :w  d  M-    g   g)a?  
Returns True if the two dimensions are compatible.

A dimension is compatible with the other if:
1. The length of the dimensions are same.
2. Each non-negative number of the two dimensions are same.
3. For negative number or 'None' in a dimension, it means unknown so it
   is compatible with any number.

Args:
    first (list/tuple): integers representing shape. "None" or negative
        number means unknown.
    second (list/tuple): integers representing shape. "None" or negative
        number means unknown.

Returns:
    True if the two dimensions are compatible.
Fr   T)rA   range)rM   rN   dim_lenis       r0   dimension_is_compatible_withrT      sd    ( %jG#f+7^8ux!|9	A8vy   r/   c                   U R                   R                  5       (       Gad  [        R                  " XR                   U5      nUbB  [	        SU R
                  < S[        U R                  5       SU R                  < SU< S3	5      e[        UR                  5       U R                  5      (       d  [        U R                  [        R                  R                  5      (       a  [        U R                  5      OU R                  n[        UR                  5       [        R                  R                  5      (       a  [        UR                  5       5      OUR                  5       n[	        SU R
                  < SU< SU< 35      eg	)
a@  
Returns True if the variable doesn't require feed check or it is compatible
with the shape and have same dtype as the fed value.

A dimension is compatible with the other if:
1. The length of the dimensions are same.
2. Each non-negative number of the two dimensions are same.
3. For negative number or 'None' in a dimension, it means unknown so it
   is compatible with any number.

Args:
    var (Variable): the Variable object
    feed (DenseTensor): the fed value, which must be a DenseTensor
    num_places: an integer value indicating the number of places.
        ParallelExecutor will divide data into devices (CPU/GPU) evenly.
Returns:
    True if the shape and dtype of variable is compatible with the feed value
Raises:
    ValueError: if the shape or dtype of the variable is not compatible with
        the feed value
The fed Variable  should have dimensions = 
, shape = , but received fed shape  on each deviceThe data type of fed Variable 	 must be , but received T)descneed_check_feedr   diff_tensor_shape
ValueErrornamerA   shaperO   _dtypedtyper;   rK   rL   r   )varfeed
num_places
diff_shapevar_dtype_formatfeed_dtype_formats         r0   check_feed_shape_typerl      s6   , xx!!++D((JG
!#CHH</I#cii.IYYc99-8oW  (syyAA cii)=)=>> cii(YY  dkkmT\\-A-ABB dkkm,[[] 
 0IFVEYYhizh}~  r/   c                D   [         R                  " XU5      nUb/  [        R                  " SU< S[	        U5       SU< SU< S3	5        [        U R                  5       U5      (       d  [        U[         R                  R                  5      (       a  [        U5      OUn[        U R                  5       [         R                  R                  5      (       a  [        U R                  5       5      OU R                  5       n[        R                  " SU< SU< SU< 35        g	)
a  
Returns True if the variable doesn't require feed check or it is compatible
with the shape and have same dtype as the fed value.

A dimension is compatible with the other if:
1. The length of the dimensions are same.
2. Each non-negative number of the two dimensions are same.
3. For negative number or 'None' in a dimension, it means unknown so it
   is compatible with any number.

Args:
    feed (DenseTensor): the fed value, which must be a DenseTensor
    name (str): name of the variable
    target_shape (list): the shape that will be compared with feed
    dtype (core.VarDesc.VarType): the dtype that will be compared with feed
    num_places: an integer value indicating the number of places.
        ParallelExecutor will divide data into devices (CPU/GPU) evenly.
Returns:
    True if the shape and dtype of variable is compatible with the feed value
Raises:
    ValueError: if the shape or dtype of the variable is not compatible with
        the feed value
rV   rW   rX   rY   rZ   r[   r\   r]   T)r   r`   warningswarnrA   rO   rd   r;   rK   rL   r   )rg   rb   target_shapere   rh   ri   rj   rk   s           r0   pir_check_feed_shape_typerq   %  s    0 ''JGJx'A#lBSATT^7
~_V	
 $DKKM599 %!5!566 %  	 $++-)=)=>> $++-( 	
 	,THI>N=QQ`ar`uv	
 r/   c                l   SnU R                    H~  nUR                  R                  5       S:X  a]  US-  nUR                  R                  S5      S   U:X  d   eUR                  R	                  S5      S   nXQ;  a  [        SU S35      eM~    O   US:  a  U[        U5      :w  a  [        S5      eUS:  $ )	ap  Check whether the block already has feed operators.

Return false if the block does not have any feed operators.
If some feed operators have been prepended to the block, check that
the info contained in these feed operators matches the feed_targets
and feed_holder_name. Raise exception when any mismatch is found.
Return true when the block has feed operators with matching info.

Args:
    block: a block instance (typically global block of a program)
    feed_targets: a dictionary of {feed_target_name: feed_target_data}
    feed_holder_name: the name of the variable that holds the data of
        all feed targets. The type of this feed_holder variable is
        FEED_MINIBATCH, which is essentially vector<DenseTensor>.

Returns:
    A boolean value that indicates whether a block has feed operators
    that match the info contained in feed_targets and feed_holder_name.
r   rg   r   XOutz'feed_targets' does not have 	 variablez:Feed operators in program desc do not match 'feed_targets')opsr^   typeinputoutput	ExceptionrA   )blockfeed_targetsfeed_holder_name
feed_countopfeed_target_names         r0   has_feed_operatorsr   T  s    * Jii77<<>V#!OJ77==%a(,<<<<!ww~~e4Q7334D3EYO  4
   A~*L(99H
 	
 >r/   c                B   SnU R                    H  nUR                  R                  5       U:X  d  M#  US-  nUR                  R                  S5      S   U:X  d   eUR                  R	                  S5      S   nUU Vs/ s H  owR                  R                  5       PM     sn;  a  [        SU S35      eUR                  R                  S5      nXaU   R                  R                  5       :X  a  M   e   US:  a  U[        U5      :w  a  [        S5      eUS:  $ s  snf )	a  Check whether the block already has fetch operators.

Return false if the block does not have any fetch operators.
If some fetch operators have been appended to the block, check that
the info contained in these fetch operators matches the fetch_targets
and fetch_holder_name. Raise exception when any mismatch is found.
Return true when the block has fetch operators with matching info.

Args:
    block: a block instance (typically global block of a program)
    fetch_targets: a dictionary of {fetch_target_name: fetch_target_data}
    fetch_holder_name: the name of the variable that holds the data of
        all fetch targets. The type of this fetch_holder variable is
        FETCH_LIST, which is essentially vector<DenseTensor>.
    fetch_op: the operator name of fetch

Return:
    A boolean value that indicates whether a block has fetch operators
    that match the info contained in fetch_targets and fetch_holder_name.
r   r   rt   rs   z'fetch_targets' does not have ru   colz<Fetch operators in program desc do not match 'fetch_targets')	rv   r^   rw   ry   rx   rb   rz   attrrA   )	r{   fetch_targetsfetch_holder_namefetch_opfetch_countr   fetch_target_namerf   idxs	            r0   has_fetch_operatorsr   |  s   0 Kii77<<>X%1K77>>%(+/@@@@ "c 21 5 +8)+8C=)   45F4GyQ  '',,u%C$c(:(?(?(D(D(FFFF  Q;#m*<<J
 	
 ?)s   >#Dc                   SSK Jn  Sn/ / /nU R                   Hy  nUR                  5       U:X  aJ  US   R	                  UR                  S5      5        US   R	                  UR                  5       S   5        Ma  UR                  5       S:X  d  Mw  SnM{     / nUbc  [        U5       HT  u  p[        U
[        5      (       a  XS   ;  a  [        SU	 S	35      eM3  X" US   5      ;  d  MC  UR	                  U
5        MV     X4$ )
a  Check whether the block already has fetch operation.

Return false if the block does not have any fetch operation.
If some fetch operation have been appended to the block, check that
the info contained in these fetch operation matches the fetch_targets.
Raise exception when any mismatch is found.
Return true when the block has fetch operation with matching info.

Args:
    block: a block instance (typically global block of a program)
    fetch_targets: a list of fetch_target_data
    fetch_op: the operator name of fetch

Return:
    A boolean value that indicates whether a block has fetch operators
    that match the info contained in fetch_targets.
r   )ValueSetFr   rb   zbuiltin.set_parameterTzFound fetch_target[z)] is type(str) and doesn't have fetch op.)paddle.autograd.backward_utilsr   rv   rb   appendoperand_sourceattrs	enumerater;   strrz   )r{   r   r   r   r   is_startup_program
fetch_infor   need_fetch_inforS   	fetch_vars              r0   +has_fetch_operations_and_is_startup_programr     s   ( 8bJii779 qM  !2!21!56qM  F!34WWY11!%  O %m4LA)S))qM1#-aS0YZ  2 (:a="99&&y1 5 ..r/   c                   U R                  5       nUR                  5       nX7R                  ;   a  UR                  U5      nO3UR	                  U[
        R                  R                  R                  SS9nXGR                  ;   a  UR                  U5      n	O3UR	                  U[
        R                  R                  R                  SS9n	[        XqU5      (       dq  [        U5       Hb  u  pUR                  U5      (       a-  UR                  U5      nUR                  SSU/0SU/0SU
0S9  MH  [        R                  " SU S	35        Md     U(       a  S
nOSn[!        XrXM5      (       d_  [        U5       HP  u  p[#        U[$        [&        45      (       d   SU
 S[)        U5       35       eUR+                  USU/0SU	/0SU
0S9  MR     U$ )NTrb   rw   persistablerg   rs   rt   r   rw   inputsoutputsr   The variable : is not found in program. It is not declared or is pruned.fetch_v2fetchWrong type for fetch_list[]: )cloneglobal_blockvarsrf   
create_varr   rK   rL   FEED_MINIBATCH
FETCH_LISTr   r   has_var_prepend_oprn   ro   r   r;   r   r   rw   	append_op)programrg   
fetch_listfeed_var_namefetch_var_nameuse_fetch_v2tmp_programr   feed_varr   rS   rb   outr   rf   s                  r0   _add_feed_fetch_opsr     s    --/K++-L)))##M2**%%44 + 
 *** $$^4	 ++%%00 , 
	 l-@@ GA##D))"&&t,(((,"SEN !*	 )  #D6)cd '  .   
+FAcHc?33 ,QCs49+>3 ""cU|,aj	 # 	 , r/   c           	        SS K nU R                  5       nSn[        XAX%5      u  pgU(       a  UR                  R	                  U 5         [        U5       H  u  p[        U	[        5      (       d   SU S[        U	5       35       eU(       a%  UR                  R                  U	R                  5      n	UR                  R                  X[        U5      -   U5      n
SU
l        M     S S S 5        g g ! , (       d  f       g = f)Nr   pd_op.fetchr   r   T)paddler   r   staticprogram_guardr   r;   r   rw   _pir_ops	parameterrb   r   r   r   )r   r   r   r   r   r   r   r   rS   fetch_inputr   s              r0   _add_pir_fetch_opsr     s    '')LH3n	
 (O
 ]]((1"+O"<!+u55 03tK7H6IJ5 &"(//";";K<L<L"MKoo++#a&!8! #' #= 21 11s   BC,,
C:c                f   SS K nU R                  5       nSn[        XQ/X&5      u  pxU(       at  UR                  R	                  U 5         U(       a%  UR
                  R                  UR                  5      nUR
                  R                  XU5      n	SU	l	        S S S 5        g g ! , (       d  f       g = f)Nr   r   T)
r   r   r   r   r   r   r   rb   r   r   )
r   fetch_value
fetch_name	fetch_colr   r   r   r   r   r   s
             r0   _add_single_pir_fetch_opr   .  s    '')LH3-	
 (O
 ]]((1!$oo778H8HI//''KC"CO	 21 11s   AB""
B0c                    US::  a  U $ [        U 5      U-  S:X  d   e[        S[        U 5      U5       Vs/ s H	  nXX!-    PM     nnU Vs/ s H  n[        R                  " U5      PM     sn$ s  snf s  snf )Nr   r   )rA   rQ   rD   rE   )rG   micro_batch_numrS   chunk_tensorchunks        r0   _merge_tensorsr   @  s    !v;(A--- q#f+77A 	1&'7   *66BHHUO66	 7s   A. A3c                &   [        U [        5      (       d   eUc
  [        5       n[        U[        R                  5      (       d   eUR                  [        U 5      5      nUc   SU -   S-   5       eUR                  5       nU(       a
  [        USS9nU$ )a!  
Fetch the value of the variable with the given name from the
given scope.

Args:
    name(str): name of the variable. Typically, only persistable variables
        can be found in the scope used for running the program.
    scope(core._Scope|None): scope object. It should be the scope where
        you pass to Executor.run() when running your program.
        If None, global_scope() will be used. Default None.
    return_numpy(bool): whether convert the tensor to numpy.ndarray.
        Default True.

Returns:
   DenseTensor|numpy.ndarray
zCannot find zm in scope. Perhaps you need to make the variable persistable by using var.persistable = True in your program.TrH   )	r;   r   r1   r   _Scopefind_var_to_name_str
get_tensorr=   )rb   r5   return_numpyrf   rG   s        r0   
_fetch_varr   K  s    " dC    }eT[[))))
..d+
,C?  ! 	?
 ^^F&t,Mr/   c                    S n[        U [        5      (       a  U S   n [        U [        5      (       a(  U  Vs/ s H
  o!" U5      PM     nnSR                  U5      $ U" U 5      $ s  snf )Nc                b   [        U [        5      (       a  U R                  R                  5       $ [        U [        5      (       a  U $ [        U [
        5      (       a  [	        [        U 5      5      $ [        U [        5      (       a  [	        U R                  5      $ [        [	        U 5      S-   5      e)Nz$ should be Variable, Operator or str)	r;   r   r^   rb   r   r   idr   	TypeErrorrf   s    r0   _to_str_to_name_str.<locals>._to_strn  s|    c8$$88==?"S!!JX&&r#w<U##svv;CH'MMNNr/   r   ,)r;   tupler>   join)rf   r   itemss       r0   r   r   m  sb    
O #u!f#t'*+stWT]s+xx{s| ,s   A#c                   [        U [        5      (       a1  [        U 5      [        UR                  5       5      -   [	        X#5      -   $ U R
                  R                  5       [        UR                  5       5      -   [	        X#5      -   $ r3   )r;   
PirProgramr   raw_address_get_program_cache_keyr^   cached_hash_str)r   r5   rg   r   s       r0   )_get_strong_program_cache_key_for_new_exer     sx    ':&&L%##%&'$T67	
 LL((*%##%&'$T67	
r/   c                    S n[        U [        R                  5      (       a  U R                  OU nU" UR                  S   5      [        [        U 5      5      -   [        X5      -   $ )Nc                    / n[        U R                  R                  5       5       H  nUR                  U5        M     SR	                  U5      $ )N
)r>   r   keysr   r   )r{   	block_strvar_names      r0   _get_varname_from_block>_get_strong_program_cache_key.<locals>._get_varname_from_block  s>    	UZZ__./HX& 0yy##r/   r   )r;   r   r*   _programblocksr   r   r   )r   rg   r   r   inner_programs        r0   _get_strong_program_cache_keyr     sg    $ gx7788 	  	  4 4Q 78
bk
	
 
2	3r/   c                >   / n[        U [        5      (       a  [        U R                  5       5      nOK[        U [        [        45      (       a0  [        U 5       H!  u  p4U[        UR                  5       5      -  nM#     / nUb  [        [        [        U5      5      nX%-   $ r3   )r;   dictr>   r   r   r   mapr   )rg   r   feed_var_namesrS   eachfetch_var_namess         r0   _get_feed_fetch_var_namesr     s    N$diik*	D4-	(	( GAd499;//N 'Os<<=++r/   c                *    [        [        X5      5      $ r3   )r   r   )rg   r   s     r0   r   r     s    (:;;r/   c                D   [        U [        R                  5      (       d  Uc   S5       e[        U5      n[        R                  " U 5      (       a&  [        R
                  " U 5      R                  U5      n O[        U [        [        45      (       aQ  [        R
                  " U 5      n U R                  [        R                  :X  a  [        S5      eU R                  U5      n O[        S[        U 5       S35      e[        R                  " 5       nUR                  X5        U$ )a  
Convert numpy.ndarray to Tensor, its only support Tensor without LoD information.
For higher dimensional sequence data, please use DenseTensor directly.

Examples:

    .. code-block:: python

        >>> import numpy as np
        >>> import paddle.base as base
        >>> place = base.CPUPlace()
        >>> exe = base.Executor(place)
        >>> data = np.array((100, 200, 300))
        >>> np_outs = map(lambda x: base.executor._as_lodtensor(x, place), data)

Args:
    data(numpy.ndarray|list|tuple|scalar): a instance of array, scalar, list or tuple
    data(core.Place): the place of created tensor
    dtype(str|paddle.dtype|np.dtype, optional): the expected data type of created tensor

Returns:
    DenseTensor
z:The dtype should be given when feed data is not np.ndarrayz
	Failed to convert input data to a regular ndarray :
	* Usually this means the input data contains nested lists with different lengths. Please consider using 'base.create_lod_tensor' to convert it to a LoD-Tensor.zConvert data of type z to Tensor is not supported)r;   rD   ndarrayr   isscalarrE   astyper>   r   re   object_r   rw   r   r?   set)dataplacere   rG   s       r0   _as_lodtensorr     s    2 dBJJ''  	
H	
  e$;;t88D>((/DtUm,,88D>DzzRZZ'd 
 ;;u%D'T
|3NO 
 F
JJtMr/   c                P   [        U [        R                  5      =(       d$    [        U R                  [        R                  5      nU(       aZ  [        U [        R                  5      (       a  U OU R                  nUR                  (       a  [
        R                  " S[        5        gg)Nz-Standalone executor is not used for inferenceFT)r;   r   r*   _graph_is_inferencern   ro   UserWarning)r   r   compiledcompiled_programs       r0   _can_use_interpreter_corer    s    '8#;#;< 
00AH  '8#;#;<<  	 ))MM? r/   c                0    [         R                  " U 5        g r3   )loggingwarning)msgs    r0   _warning_oncer    s    OOCr/   c                  4    \ rS rSrSS jrS r\S 5       rSrg)FetchHandleri  Nc                &    Uc   eXl         X l        g r3   )var_dictperiod_secs)selfr  r  s      r0   __init__FetchHandler.__init__	  s    ### &r/   c                    U HM  n[        X   5      [        R                  L d  M#  [        R                  R                  U SX   S    S35        MO     [        R                  R                  S5        g )Nz[0]: r    r   )rw   rD   r   sysstdoutwrite)r  res_dictkeys      r0   handlerFetchHandler.handler  sZ    CHM"bjj0

  C5hmA.>-?q!AB  	

r/   c                     [        S5        g )Na  
class FetchHandlerExample(FetchHandler):
    def handler(self, res_dict):
        print(res_dict["auc"])
        print("auc: {}, {}".format(res_dict["auc"], time.ctime()))

auc = Variable()
var_dict = {"auc": auc}
handler = FetchHandlerExample(var_dict=var_dict)
)printr.   r/   r0   helpFetchHandler.help  s    		
r/   )r  r  )N<   )	__name__
__module____qualname____firstlineno__r  r  staticmethodr   __static_attributes__r.   r/   r0   r  r    s     '
 
 
r/   r  c                  6    \ rS rSrS r SS jrS	S jrS rSrg)
_StandaloneExecutori$  c                    [         R                  " 5       U l        U R                  R                  U5        X l        X0l        U R                  5       U l        g r3   )r   Place_place	set_place_plan_scope_create_new_executor_new_exe)r  r   planr5   s       r0   r  _StandaloneExecutor.__init__%  s;    jjle$
113r/   c                <   U R                   R                  X5      R                  5       nU(       aB  [        USS9n[	        S5      S   (       d#  [        X@R                  R                  5       5      $ U$ U R                  R                  5       S:  a  [        S5      eU$ )a  
Args:
    feed_names(list): This parameter represents the input names of the model.
    fetch_list(list): This parameter represents the Tensors that need to be returned
        after the model runs. The default is None.
    return_numpy(bool): This parameter indicates whether convert the fetched Tensors
        (the Tensor specified in the fetch list) to numpy.ndarray. if it is False,
        the type of the return value is a list of :code:`DenseTensor`. The default is True.
Tr   FLAGS_enable_pir_in_executorr   z;`merge_tensor` does not support when return_numpy is False.)	r2  run_move_to_listr=   r   r   r/  r   rB   )r  
feed_namesr   enable_job_schedule_profilertensorss        r0   r7  _StandaloneExecutor.run,  s     --##

-/ 	 wT2G;<. &gzz/I/I/KLLNzz))+a/"Q  Nr/   c                <    U R                   R                  U5      nU$ r3   )r2  run_profile)r  r9  program_descs      r0   r>  _StandaloneExecutor.run_profileI  s    }}00<r/   c                r    [         R                  " U R                  U R                  U R                  5      nU$ r3   )r   StandaloneExecutorr-  r/  r0  )r  new_exes     r0   r1  (_StandaloneExecutor._create_new_executorM  s'    ))$++tzz4;;Or/   )r2  r-  r/  r0  N)TF)returnzcore.ProgramDesc)	r#  r$  r%  r&  r  r7  r>  r1  r(  r.   r/   r0   r*  r*  $  s    4 KP:r/   r*  c                  R    \ rS rSr " S S5      rS rS rS rS rS r	S	 r
S
 rSrg)_ExecutorCacheiR  c                  ,    \ rS rSr SS jrS rS rSrg)_ExecutorCache._CachedDataiS  Nc	                   Xl         X l        X0l        X@l        XPl        X`l        Xpl        Xl        [        U R                   [        R                  5      (       a  U R                   R                  (       dG  [        R                  " U R                   R                  5      R                  5       U R                   l        [!        [#        U R                   R                  U R                  U R                  U R                  5      5      U l        g [!        [#        U R                   U R                  U R                  U R                  5      5      U l        g r3   )r   rg   r   r   r   r   r5   r3  r;   r   r*   r   r   IrGraphr  
to_programhashr   r  	r  r   rg   r   r   r   r   r5   r3  s	            r0   r  #_ExecutorCache._CachedData.__init__T  s     #LI(O!."0JJI $,,(@(@AA||,, -6,=,=++- jl LL)  =--

			  =djj$))T__r/   c                v    [        U[        R                  5      =(       a    U R                  UR                  :H  $ r3   )r;   rG  _CachedDatar  )r  others     r0   __eq__!_ExecutorCache._CachedData.__eq__  s,    5."<"<= *HH		)r/   c                    U R                   $ r3   )r  r  s    r0   __hash__#_ExecutorCache._CachedData.__hash__  s    88Or/   )	rg   r   r   r   r  r   r3  r   r5   r3   )r#  r$  r%  r&  r  rS  rW  r(  r.   r/   r0   rQ  rI  S  s     *	X		r/   rQ  c                |    [        SS9" U R                  5      U l        [        SS9" U R                  5      U l        g )N   )maxsize)r   _get_program_and_executor _get_cached_program_and_executor_get_pir_program_and_executor)_get_cached_program_and_executor_pir_moderV  s    r0   r  _ExecutorCache.__init__  s=     1:!0D**1
- :C19M..:
6r/   c                8    U R                   R                  5         g r3   )r]  cache_clearrV  s    r0   clear_ExecutorCache.clear  s    --99;r/   c                N    U R                  U R                  UUUUUUU5      5      $ r3   )r]  rQ  )r  r   rg   r   r   r   r   r5   s           r0   get_program_and_executor'_ExecutorCache.get_program_and_executor  s:     44

 
	
r/   c           	        [        UR                  5      n[        U[        R                  5      (       a  UR
                  OUnUR                  nUR                  nUR                  nUR                  nUR                  nUR                  n	[        U[        R                  5      (       d)  [        UR                  [        R                  5      (       a  [        U[        R                  5      (       a  UOUR                  n
U
R                  nSnUb'  UR                  (       a  SnSUl        [        SS05        U
R!                  X5        U(       a  SUl        ["        R$                  " U
R                  5      nUR'                  5       n[)        US5      (       a  UR*                  Ul        UnO-S nSSKJnJn  U" 5       (       a  U[3        5       :X  a  U" 5         Un[5        UUUUUSS9nUR7                  5       nUR8                  (       a7  SUR8                  ;   a'  SS	KJn  UR8                  S   nUS
   nU" UUUU5      nGO.[>        R@                  " S5      n[C        S5      S   (       a  [D        RF                  " S5      S;   a  URH                  (       a  [K        URL                  5      u  nnSSK'J(n  URS                  UUURT                  5        [>        RV                  " 5       (       a(  [X        RZ                  " S5        UR]                  US 5      n[_        5       (       a  [a        U5        SU0nO&S[c        URL                  5      0nOSURL                  0n[>        Rd                  " U/U5      nURf                  (       a  SURf                  ;   a  [i        URf                  S   5      S:  a  [j        Rl                  " 5       nURf                  S    HS  nUS:X  a8  SSK7J8n  URs                  5        H  nURu                  U5      nU" U5        M     MA  URw                  U0 5        MU     URs                  5        H%  nURu                  U5      nURy                  U5        M'     [{        UUU	5      n UU 4$ )NFT!FLAGS_new_executor_use_cuda_graphlr_schedulerr   )	prim2origprim_enabled)r   rg   r   r   r   r   standalone_opt)
apply_passschedule_modedefaultr6  "FLAGS_enable_prim_after_distribute)Truetrue1decomp apply auto_recompute in executor	pass_listeliminate_transpose)eliminate_transpose_by_reshape)>r   r   r;   r   r*   r   rg   r   r   r   r   r5   r  _build_strategyallow_cuda_graph_capturer   _compiler   rK  rL  hasattrrj  paddle.incubate.autogradrk  rl  r   r   r   _pipeline_opt1paddle.distributed.passes.pipeline_scheduler_passrn  r   Jobr   osgetenv_need_decompr   r^   paddle.decompositionrv  decompose_pir_program_grad_var_to_var_enable_auto_recomputer	  infoauto_recompute_pir_programr
   r   r   Plan	_pass_optrA   r	   PassManager0paddle.distributed.auto_parallel.static.pir_passrz  	job_types
ir_programadd_passr7  r*  )!r  cached_datar   r   rg   r   r   r   r   r5   r  build_strategyuse_cuda_graphir_graphconverted_programrk  rl  new_programrn  rm  	pass_namer3  default_jobpir_programparam_mappingrv  type_to_programpmprz  job_typer  rC  s!                                    r0   r\  (_ExecutorCache._get_program_and_executor  s   ()<)<= '8#;#;<<  	
  ++
#11$33!!!! gx7788JNNH44=
 =

 gx'?'?@@ ^^ 
 .==N"N *";;!%:?7>EF%%e3:>7 (()9)@)@AH ( 3 3 5}n551>1K1K!.-M "NH~~'-A-C"C#M%!!')
 mmo%% K$=$== )667GHN&7I[)^D ((9-K78. IIBC,-#00
 88H8HI#% <00#]K4P4P 2244%GH&,&G&G'' $~~'4'0+&>O "#3K4D4D#E'O $-k.>.>"?99k]O<D !!{444K))+67!;"B **;7-- %)NN$4%)__X%>
6zB %5 KK2& 8 !NN,!__X6
z" - &eT59G##r/   c	                P    U R                  U R                  UUUUUUUU5      5      $ r3   )r_  rQ  rN  s	            r0   get_pir_program_and_executor+_ExecutorCache.get_pir_program_and_executorB  s=     ==	
 	
r/   c                   / n[        U5       Hn  u  pE[        U[        5      (       a  UR                  U5        M-  U H;  nUR	                  U5      (       d  M  UR                  UR                  U5      5        M=     Mp     U$ r3   )r   r;   r   r   haslook_up)r  r   value_map_listupdate_fetch_listrS   r   	value_maps          r0   _update_pir_fetch_list%_ExecutorCache._update_pir_fetch_listZ  sn    %j1LA)S))!((3!/I }}Y//)001B1B91MN "0	 2 ! r/   c           	        UR                   nUR                  nUR                  nUR                  nUR                  nUR
                  nUR                  nS n	UR                  c  [        R                  " 5       n
[        UR                  5       UUS5      u  pUR                  U
5      nU(       a  UnOU R                  XJ/5      n[        UUUS9  [        R                   " S5      nU(       d  [#        5       (       a  U	" U5        SU0n[        R$                  " U/U5      nGO[0 n/ nUR                  R'                  5        HZ  nUR                  R)                  U5      n[        R                  " 5       n
UR                  U
5      nUUU'   UR+                  U
5        M\     / nUR                  R-                  5        H  nUR+                  U5        M     [        R$                  " UU5      nU R                  UU5      n[/        U5       H4  u  nn[1        UR2                  R                   UU[5        U5      -   U5        M6     [#        5       (       a0  UR'                  5        H  nUR)                  U5      nU	" U5        M     [7        UUU5      n/ nUR                  5       nUR8                   GH"  nUR;                  5       S:X  ap  UR=                  5       S   n[>        UR=                  5       S      nUR=                  5       S   nUUUURA                  S	5      RB                  4n UR+                  U 5        UR;                  5       S
:X  d  M  UR=                  5       S   n[>        URE                  5       S	   RF                     nURE                  5       S	   RH                  nUUUURA                  S	5      RB                  4n UR+                  U 5        GM%     UUU4$ )Nc                   SSK Jn  [        R                  " 5       (       a@  [        R
                  " S5        UR                  5          UR                  U 5        S S S 5        [        R                  " 5       (       a(  [        R
                  " S5        UR                  U S 5      n [        U 5        U $ ! , (       d  f       N]= f)Nr   ru  zapply decompose in executorrw  )r  rv  r   _enable_dist_prim_allr	  r  
prim_guarddecompose_dist_programr  r  r   )r   rv  s     r0   cinn_processB_ExecutorCache._get_pir_program_and_executor.<locals>.cinn_processn  s    3))++:;&&(11': ) **,,?@ ;;GTJG$N )(s   B00
B>r   )r   r   rp  z
pd_op.datarb   re   rc   r   z
pd_op.feed)%r   rg   r   r   r   r   r5   r3  r	   	IrMappingr   r   r   r  r   r   r  r
   r  r  r  r   job_listr   r   r{   r   r*  rv   rb   r   r   resultr   resultsre   rc   )!r  r  r   rg   r   r   r   r   r5   r  r  _r   r  r  r  r3  r  r  r  program_tmpr  jobrS   valuerC  data_op_infosr   r   r   var_type	var_shapetups!                                    r0   r^  ,_ExecutorCache._get_pir_program_and_executore  sn   %% ++
#11$33!!!!	 #I$O$$&	%!A mmI.G!$.!$($?$?%! ,-
 ((9-K%,..W%('2O99k]O<D ON',,668(--88B
MMO	(..y9,7)%%i0 9 H"''002$ 3 99X7D $ ; ;N! &&785(KK''Q0G 9
 ~~ $ 0H!%!:J , !1 &eT59++-""BwwyL(#%88:f#5 4RXXZ5HIHHJw/	$IIaL,,	 $$S)wwyL(#%88:f#5 4RZZ\!_5J5JKJJLO11	$IIaL,,	 $$S)- #0 ..r/   )r]  r_  N)r#  r$  r%  r&  rQ  r  rc  rf  r\  r  r  r^  r(  r.   r/   r0   rG  rG  R  s3    4 4l	
<
,S$j
0	!m/r/   rG  c                     \ rS rSr% SrS\S'   S7S8S jjrS rS9S jrS	 r	S
 r
S rS rS rS rS rS rS rS rS rS rS rS:S jrS rS rS rS rS r\S 5       r\ S;S j5       r\S 5       r S9S jr S9S  jr!\"         S<                   S=S! jj5       r#\"         S<                   S>S" jj5       r#\"         S<                   S?S# jj5       r#         S@S$ jr#S% r$S& r%S' r&S( r'SAS) jr(S* r)SBS+ jr*        SCS, jr+          SDS- jr,           SES. jr-S/ r.\ SFS0 j5       r/\SGS1 j5       r0           SES2 jr1         SH                   SIS3 jjr2       SJ               SKS4 jjr3         SH                   SIS5 jjr4S6r5g)LExecutori  aS
  
:api_attr: Static Graph

An Executor in Python, supports single/multiple-GPU running,
and single/multiple-CPU running.

Args:
    place(paddle.CPUPlace()|paddle.CUDAPlace(n)|str|None): This parameter represents
        which device the executor runs on. When this parameter is None, PaddlePaddle
        will set the default device according to its installation version. If Paddle
        is CPU version, the default device would be set to `CPUPlace()` . If Paddle is
        GPU version, the default device would be set to `CUDAPlace(0)` . Default is None.
        If ``place`` is string, it can be ``cpu``, and ``gpu:x``, where ``x``
        is the index of the GPUs. Note: users only pass one Place or None to initialize
        Executor when using multiple-cards. Other APIs will override the cards. See
        `document for multiple-cards <https://www.paddlepaddle.org.cn/documentation/docs/en/develop/guides/01_paddle2.0_introduction/update_en.html#stand-alone-multi-card-launch>`_

Returns:
    Executor

Examples:

    .. code-block:: python

        >>> import paddle
        >>> import numpy
        >>> import os

        >>> # Executor is only used in static graph mode
        >>> paddle.enable_static()

        >>> # Set place explicitly.
        >>> # use_cuda = True
        >>> # place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace()
        >>> # exe = paddle.static.Executor(place)

        >>> # If you don't set place, PaddlePaddle sets the default device.
        >>> exe = paddle.static.Executor()

        >>> train_program = paddle.static.Program()
        >>> startup_program = paddle.static.Program()
        >>> with paddle.static.program_guard(train_program, startup_program):
        ...     data = paddle.static.data(name='X', shape=[None, 1], dtype='float32')
        ...     hidden = paddle.static.nn.fc(data, 10)
        ...     loss = paddle.mean(hidden)
        ...     paddle.optimizer.SGD(learning_rate=0.01).minimize(loss)
        ...
        >>> # Run the startup program once and only once.
        >>> # Not need to optimize/compile the startup program.
        >>> exe.run(startup_program)

        >>> # Run the main program directly without compile.
        >>> x = numpy.random.random(size=(10, 1)).astype('float32')
        >>> loss_data, = exe.run(train_program, feed={"X": x}, fetch_list=[loss.name])

        >>> # Or, compiled the program and run. See `CompiledProgram`
        >>> # for more details.
        >>> compiled_prog = paddle.static.CompiledProgram(
        ...     train_program)
        >>> loss_data, = exe.run(compiled_prog, feed={"X": x}, fetch_list=[loss.name])

r(   r   Nc                P   Uc  [         R                  " 5       nX l        O[         R                  " U5      U l        0 U l        0 U l        0 U l        0 U l        0 U l        0 U l	        0 U l
        [        R                  " 5       nUR                  U R                  5        [        R                  " U5      U l        SU l        0 U l        SU l        S U l        [(        R*                  " S5      U l        [/        5       U l        [        R2                  R5                  5       U l        SU l        g )NF__auto_checkpoint_executor__)r   _current_expected_place_r   _get_paddle_placeprogram_caches
ctx_cachestrainer_cachesscope_cachesmicro_scope_cache
var_cachespruned_program_cachesr   r,  r.  r  _default_executor_closedpruned_program_scope_caches_prepare_to_run_calledr3  r   generate_auto_checkpoint_namerG  _executor_cacheop_proto_and_checker_makerkOpRoleAttrNameop_role_keyr:  )r  r   expected_placer  s       r0   r  Executor.__init__  s    =&??AN'J"44U;DJ  !#%'"JJL	DJJ!%q!1+-(&+#	%0%9%9*&
"  ./::JJL,1)r/   c                    U R                   UR                  ;   =(       aT    [        UR                  5       U R                      5      [        [        R
                  R                  R                  5      -  $ r3   )r  
attr_namesint	all_attrsr   r  OpRoleOptimize)r  r   s     r0   _is_optimizer_opExecutor._is_optimizer_op6  s[    2==0 ASLLN4++,6
//66??@6A 	Ar/   c                X    U R                  5         U R                  R                  5         g r3   )closer  rc  rV  s    r0   __del__Executor.__del__;  s     	

""$r/   c                    Xl         g r3   )r3  )r  r3  s     r0   	_set_planExecutor._set_planB  s    	r/   c                :    U R                   R                  US 5      $ r3   )r  getr  program_cache_keys     r0   _get_scope_cacheExecutor._get_scope_cacheE  s      $$%6==r/   c                :    U R                   R                  US 5      $ r3   )r  r  r  s     r0   _get_ctx_cacheExecutor._get_ctx_cacheH  s    ""#4d;;r/   c                :    U R                   R                  US 5      $ r3   )r  r  r  s     r0   _get_trainer_cacheExecutor._get_trainer_cacheK      ""&&'8$??r/   c                :    U R                   R                  US 5      $ r3   )r  r  r  s     r0   _get_program_cacheExecutor._get_program_cacheN  r  r/   c                     X R                   U'   g r3   )r  r  r  r   s      r0   _add_program_cacheExecutor._add_program_cacheQ  s    18-.r/   c                :    U R                   R                  US 5      $ r3   )r  r  r  s     r0   _get_pruned_program_cache"Executor._get_pruned_program_cacheT  s    ))--.?FFr/   c                     X R                   U'   g r3   )r  r  s      r0   _add_pruned_program_cache"Executor._add_pruned_program_cacheW  s    8?""#45r/   c                :    U R                   R                  US 5      $ r3   )r  r  r  s     r0   _get_pruned_program_scope_cache(Executor._get_pruned_program_scope_cacheZ  s    //334EtLLr/   c                     X R                   U'   g r3   )r  r  s      r0   _add_pruned_program_scope_cache(Executor._add_pruned_program_scope_cache]  s    >E(():;r/   c                     X R                   U'   g r3   )r  )r  ctx_cache_keyctxs      r0   _add_ctx_cacheExecutor._add_ctx_cache`  s    ),&r/   c                     X R                   U'   g r3   )r  )r  trainer_cache_keyr  s      r0   _add_trainer_cacheExecutor._add_trainer_cachec  s    14-.r/   c                     X R                   U'   g r3   )r  )r  scope_cache_keyr5   s      r0   _add_scope_cacheExecutor._add_scope_cachef  s    -2/*r/   c                     X R                   U'   g r3   )r  )r  r  micro_scopess      r0   _add_micro_scopes_cache Executor._add_micro_scopes_cachei  s    4@01r/   c                :    U R                   R                  US 5      $ r3   )r  r  r  s     r0   _get_micro_scopes_cache Executor._get_micro_scopes_cachel  s    %%))*;TBBr/   c                "    [        SU S35        g )Nz"use_program_cache is force set to z! by FLAGS_FORCE_USE_PROGRAM_CACHE)r  )r  use_program_caches     r0   _log_force_set_program_cache%Executor._log_force_set_program_cacheo  s    01B0CCde	
r/   c           	        UR                  5       nUR                   GH%  nUR                  R                  5       S:X  Ga  UR                  R	                  S5      S   nX'   nUR                  U5      n	U	R                  [        R                  R                  R                  :w  aJ  [        U[        R                  5      (       d   [        XR                  U	R                  5      n[        X5        UR                  R!                  S5      n
Sn[#        U5      U   (       a  [        R$                  " XHXz5        GM  U/nSnUR&                  (       a  SUR&                  ;   a  UR&                  S   S   n[)        UR*                  5      (       a  UR+                  5       S   OUR*                  S   nX-  S:X  d   e[,        R.                  " [,        R0                  " U5      US5      n[3        U5       HN  nUS:  a#  [        X   U R                  U	R                  5      OX   n[        R$                  " UUUX-  U-   5        MP     GM&    g    g )	Nrg   rt   r   r   r6  r   rm  num_micro_batches)r   rv   r^   rw   ry   rf   re   r   rK   rL   STRINGSr;   r?   r   r   rl   r   r   set_feed_variabler  callablerc   rD   splitrE   rQ   )r  r   rg   r   r5   r   r   r   cur_feedrf   r   pir_flag_namemicro_cur_feednum_micro_batch
batch_sizerS   
micro_feeds                    r0   
_feed_dataExecutor._feed_datat  s   ++-""Bww||~'#%77>>%#8#; 1"&&'7899 4 4 < <<%h0@0@AA#0$jj#))$ *#8ggll5) >]+M:**)9 '/ZN&'O--,0E0EE*1*?*?,+-+/
  (77 %NN,Q/!)!2 #
  *;q@@@)+HHX.* #?3
  /2 * . 14::syy "0!2 # ..!&)1A5	 4 g #r/   c                
   [        5       nU H  nUS   nUR                  U5        US   nUS   n	US   n
XrR                  5       ;  a	  U
(       a  MD  X'   n[        U[        R
                  5      (       d  [        XR                  U5      n[        XX5        [        R                  " X;US5        M     [        UR                  5       5       H5  nX;  d  M
  UR                  U5        [        R                  " SU S35        M7     g )Nr   r   r      z
The value r   )r   addr   r;   r   r?   r   r   rq   r$  r>   poprn   ro   )r  r   rg   r5   r  feed_target_namesdata_op_infor   r  r  is_persistabler'  	feed_names                r0   _pir_feed_dataExecutor._pir_feed_data  s    E)L+A!!"23#AH$QI)!_Nyy{2~ -Hh(8(899(::xH%I ""54DaH# *( diik*I1# +ef +r/   c                    [        [        U5      5       Vs/ s H  n[        R                  " X2U5      PM     nnU$ s  snf r3   )rQ   rA   r   get_fetch_variable)r  r   r   r5   rS   outss         r0   _fetch_dataExecutor._fetch_data  sF     3z?+
+ ##E1=+ 	 
 	
s   !<c                   / n/ nS n[        U5       H  u  pV[        U[        5      (       a  U H  nU" X#U5        M     M.  [        U[        5      (       ac  [        US   [        [        45      (       d.  [	        SU SU SU S[        US   5      R                   S3	5      eUS    H  nU" X#U5        M     M  U" X#U5        M     X24$ )a  
Split optimize_ops from fetch_list, which provided to specify program pruning.
Args:
    fetch_list(list): The original fetch_list.
    Possible types of fetch_list are:
        fetch_list = ['loss']
        fetch_list = [[sgd, sgd], 'loss']
        fetch_list = [([sgd, sgd], [(param, grad)]), 'loss']

Returns:
    optimize_ops(list): The optimize operators splited from fetch_list.
    fetch_list(list):  The updated fetch_list which does not contain optimize operators.
c                   [        U[        5      (       a2  UR                  5       (       a  U R                  U5        g [	        S5      e[        U[
        [        45      (       a  UR                  U5        g [	        S[        U5       S35      e)Nz0The operator in fetch_list is not an optimize_opzLThe item in fetch_list should be str, variable or optimize_op, but received .)r;   r   _is_optimize_opr   r   r   r   rw   )_optimize_ops_fetch_listr   s      r0   _get_targets@Executor._split_optimize_ops_in_fetch_list.<locals>._get_targets  s    $))''))!((.#J  D8S/22""4(bcghlcmbnnop r/   r   zRequires fetch_list[z8][0] shall be one of (list, tuple) when type(fetch_list[z']) is `tuple`, but received fetch_list[z][0]'s type is `z`.)r   r;   r>   r   r   rw   r#  )clsr   rB  rC  rD  indexr   rS   s           r0   !_split_optimize_ops_in_fetch_list*Executor._split_optimize_ops_in_fetch_list  s    	 %Z0KE $%%A Q? D%((!$q'D%=99#.ug5mnsmt  u\  ]b  \c  cs  tx  y}  ~  y@  tA  tJ  tJ  sK  KM  N  aA Q? ! ]> 1" ))r/   c                   [        U[        R                  5      nU(       a5  UR                  (       a  UR                  nO[        R
                  " S5        gUn/ n[        U[        5      (       a  [        UR                  5       5      nOK[        U[        [        45      (       a0  [        U5       H!  u  pU[        U	R                  5       5      -  nM#     U(       dN  UR                   H>  n
U
R                   H+  nUR                  5       (       d  M  UR                  U5        M-     M@     X4-   nUR                  X|5      nU(       a4  Xl        [         R"                  " UR$                  5      Ul        SUl        U$ UnU$ )a  
Prune operators and variables which are not needed to generate
:code:`fetch_list` and optimize operators.
Prune operators and variables which are needed
to generate variables to be fed.

Notes: This is a very low level API. Users should not use this API
directly.

Args:
    program(Program): the origin program
    feed(list|dict): feed dict or list.
    fetch_list(list|Variable): A list of variables need to be fetched
    optimize_ops(list[Operator]): A list of optimizer operators

Returns:
    Program:  A new, pruned program.
z[The program holds no _program, maybe it is constructed by graph, which can't be pruned yet.NF)r;   r   r*   r   rn   ro   r   r>   r   r   r   r   rv   rA  r   _prune_with_inputr   Graphr^   r  	_compiled)rF  r   rg   r   optimize_opsr  origin_programr9  rS   r   r{   r   targetspruned_programs                 r0   _prune_programExecutor._prune_program  s4   , gx'?'?@!(!1!1q $N
dD!!diik*JtUm,,$T?d499;//
 + '..))B))++$++B/ $ /
 +'99*N  .!ZZ(;(;<GN %G  %Gr/   c                   [        U[        R                  5      nU(       aD  UR                  (       a  UR                  R	                  5       nO([
        R                  " S5        U$ UR	                  5       n[        U[        5      (       ae  [        UR                  5       5       HF  nUR                  U5      (       a  M  UR                  U5        [
        R                  " SU S35        MH     U$ [        U[        [        45      (       aw  [        U5       Hh  u  pg[        UR                  5       5       HF  nUR                  U5      (       a  M  UR                  U5        [
        R                  " SU S35        MH     Mj     U$ )a  
Update the feed dict, remove the feed item which is pruned in program.

Notes: This is a very low level API. Users should not use this API
directly.

Args:
    program(Program): the pruned program.
    feed(list|dict): feed dict or list.

Returns:
    feed:(list|dict)  updated feed.
z@The program holds no _program, maybe it is constructed by graph.r   r   )r;   r   r*   r   r   rn   ro   r   r>   r   r   r2  r   r   )rF  r   rg   r  r   r6  rS   r   s           r0   _update_feedExecutor._update_feedC  s.    gx'?'?@&//<<>V "//1LdD!!!$))+.	#++I66HHY'MM'	{2lm /  tUm,,$T?!%diik!2I'//	::+ +I;6pq "3 + r/   c                    U R                   (       da  SU l         U R                  R                  5        H!  u  pU R                  R	                  U5        AM#     U R                  R                  5         gg)a  
Close the executor. This interface is used for distributed training (PServers mode).
This executor can not be used after calling the interface, because
this interface releases resources associated with the current Trainer.

Returns:
    None

Examples:

    .. code-block:: python

        >>> import paddle

        >>> cpu = paddle.CPUPlace()
        >>> exe = paddle.static.Executor(cpu)
        >>> # execute training or testing
        >>> exe.close()
TN)r  r  itemsr  release_trainerr  )r  ktrainer_instances      r0   r  Executor.closev  s`    ( ||DL'+':':'@'@'B#&&667GH$ (C ""((* r/   c                    U R                   (       a  gU R                  R                  5        H!  u  pU R                  R	                  U5        AM#     U R                  R                  5         g)z'
flush all trainer param to root_scope
N)r  r  rX  r  rY  rc  )r  r  r[  s      r0   flushExecutor.flush  sV     <<#'#6#6#<#<#>A""223CD  $? 	!!#r/   c
                    g r3   r.   
r  r   rg   r   r   r   r5   r   r  	use_prunes
             r0   r7  Executor.run  s     "%r/   c
                    g r3   r.   ra  s
             r0   r7  rc    s     r/   c
                    g r3   r.   ra  s
             r0   r7  rc    s     14r/   c
                   [         R                  R                  SS5      n
U
b  U
S;   nU R                  U5        [	        5       (       a  U R                  UUUUUUUS9nU$ U R                  UUUUUUUUU	S9	n[        R                  " 5         U$ )a  
Run the specified :code:`Program` or :code:`CompiledProgram`. It should be noted that the executor
will execute all the operators in :code:`Program` or :code:`CompiledProgram` without pruning some
operators of the :code:`Program` or :code:`CompiledProgram` according to fetch_list. And you could
specify the scope to store the :code:`Tensor` during the executor running if the scope
is not set, the executor will use the global scope, i.e. :code:`paddle.static.global_scope()`.

Args:
    program(Program|CompiledProgram): This parameter represents the :code:`Program` or
        :code:`CompiledProgram` to be executed. If this parameter is not provided, that
        parameter is None, the program will be set to :code:`paddle.static.default_main_program()`.
        The default is None.
    feed(list|dict): This parameter represents the input Tensors of the model.
        If it is single card training, the feed is dict type, and if it is multi-card
        training, the parameter feed can be dict or list of Tensors. If the
        parameter type is dict, the data in the feed will be split and sent to
        multiple devices (CPU/GPU), that is to say, the input data will be evenly
        sent to different devices, so you should make sure the number of samples of
        the current mini-batch must be greater than the number of places;
        if the parameter type is list, those data are copied directly to each device,
        so the length of this list should be equal to the number of places.
        The default is None.
    fetch_list(list): This parameter represents the Tensors that need to be returned
        after the model runs. The default is None.
    feed_var_name(str): This parameter represents the name of the input Tensor of
        the feed operator. The default is "feed".
    fetch_var_name(str): This parameter represents the name of the output Tensor of
        the fetch operator. The default is "fetch".
    scope(Scope): the scope used to run this program, you can switch
        it to different scope. default is :code:`paddle.static.global_scope()`
    return_numpy(bool): This parameter indicates whether convert the fetched Tensors
        (the Tensor specified in the fetch list) to numpy.ndarray. if it is False,
        the type of the return value is a list of :code:`DenseTensor`. The default is True.
    use_program_cache(bool): This parameter indicates whether the input :code:`Program` is cached.
        If the parameter is True, the model may run faster in the following cases:
        the input program is :code:`paddle.static.Program`, and the parameters(program, feed Tensor name
        and fetch_list Tensor) of this interface remains unchanged during running.
        The default is False.
    use_prune(bool): This parameter indicates whether the input :code:`Program` will be pruned.
        If the parameter is True, the program will be pruned according to the given feed and fetch_list,
        which means the operators and variables in program that generate :code:`feed` and are not
        needed to generate :code:`fetch_list` will be pruned. The default is False, which means the
        program will not pruned and all the operators and variables will be executed during running.
        Note that if the tuple returned from :code:`Optimizer.minimize()` is passed to :code:`fetch_list`,
        :code:`use_prune` will be overridden to True, and the program will be pruned.

Returns:

    List: The fetched result list.

Examples:

    .. code-block:: python
        :name: code-example-1

        >>> # doctest: +SKIP("This has diff in xdoctest env")
        >>> import paddle
        >>> import numpy

        >>> # First create the Executor.
        >>> paddle.enable_static()
        >>> place = paddle.CPUPlace()  # paddle.CUDAPlace(0)
        >>> exe = paddle.static.Executor(place)

        >>> data = paddle.static.data(name='X', shape=[None, 1], dtype='float32')
        >>> hidden = paddle.static.nn.fc(data, 10)
        >>> loss = paddle.mean(hidden)
        >>> adam = paddle.optimizer.Adam()
        >>> adam.minimize(loss)
        >>> i = paddle.zeros(shape=[1], dtype='int64')
        >>> array = paddle.tensor.array_write(x=loss, i=i)

        >>> # Run the startup program once and only once.
        >>> exe.run(paddle.static.default_startup_program())

        >>> x = numpy.random.random(size=(10, 1)).astype('float32')
        >>> loss_val, array_val = exe.run(
        ...     feed={'X': x},
        ...     fetch_list=[loss.name, array.name]  # type: ignore[union-attr]
        ... )
        >>> print(array_val)
        >>> # doctest: +SKIP("Random output")
        [array(0.16870381, dtype=float32)]
        >>> # doctest: -SKIP

    .. code-block:: python
        :name: code-example-2

        >>> # doctest: +SKIP("This has diff in xdoctest env")
        >>> # doctest: +REQUIRES(env:GPU)
        >>> import paddle
        >>> import numpy as np

        >>> # First create the Executor.
        >>> paddle.enable_static()
        >>> place = paddle.CUDAPlace(0)
        >>> exe = paddle.static.Executor(place)

        >>> data = paddle.static.data(name='X', shape=[None, 1], dtype='float32')
        >>> class_dim = 2
        >>> prediction = paddle.static.nn.fc(data, class_dim)
        >>> loss = paddle.mean(prediction)
        >>> adam = paddle.optimizer.Adam()
        >>> adam.minimize(loss)

        >>> # Run the startup program once and only once.
        >>> exe.run(paddle.static.default_startup_program())
        >>> build_strategy = paddle.static.BuildStrategy()
        >>> binary = paddle.static.CompiledProgram(
        ...     paddle.static.default_main_program(),
        ...     build_strategy=build_strategy
        ... )
        >>> batch_size = 6
        >>> x = np.random.random(size=(batch_size, 1)).astype('float32')

        >>> prediction, = exe.run(
        ...     binary,
        ...     feed={'X': x},
        ...     fetch_list=[prediction.name]
        ... )
        >>> # If the user uses two GPU cards to run this python code, the printed result will be
        >>> # (6, class_dim). The first dimension value of the printed result is the batch_size.
        >>> print("The prediction shape: {}".format(np.array(prediction).shape))
        The prediction shape: (6, 2)

        >>> print(prediction)
        >>> # doctest: +SKIP("Random output")
        [[-0.37789783 -0.19921964]
         [-0.3577645  -0.18863106]
         [-0.24274671 -0.12814042]
         [-0.24635398 -0.13003758]
         [-0.49232286 -0.25939852]
         [-0.44514108 -0.2345845 ]]
        >>> # doctest: -SKIP

FLAGS_FORCE_USE_PROGRAM_CACHEN)r   rt  Trr  rs  )r   rg   r   r   r   r5   r   )	r   rg   r   r   r   r5   r   r  rb  )	r  environr  r  r   _run_pir_impl	_run_implr   update_autotune_status)r  r   rg   r   r   r   r5   r   r  rb  force_use_program_cacheress               r0   r7  rc    s    j #%**..+T#
 #. 7 < ! --.?@==$$%+-) % C, 
 ..%+-)"3# ! 
C '')
r/   c
           	        U R                   (       a  [        S5      eUS L n
Uc
  [        5       nU R                  U5      n[	        U[
        5      (       a  UR                  (       a  UR                  S   n[        R                  " U5      n[        R                  " 5       nUR                  U5        [        R                  " U5      U l        SUR                  ;   a  UR                  S   n[	        U[
        5      (       aF  [        UR                  5       R                   5      S:X  a  U
(       a  Sn["        R$                  " U5        Uc
  ['        5       nUnUnU R)                  U5      u  nnU(       a  Sn	U	(       Ga  [+        XU5      nU R-                  U5      nUc  [	        U[.        R0                  5      (       a  U R3                  [5        [7        U5      5      5      n[8        R8                  " U5      nUUl        U R3                  [5        [7        U5      5      5       c$  U R=                  [5        [7        U5      5      U5        U R?                  XUU5      nU RA                  UU5        OUnU RC                  UU5      nUn[E        XRF                  5      (       Ga  Uc  0 nO6[	        U[H        [J        45      (       a  [        U5      S:X  d   S5       eUS   n[	        U[L        5      (       d  [O        S	[Q        U5       35      eU RC                  X5      n0 n[	        U[.        R0                  5      (       d)  [	        URR                  [.        R0                  5      (       a  [	        U[.        R0                  5      (       a  UOURR                  nURT                  nUb  URV                  (       a  S
S/nU HW  n[X        RZ                  " US5      n[	        U[4        5      (       a  UR]                  5       nUS:X  a  SOSn[_        U5      UU'   MY     [a        [L        Rc                  US5      5        U Rd                  Rg                  UUUUUU RF                  U5      u  nnU Ri                  XXF5        [k        US5      (       Gac  SSK6J7n  [	        URp                  U5      (       d   S5       eURp                  nU" 5       nUR                  5       Rr                  URt                     n[v        Rx                  " U/5      R{                  [}        UR~                  5      5      n [        R                  " UURt                  5      n![        U [        R                  " 5       5      n"[        R                  " 5       (       a  ["        R$                  " S5        OW[        R                  " 5       (       a!  U!R                  U"U!R                  5       5        OU!R                  U"U RF                  5        UR                  [I        UR                  5       5      UU R                  5      n#[a        U5        U#$ [	        U[.        R0                  5      n$U	(       Ga&  U$(       a  UR                  R                  5       n%OUR                  5       n%U%Rr                   H  n&U%R                  R                  U&R                  5       5      n'U%Rr                  U&   n(U'R                  5       SL d  MP  U'RQ                  5       [        R                  R                  R                  :X  d  M  U'R                  5       SL d  M  U(R                  SL d  M  U(R                  SL d  M  U(R                  SL d  M  U&U;  d  M  [        SU& 35      e   [        R                  " X5        UR                  X`RF                  5        UR                  (       d   SUR                   35       eU R                  UR                  U5      $ )N"Attempted to use a closed Executorheter_placestartup_programr   Now you are using default_main_program, but there are no operators in the program to be executed. Please ensure you create model correctly or you can pass the Program or the CompiledProgram manually.Tr   Not compiled with data parallel7feed requires dict as its Parameter. But you passed in FLAGS_new_executor_serial_run!FLAGS_new_executor_sequential_runFrs  rj  LRSchedulermust be LRSchedulerCaution!!! When capturing CUDA Graph, the learning rate scheduler would not take any effect! Please set the learning rate manually before each batch!zNeed feed data for variable z0Program must have _is_inference = True, but get )]r  rB   r   _check_fetch_listr;   r   _heter_pipeline_optr   r  r   r,  r.  r  r  rA   r   rv   rn   ro   r1   rH  r   r  r   r*   r  r   r   rH   _share_vars_fromr  rR  r  rU  r  r   r>   r   r   r   rw   r  r{  sequential_runr  r  lowerboolr   fromkeysr  rf  r-  r~  paddle.optimizer.lrrx  rj  r   	_var_namerD   rE   r   r   re   get_variable_tensorr   CPUPlaceis_cuda_graph_capturingis_compiled_with_ipu
_copy_fromr-  r7  r   r:  r   r^   r   encoder   rK   rL   DENSE_TENSORr_   stop_gradientis_databelong_to_optimizerra   acp_auto_checkpointr}  r  _run_inference	_executor))r  r   rg   r   r   r   r5   r   r  rb  use_default_main_programrp  r  
error_info_origin_fetch_list_origin_programrN  	cache_keycached_pruned_programprogram_scope_cacherQ  stored_flagr  r  schedule_flagflagr  rC  rx  rj  lr_valuelr_varr   rG   
cpu_tensorretr  r   varnamevardescvarobjs)                                            r0   rj  Executor._run_impl  s    <<CDD#*d? ?*,G++J7
gw''G,G,G "55mDK#55kBK

AKK$%)]]1%5D" G$?$??!556GH w((G((*../14'C  j)= NE (!#'#I#I$
 
L I51I %)$B$B9$M!$,gx'?'?@@*.*N*NB/0+' #ii0G/BG,<<? 34   
 <<? 34g "&!4!4:|" ..y.I!6$$^T:D$G$Wjj99|D4-004yA~H'HH~AwdD))MdSWj\Z  $$W3DK'8#;#;<<
 8 8A A
 "'8+C+CDD   !
 "2!A!A!-.2O2O7;%M !. "		$ 6%eS11$)KKME,1VODE,0KD) !. dmmM4@A#33LL

 GW OOG=@w//;!'"6"6DD )D  '33'> --/44\5K5KLxx
+22=3NO11%9O9OP*4A
//11MMd ..00%%j&--/B%%j$**=++TYY[!11C
 k"Jgx'?'?@ &//<<>&335',,&++44W^^5EF%**73 '')U2$,,*>*>*K*KK//1T9,,4$.22e;t+$'CG9%MNN - 	T+

+$$ 	
>w?T?T>UV	
$ ""7#4#4d;;r/   c           
     n   SS K nUR                  R                  n	UR                  R                  R                  n
U R
                  (       a  [        S5      eUS L nU(       a  U
" 5       nU R                  U5      n[        X5      (       aF  [        UR                  5       R                  5      S:X  a  U(       a  Sn[        R                  " U5        Uc
  [        5       nUc  0 nO6[        U[        [         45      (       a  [        U5      S:X  d   S5       eUS   n[        U["        5      (       d  [%        S['        U5       35      eU R(                  R+                  UUUUUU R,                  UU R.                  5      u  nnnU R1                  XXn5        [3        US5      (       Ga_  SSKJn  [        UR8                  U5      (       d   S	5       eUR8                  nU" 5       nUR;                  UR<                  5      n[>        R@                  " U/5      RC                  [E        URF                  5      5      n[        RH                  " [        5       UR<                  5      n[K        U[        RL                  " 5       5      n[        RN                  " 5       (       a  [        R                  " S
5        OW[        RP                  " 5       (       a!  URS                  UURU                  5       5        OURS                  UU R,                  5        URW                  [        URY                  5       5      XpRZ                  5      nU$ )Nr   ro  rr  r   rs  rt  rj  rw  ry  rz  ).r   r	   r   r   r   r  rB   r{  r;   rA   r   rv   rn   ro   r1   r>   r   r   r   rw   r  r  r   r3  r7  r~  r  rx  rj  get_parameter_value_by_namelr_namerD   rE   r   r   re   r  r   r  r  r  r  r-  r7  r   r:  )r  r   rg   r   r   r   r5   r   r   r   r   r  r  rC  r  rx  rj  r  r  r   rG   r  r  s                          r0   ri  Executor._run_pir_implI  s    	**$$%zzCC<<CDD#*d? #*,G++J7
 w((G((*../14'C  j)= NE<DtUm,,t9>D#DD>7D$%%I$t*V    ==JJII	
		
 	G5@7N++7g22K@@ %@ #//L#~H88IF88XJ'..}V\\/JKD--lngooNF&tT]]_=J++--` **,,!!*fmmo>!!*djj9kk|-N-N
 
r/   c                $    UR                  U5      $ r3   )r7  )r  exerg   s      r0   r  Executor._run_inference  s    wwt}r/   c           	       ^ S mS nUc  / $ T" U5      (       a  U/$ U" U5      (       d   S[        U5       S35       e/ n[        U5       H  u  pET" U5      (       a  UR                  U5        M%  U" U5      (       aI  [        U4S jU 5       5      (       a  UR	                  [        U5      5        Mh  UR                  U5        M{  [        SU S[        U5      R                   S35      e   U$ )	Nc                8    [        U [        [        [        45      $ r3   )r;   r   r   r   r   s    r0   <lambda>,Executor._check_fetch_list.<locals>.<lambda>  s    :cHc53I#Jr/   c                .    [        U [        [        45      $ r3   )r;   r   r>   r   s    r0   r  r    s    JsUDM$Br/   zUCurrently , The fetch_list type only should be list or tuple, 
but the input type is z>. For more information please refer to 
the executor.run(...).c              3  4   >#    U  H  nT" U5      v   M     g 7fr3   r.   ).0vis_fetch_vars     r0   	<genexpr>-Executor._check_fetch_list.<locals>.<genexpr>  s     41|As   zRequire fetch_list[z5] 's type shall be one of (Value, str), but received r@  )rw   r   r   allextendr>   r   r#  )r  r   is_tuple_listrm  rS   rf   r  s         @r0   r{  Executor._check_fetch_list  s    JBI
##<Z(( 	
%%)*%5$6 7%%	
( 
+FAC  

3s##4444JJtCy)JJsO)!,abfgjbkbtbtauuvw  , 
r/   c                   [        [        [        U5      5      S-   S5       nUR                  [        U5      5        S S S 5        UR                  (       aN  SUR                  ;   a=  [        SS5       nUR                  [        UR                  S   5      5        S S S 5        g g g ! , (       d  f       Nn= f! , (       d  f       g = f)Nz_train_desc.prototxtw
fleet_desczfleet_desc.prototxt)openr   r   r  
_fleet_opt)r  r   trainerfouts       r0   _dump_debug_infoExecutor._dump_debug_info  s    #bk"%;;SATJJs7|$ B,'2D2D"D+S1T

3w11,?@A 21 #E BA 21s   B%2(B6%
B36
Cc                
   [        UR                  R                  5       5      nXC:  a  Un[        SU SU S35        XCUS   S   -  :  a  [        SXC-   SU S35        XC-  US   S'   UR	                  US   S   U-  5        U$ )Nz/Pipeline training: setting the pipeline num to z" is enough because there are only z filesconcurrency_listr   zBPipeline training: setting the 1st element in concurrency_list to )rA   datasetget_filelistr  
set_thread)r  pipeline_optr  pipeline_numfilelist_lengths        r0   _adjust_pipeline_resource"Executor._adjust_pipeline_resource  s    goo::<=)*LA/ARRt  vE  uF  FL  M L9K,LQ,OOOTUdUtTu  vX  Yh  Xi  io  p  / +,Q/ 	<(:;A>MNr/   c                |
   / n/ nS nSnUR                  5       R                   H  nU R                  U5      (       a    OUR                  S5      (       d  M3  UR	                  S5      S:w  a  UR	                  S5      OUnUb  XG:w  a"  UR                  / 5        UR                  U5        US   R                  U5        UnM     [        U5      nSn	S n
X:  a  X:  a  X9   U:X  a  U	S-  n	X:  a
  X9   U:X  a  M  X:X  a  OX9   n
U	S-  n	U	nSnX:  a'  X9   U
:w  a  X9   U:w  a  SnOU	S-  n	X:  a
  X9   U
:w  a  M  X:X  a  OHU(       d  Mt  [        X5       H)  nX-    H  nUR                  SU
5        M     XU'   US-  nM+     X:  a  M  S n/ n/ n[        U5       HL  n	Ub  XCU	   :w  a$  UR                  / 5        UR                  X9   5        US   R                  X)   5        X9   nMN     [        5       nUR                  5       R                   HP  nUR                  5       R                  U5      nUR                  (       a  M5  UR                  UR                  5        MR     [        U5      n[        5       n[        5       n[        U5       V	s/ s H  n	/ PM     nn	[        U5       H  n	[        5       n[        5       nX    H  nUR                    H4  nUR#                  U5       H  nUU;  d  M  UR                  U5        M     M6     UR$                   H,  nUR'                  U5       H  nUR                  U5        M     M.     M     U	S:X  a  / UU	'   OU	S:X  a  UU-  U-  UU	'   OUU-  UU	'   [(        R*                  " U5      n[(        R*                  " U5      nM     [        U5      n/ n/ n[        U5       V	s/ s H  n	/ PM     nn	Sn/ n[        U5       H  n	UR                  U5        UR                  U[        X   5      -   S-
  5        U[        X   5      -  nXS-
  :  a#  UU	   R                  [-        UU	S-      5      5        UR/                  5       n X   U:w  a=  U R1                  [-        UU	   5      [-        UU	   5      5      n UR                  U 5        M  UR                  U 5        M     U V	s/ s H  n	[-        U	5      PM     n!n	Sn"S n#[        [        U5      5       H%  n	X   n$U$U:w  d  M  U"(       a  [3        S	5        Sn"U	n#M'     U#c  [3        S
5        g UU#   UU#   UU#   U!U#   UU#   /$ s  sn	f s  sn	f s  sn	f )Ncpu	op_device r   r   TFz'only one region of program can be heterzwarning: non heter program)r   rv   r  has_attrr   r   rA   rQ   	_set_attrr  r   r   rf   r   r1  rb   input_namesrx   output_namesry   rH   deepcopyr>   r   rK  r  )%r  r   ops_list	type_listpretype_cpur   cur_attrlrS   
type_heterstartvalidjmerged_ops_listmerged_type_list	data_varsrZ  rf   
inputs_preoutputs_prein_from_prer   r   rx   tmpry   
start_listend_list	send_listsumprogram_listprog	recv_listfoundheter_indexrI   s%                                        r0   split_program_by_device Executor.split_program_by_device  s/   	&&(,,B$$R(({{;'' ww{+r1 GGK(! 
 ;#/OOB'$$X.##B' - 	N
e%ILH4Q %ILH4v"JFAEE%ILJ6<8+!EQ	 %ILJ6 v5_"+BLLj9 &)!Q	 %+ e6 qA{cq\1&&r* ''	5B&&x{3,C  E	%%',,A&&(,,Q/C???chh' -
  U
e#(8,8ar8,qAUFeG%(^^E!xxg-"JJsO  / , !ooF!yy0C(  1 . ) Av!#Aa"-	"9V!CA!,v!5Av.J--0K% ( 
!&q*AR	*qAc"OOC#o&8"99A=>3)**Cq5y!##DQU);$<===?D"h.--Q($y|*< ##D)##D)  '22kT!Wk	2s+,-A #AH}CD . ./ ;'%+&+&[) o -0 +" 3s   	T/6T42T9c	                <   Sn	Sn
UR                   bg  UR                   R                  SS5      S:X  a  Sn	UR                   R                  SS5      S:X  a  Sn	UR                   R                  SS	5      (       a  S
n
Uc
  [        5       nUc  / nUc  / n[        U5      [        U5      :X  d   e[	        U[
        R                  5      nU	(       a  U R                  U5      nU(       d  UR                  (       a$  [        5       R                  UR                  5      nOsUR                  (       a$  [        5       R                  UR                  5      nO>[        5       R                  UR                   5      nUR                  UR                  5        UR                  U5        U	(       a  UR                  W5        OUR                  (       a.  [        5       R                  UR                   R                  5      nOlUR                  (       a.  [        5       R                  UR                   R                  5      nO-[        5       R                  UR                   R                   5      nUR                  UR                   5        US::  af  U
(       a(  UR#                  [        UR                   S   5      5        OHUR$                  S::  a  ['        S5      eUR#                  UR$                  5        OUR#                  U5        UR)                  U5        UR+                  XgU5        X=4$ )Nr   worker_classr  HeterCpuWorkerr   r  HeterXpuTrainer
use_ps_gpuFTworker_placeszSYou should set thread num first, either in Datasetor in Executor.train_from_dataset)r  r  r1   rA   r;   r   r*   r  r  r"   _create_trainerr|  _set_thread_barrier_is_distributed_set_program_set_heter_infor   _set_thread
thread_numrB   
_set_debug_set_fetch_var_and_info)r  r   r  r5   threaddebugr   r   print_periodis_heterr  r  r  r  s                 r0   _prepare_trainerExecutor._prepare_trainerh	  s    
)!!%%nb9=MM!!%%i48II!!%%lE::!
= NEJJ:#j/111gx'?'?@..w7C$$(*::)) ,,(*::// )*::7;M;MN++G,C,CD  )'',$$(*::OO11 ,,(*::OO77 )*::OO..   1Q;##C(:(:?(K$LM##q("8 
 ##G$6$67'5!''
M~r/   c                   UR                   b  SS KnUb  [        S5      e/ nUR                  5       R                  R                  5        H'  nUR                  (       d  M  UR                  U5        M)     UR                  R                  5       R                  S5      nUR                  S5        UR                  S5        UR                  S/5        UR                  U5        GOUR                  Gbp  UR                  S   nUR                  S   nUS:w  a  SUR                  ;  a  SS KnUb  [        S	5      e/ nUR                  5       R                  R                  5        H'  nUR                  (       d  M  UR                  U5        M)     UR                  R                  5       R                  S
5      nUR                  S5        UR                  S5        UR                  S/5        UR                  U5        OUc  [        S5      e[         R"                  " U5      n[$        R&                  " 5       nUR)                  U5        [$        R*                  " U5      U l        OUc  [        S5      eUR/                  5         / nUR                   (       Ga  UR                   S   nU HX  n[1        U[2        5      (       a  UR4                  nOUnUUR                  5       R                  ;   d  MG  UR                  U5        MZ     [7        UR                   S   / USSS9UR                   S'   UR                   S   R9                  S5      nUR:                   HI  nUR<                  S:X  d  M  UR?                  S[$        R@                  RB                  RD                  5        MK     S nU RG                  UUUUUUUU	S9u  nnURI                  U5        URK                  5         UR                   c  UR                  c  U RM                  UUS9  URN                  SL a1  URP                  RN                  (       a  [R        RT                  " S5        URW                  URP                  RX                  5        UR                  S L=(       dW    URZ                  S L=(       aB    URZ                  R]                  SS5      =(       a    URZ                  R]                  SS5      S:H  nUSL a@  U R,                  R_                  UR`                  URc                  5       X2Rd                  5      nOUc  / n[g        US U5      nU Ri                  U5      nUcR  U R,                  R_                  UR`                  URc                  5       X2Rd                  5      nU Rk                  UU5        OURm                  URd                  5        U
by  URo                  S5      n[q        UU
5      nURs                  5         U R,                  Ru                  U5        URw                  5         USL a  U R,                  Ry                  U5        O;U R,                  Ru                  U5        USL a  U R,                  Ry                  U5        UR{                  5         UR}                  5         U(       a:  UR                  S5      R                  5       nUR                  5       n[        U5      $ g )Nr   (dataset should be None for pipeline modeFileInstantDatasetr   Nonepipeline_stagerp  
is_fl_modez.dataset should be None for heter pipeline modeInMemoryDatasetz)dataset is need and should be initializedsection_programrg   r   r   rg   r   r   r   op_roler   r  r5   r  r  r   r   r  r   r  F0dataset should call set_use_ps_gpu in PsGpu moder  dump_fields_pathr  )Cr  r   rB   r   r   valuesr  r   baseDatasetFactorycreate_datasetset_batch_sizer  set_filelistset_use_varr|  r   r  r   r,  r.  r  r  _prepare_to_runr;   r   rb   r   r{   rv   rw   r  r  r  r  r  
_set_infer_gen_trainer_descr  r  
proto_descr	  r
  _dynamic_adjust_before_trainr  r  r  init_for_datasetr^   _descr  r   r  r  ResetDatasetget_worker_scoper!   r  run_from_datasetstoprY  _dynamic_adjust_after_train_finish_to_runr   get_fetch_listr8  r=   )r  r   r  r5   r  is_inferr  r   r   r  fetch_handlerr   r  rf   stage_idrp  r  real_fetch_listreal_programr   r   
main_blockr   r  reused_trainerr[  r  scope0fetch_monitorarrr;  s                                  r0   _run_from_datasetExecutor._run_from_dataset	  s      ,""#MNN I++-2299;;;;$$S) < kk002AA$G ""1%q!  &*	*((4223CDH!55mDK1}w'B'BB!**L 
 !#I&335::AAC;;;%,,S1  D %kk88:II)G **1-&&q)((&2''	2?&C  $55kBK

AKK$%)]]1%5D""#NOO!   "001BCL'	i22%.^^N%.N!\%>%>%@%E%EE#**95 ( 8K--.?@*$&8G!!"34 !../@AGGJJ nn 77g%LL!77>>GG	 % J..!!% / 	
w 	8$!!#  (**2%%gw%G&7+=+=+H+HOONO,,W-?-?-J-JK 44D@ 
d* E""&&|U;E""&&'92>"D 	
 U"&&77LL'--/5//  !
5gtZPI#66yA'#'#9#9#J#JLL'--/5//$  ''	3CD --goo>$%66q9F/FM!""334DE &&&667GH""334DE&&&667GH++- ..)88:C'')GG$$r/   c                  ^^^ TR                   c   eUb   S5       e[        TS T5      nU R                  U5      nU(       a  Ub  U$ SS KmUU4S jnU" 5       nUU4S jnU" 5       u  nnUTR                   S'   S mU R	                  TUUUUTUU	S9u  nnUR                  U5        UR                  5         UR                  SL a1  UR                  R                  (       a  [        R                  " S5        UR                  UR                  R                  5        UR                  5       nU R                  R                  TR                   UX2R"                  5      nUUU/nU(       a  U R%                  X5        U$ )	Nr	  r   c                   > / n TR                  5       R                  R                  5        H'  nUR                  (       d  M  U R	                  U5        M)     TR
                  R                  5       R                  S5      nUR                  S5        UR                  S5        UR                  S/5        UR                  U 5        UR                  5         U$ )Nr
  r   r  )r   r   r  r  r   r  r  r  r  r  r  r  r  )r  rf   r  r   r   s      r0   _get_dataset4Executor._prepare_pipeline_ctx.<locals>._get_datasetz
  s    I++-2299;;;;$$S) < kk002AA$G ""1%q!  &*	*##%Nr/   c                   > TR                   S   n / nT HW  n[        U[        5      (       a  UR                  nOUnX0R	                  5       R
                  ;   d  MF  UR                  U5        MY     [        U / USSS9n U R                  S5      nUR                   HI  nUR                  S:X  d  M  UR                  S[        R                  R                  R                  5        MK     X4$ )Nr  rg   r   r  r   r  )r  r;   r   rb   r   r   r   r   r{   rv   rw   r  r   r  r  r  )r/  r.  r   r   r0  r   r   r   s         r0   _get_real_program_fetch_listDExecutor._prepare_pipeline_ctx.<locals>._get_real_program_fetch_list
  s    "001BCL O'	i22%.^^N%.N!%>%>%@%E%EE#**95 ( /$*$&L &++A.J nn 77g%LL!77>>GG	 %  00r/   r  r  Fr  )r  r   r  r   r  r  r  r  r   r	  r
  r!  r  r#  r  r"  r^   r  r  )r  r   r  r5   r  r+  r  r   r   r  r,  r  r  r  r9  r<  r/  r.  r  trainer_descr[  r   s    `     `             @r0   _prepare_pipeline_ctxExecutor._prepare_pipeline_ctx`
  su    $$000J JJ1'4L	!!),J	 .	1: )E(F%o3?/0
..!!% / 	
w 	8$!!# &7+=+=+H+HOONO,,W-?-?-J-JK}}11BBLL,
 o'78	/
r/   c                   UR                  5       nUR                  5       nX5R                  ;   a  UR                  U5      nO3UR	                  U[
        R                  R                  R                  SS9n[        XRU5      (       dq  [        U5       Hb  u  pxUR                  U5      (       a-  UR                  U5      n	UR                  SSU/0SU	/0SU0S9  MH  [        R                  " SU S	35        Md     U$ )
NTr   rg   rs   rt   r   r   r   r   )r   r   r   rf   r   r   rK   rL   r   r   r   r   r   rn   ro   )
r  r   rg   r   r   r   r   rS   rb   r   s
             r0   _add_feed_opsExecutor._add_feed_ops
  s    mmo"//1---#''6H#.."\\))88  / H ",mDD$T?''--&**40C ,,# #hZ0!&$aj	 -  MM'v-gh + r/   c                   UR                  5       nUR                  5       nX6R                  ;   a  UR                  U5      nO3UR	                  U[
        R                  R                  R                  SS9nU(       a  SnOSn[        XbX85      (       d_  [        U5       HP  u  p[        U
[        [        45      (       d   SU	 S[        U
5       35       eUR                  USU
/0SU/0S	U	0S
9  MR     U$ )NTr   r   r   r   r   rs   rt   r   r   )r   r   r   rf   r   r   rK   rL   r   r   r   r;   r   r   rw   r   )rF  r   r   r   r   r   r   r   r   rS   rf   s              r0   _add_fetch_opsExecutor._add_fetch_ops
  s	    mmo"//1...$((8I$//#\\))44  0 I !HH #n
 
 $J/!##77 03tCykB7 &&!#<"YK0 !*	 ' 	 0 r/   c                   UR                  5       nUR                  5       n[        UR                  5      n[	        [        U5      5       H3  nUR                  U   R                  U:X  d  M"  UR                  U5        M5     U$ r3   )r   r   rA   rv   reversedrQ   rw   
_remove_op)rF  r   fetch_op_namer   r   op_numr   s          r0   _remove_fetch_opsExecutor._remove_fetch_ops  sm    mmo"//1\%%&E&M*C$))]:'', + r/   c                   U R                  UUUUUUUUU	U
U5      u  p<nSSKJn  [        US5      (       a  UR                  n[        X5      (       d   S5       eU" 5       nUR                  5       R                  UR                     n[        R                  " U/5      R                  [        UR                  5      5      n[        R                  " X?R                  5      nUR!                  UU R"                  5        U R$                  R'                  U5        U(       d  U R$                  R)                  U5        U(       a:  UR+                  S5      R-                  5       nUR/                  5       n[1        U5      $ g )Nr   rw  rj  ry  r   )r?  r  rx  r~  rj  r;   r   r   r  rD   rE   r   r   re   r   r  r   r   r  r&  rY  r   r*  r8  r=   )r  r   r  r5   r  r+  r  r   r   r  r,  r  r.  r[  rx  rj  r  r  r   rG   r4  r;  s                         r0   _run_pipelineExecutor._run_pipeline   sD    483M3M4
0 0 	47N++"//Ll88O:OO8#~H))+001G1GHF88XJ'..}V\\/JKD--e5K5KLFJJtTZZ(//0@A ""223CD..)88:C'')GG$$r/   c
                6    U R                  UUUUSUUUUU	5
      $ )a  
Infer from a pre-defined Dataset. Dataset is defined in paddle.base.dataset.
Given a program, either a program or compiled program, infer_from_dataset will
consume all data samples in dataset. Input scope can be given by users. By default,
scope is global_scope(). The total number of thread run in training is `thread`.
Thread number used in training will be minimum value of threadnum in Dataset and
the value of thread in this interface. Debug can be set so that executor will display
Run-Time for all operators and the throughputs of current infer task.

The document of infer_from_dataset is almost the same as train_from_dataset,
except that in distributed training, push gradients will be disabled in infer_from_dataset.
infer_from_dataset() can be used for evaluation in multi-threadvery easily.

Args:
    program(Program|CompiledProgram): the program that needs to be run,
        if not provided, then default_main_program (not compiled) will be used.
    dataset(paddle.base.Dataset): dataset created outside this function,
        a user should provide a well-defined dataset before calling this function.
        Please check the document of Dataset if needed. default is None
    scope(Scope): the scope used to run this program, you can switch it to different scope
        for each run. default is global_scope
    thread(int): number of thread a user wants to run in this function. Default is 0, which
        means using thread num of dataset
    debug(bool): whether a user wants to run infer_from_dataset, default is False
    fetch_list(Tensor List): fetch Tensor list, each Tensor will be printed during
        training, default is None
    fetch_info(String List): print information for each Tensor, default is None
    print_period(int): the number of mini-batches for each print, default is 100
    fetch_handler(FetchHandler): a user define class for fetch output.

Returns:
    None

Examples:

    .. code-block:: python

        >>> import paddle

        >>> paddle.enable_static()
        >>> place = paddle.CPUPlace()  # you can set place = paddle.CUDAPlace(0) to use gpu
        >>> exe = paddle.static.Executor(place)
        >>> x = paddle.static.data(name="x", shape=[None, 10, 10], dtype="int64")
        >>> y = paddle.static.data(name="y", shape=[None, 1], dtype="int64", lod_level=1)
        >>> dataset = paddle.base.DatasetFactory().create_dataset()
        >>> dataset.set_use_var([x, y])
        >>> dataset.set_thread(1)
        >>> # you should set your own filelist, e.g. filelist = ["dataA.txt"]
        >>> filelist = [] # type: ignore[var-annotated]
        >>> dataset.set_filelist(filelist)
        >>> exe.run(paddle.static.default_startup_program())
        >>> exe.infer_from_dataset(program=paddle.static.default_main_program(),
        ...                         dataset=dataset)
Tr5  
r  r   r  r5   r  r  r   r   r  r,  s
             r0   infer_from_datasetExecutor.infer_from_datasetS  s6    D %%
 	
r/   c                8   U R                  US USUUUUS9u  p(UR                  S5        UR                  5         U R                  XS9  U R                  R                  UR                  UR                  5       US 5      n	U R                  R                  U	5        U	$ )Nr   r  Fr  )	r  r  r  r  r  r"  r^   r#  r&  )
r  r   r5   r  r   r   r  r,  r  r[  s
             r0   start_heter_trainerExecutor.start_heter_trainer  s     ..!!% / 	
 	5!!!#g?11BBLL'--/5$
 	//0@A  r/   c
                6    U R                  UUUUSUUUUU	5
      $ )ap
  
Train from a pre-defined Dataset. Dataset is defined in paddle.base.dataset.
Given a program, either a program or compiled program, train_from_dataset will
consume all data samples in dataset. Input scope can be given by users. By default,
scope is global_scope(). The total number of thread run in training is `thread`.
Thread number used in training will be minimum value of threadnum in Dataset and
the value of thread in this interface. Debug can be set so that executor will display
Run-Time for all operators and the throughputs of current training task.

Note: train_from_dataset will destroy all resources created within executor for each run.

Args:
    program(Program|CompiledProgram): the program that needs to be run,
        if not provided, then default_main_program (not compiled) will be used.
    dataset(paddle.base.Dataset): dataset created outside this function,
        a user should provide a well-defined dataset before calling this function.
        Please check the document of Dataset if needed.
    scope(Scope): the scope used to run this program, you can switch it to different scope
        for each run. default is global_scope
    thread(int): number of thread a user wants to run in this function. Default is 0, which
        means using thread num of dataset
    debug(bool): whether a user wants to run train_from_dataset
    fetch_list(Tensor List): fetch Tensor list, each variable will be printed
        during training
    fetch_info(String List): print information for each Tensor, its length should be equal
        to fetch_list
    print_period(int): the number of mini-batches for each print, default is 100
    fetch_handler(FetchHandler): a user define class for fetch output.

Returns:
    None

Examples:

    .. code-block:: python

        >>> import paddle

        >>> paddle.enable_static()
        >>> place = paddle.CPUPlace() # you can set place = paddle.CUDAPlace(0) to use gpu
        >>> exe = paddle.static.Executor(place)
        >>> x = paddle.static.data(name="x", shape=[None, 10, 10], dtype="int64")
        >>> y = paddle.static.data(name="y", shape=[None, 1], dtype="int64", lod_level=1)
        >>> dataset = paddle.base.DatasetFactory().create_dataset()
        >>> dataset.set_use_var([x, y])
        >>> dataset.set_thread(1)
        >>> # you should set your own filelist, e.g. filelist = ["dataA.txt"]
        >>> filelist = [] # type: ignore[var-annotated]
        >>> dataset.set_filelist(filelist)
        >>> exe.run(paddle.static.default_startup_program())
        >>> exe.train_from_dataset(program=paddle.static.default_main_program(),
        ...                         dataset=dataset)
FrR  rS  s
             r0   train_from_datasetExecutor.train_from_dataset  s6    B %%
 	
r/   )r  r  r  r  r  r  r:  r  r  r   r3  r  r  r  r  r  r  r3   )r   zPlaceLike | NonerE  r  )rE  r  )r  r>   )NNN)	.........)r    Program | CompiledProgram | Nonerg   ;dict[str, npt.NDArray[Any]] | list[npt.NDArray[Any]] | Noner   ,str | Tensor | Sequence[str | Tensor] | Noner   r   r   r   r5   core._Scope | Noner   zLiteral[True]r  r  rb  r  rE  zlist[npt.NDArray[Any]])r   r\  rg   r]  r   r^  r   r   r   r   r5   r_  r   zLiteral[False]r  r  rb  r  rE  zlist[Tensor])r   r\  rg   r]  r   r^  r   r   r   r   r5   r_  r   r  r  r  rb  r  rE  z%list[Tensor] | list[npt.NDArray[Any]])	NNNrg   r   NTFF)NN)r   r   rE  zlist[int] | None)NNNr   FNNd   )
NNNr   FFNNr`  N)NNNr   FFNNr`  NFFr   )	NNNr   FNNr`  N)r   r\  r  z&DatasetBase | _FleetDatasetBase | Noner5   r_  r  r  r  r  r   list[Tensor] | Noner   list[str] | Noner  r  r,  FetchHandler | NonerE  r  )NNFNNr`  N)r   zProgram | Noner5   r_  r  r  r   rc  r   rd  r  r  r,  re  rE  zcore.TrainerBase)6r#  r$  r%  r&  __doc____annotations__r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r-  r7  r<  classmethodrH  rR  rU  r  r^  r   r7  rj  ri  r  r{  r  r  r  r  r5  r?  rB  rE  rL  rO  rT  rW  rZ  r(  r.   r/   r0   r  r    sC   =~ M2>A
%><@@9G@MF-53AC

6p< 1* 1*f ?C; ;z * *X+6	$  58LOCF !$'&)"%%1% J% A	%
 % % "% $%  % % 
 % %  58LOCF !$''*"%1 J A	
   " %    
   58LOCF !$' "%414 J4 A	4
 4 4 "4 4  4 4 
/4 4 xtG<R_B@B"AJ L` hX l\@ ?D$ $L   1j 59:>$(*.'+-1M
1M
 8M
 "	M

 M
 M
 (M
 %M
 M
 +M
 
M
b #'$(*.'+-1* *  "*  	* 
 (*  %*  *  +*  
* \ 59:>$(*.'+-1L
1L
 8L
 "	L

 L
 L
 (L
 %L
 L
 +L
 
L
 L
r/   r  )rE  core._Scope)r5   ri  rE  ri  )r5   ri  rE  zGenerator[None, None, None]ra  )r   rb  )r   )NTr3   )f
__future__r   rH   r	  r  r  rn   	functoolsr   typingr   r   r   r   numpyrD   r   r	   paddle.base.frameworkr
   paddle.base.libpaddle.pirr   r   r   r   r   r   r  r   r   r   r   data_feederr   r   r   r   r   r   r   r   r   r   incubate.checkpointr    r  trainer_factoryr!   r"   wrapped_decoratorr#   collections.abcr$   r%   numpy.typingnptr&   paddle._typingr'   paddle._typing.device_liker(   paddle.base.datasetr)   (paddle.distributed.fleet.dataset.dataset_FleetDatasetBasepaddle.staticr*   __all__Scoper-   NativeConfigInferNativeConfigAnalysisConfigInferAnalysisConfigr1   r7   r9   r=   rO   rT   rl   rq   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r*  rG  r  r.   r/   r0   <module>r     s   #   	 
   8 8   . 5  5 4 &   8 @ <3(1/ .

**,%% )) , ' 'T+\$ F+\,^%R 7>*\ 7D*/\ LQ=@'0#$7D0
(
,<1h,  
 
8+ +\@/ @/FE
 E
r/   