o
    Me|                    @   s  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZddl	m
Z
 d dlZddlmZ ddlmZmZmZmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ d dlZddlmZ ddlm Z! ddlm"Z" d dl#m$Z$ g dZ%e& a'ej(Z)ej*Z+dd Z,dd Z-e
dd Z.dGddZ/dd Z0dd  Z1dHd!d"Z2d#d$ Z3	%dId&d'Z4	dGd(d)Z5d*d+ Z6dJd-d.Z7d/d0 Z8d1d2 Z9d3d4 Z:d5d6 Z;d7d8 Z<d9d: Z=d;d< Z>dKd=d>Z?G d?d@ d@e@ZAG dAdB dBe@ZBG dCdD dDe@ZCG dEdF dFe@ZDdS )L    )print_functionN   )signature_safe_contextmanager)convert_dtype)Programdefault_main_programVariableOperator)convert_np_dtype_to_dtype__apply_pass)core)unique_name)compiler   )compat)TrainerFactory)FetchHandlerMonitor)	framework)auto_checkpoint)_prune_feed_ops)	lru_cache)Executorglobal_scopescope_guardc                   C   s   t S )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 r   r   ED:\Projects\ConvertPro\env\Lib\site-packages\paddle/fluid/executor.pyr   1   s   r   c                 C   s   t }| a |S Nr   scopeexr   r   r   _switch_scopeG   s   r"   c                 c   s*    t | }z
dV  W t | dS t | w )a  
    
    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())
    N)r"   r   r   r   r   r   N   s
   "r   Fc                    s   t | tjr fdd| D S t | tr fdd| D S t | tjs%J |  }t|dkr3td|  rC r>t	
| S t	| S dS )a   
    Convert a Tensor to a numpy.ndarray, its only support Tensor without LoD information.
    For higher dimensional sequence data, please use LoDTensor directly.

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          import numpy

          new_scope = fluid.Scope()
          with fluid.scope_guard(new_scope):
              fluid.global_scope().var("data").get_tensor().set(numpy.ones((2, 2)), fluid.CPUPlace())
          tensor = new_scope.find_var("data").get_tensor()
          fluid.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
    c                       g | ]}t | qS r   as_numpy.0tcopyr   r   
<listcomp>       zas_numpy.<locals>.<listcomp>c                    r#   r   r$   r&   r)   r   r   r+      r,   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 LoDTensor itself directly.N)
isinstancer   ZLoDTensorArraylist	LoDTensorlodlenRuntimeErrorZ_is_initializednparrayZasarray)tensorr*   r0   r   r)   r   r%   w   s   


r%   c                 C   s4   t | tjjst| } t |tjjst|}| |kS )a  
    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secondr   r   r   dtype_is_compatible_with   s
   r:   c                 C   st   t | }|t |krdS t|D ]'}| | du s| | dk rq|| du s+|| dk r,q| | || kr7 dS qdS )aw  
    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.
    FNr   T)r1   range)r8   r9   Zdim_lenir   r   r   dimension_is_compatible_with   s   r=   c                 C   s   | j  rUt|| j |}|dur td| jt| j| j|f t|	 | j
sUt| j
tjjr5t| j
n| j
}t|	 tjjrGt|	 n|	 }td| j||f dS )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 (LoDTensor): the fed value, which must be a LoDTensor
        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
    NzeThe fed Variable %r should have dimensions = %d, shape = %r, but received fed shape %r on each devicez<The data type of fed Variable %r must be %r, but received %rT)descneed_check_feedr   Zdiff_tensor_shape
ValueErrornamer1   shaper:   Z_dtypedtyper-   r6   r7   r   )varfeedZ
num_placesZ
diff_shapeZvar_dtype_formatZfeed_dtype_formatr   r   r   check_feed_shape_type   s2   


rF   c                 C   s   d}| j D ]-}|j dkr2|d7 }|jdd |ksJ |jdd }||vr1td|q |dkrA|t|krAtd|dkS )a   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<LoDTensor>.

    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   rE   r   XOutz('feed_targets' does not have {} variablez:Feed operators in program desc do not match 'feed_targets')opsr>   typeinputoutput	Exceptionformatr1   )blockZfeed_targetsZfeed_holder_nameZ
feed_countopfeed_target_namer   r   r   has_feed_operators   s&   
rR   fetchc                 C   s   d}| j D ]B}|j |krG|d7 }|jdd |ksJ |jdd }|dd |D vr6td||jd}||| j ksGJ q|dkrV|t	|krVtd	|dkS )
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<LoDTensor>.
        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   rH   rG   c                 S   s   g | ]}|j  qS r   )r>   rA   )r'   rD   r   r   r   r+   F  s    
z'has_fetch_operators.<locals>.<listcomp>z)'fetch_targets' does not have {} variablecolz<Fetch operators in program desc do not match 'fetch_targets')
rI   r>   rJ   rL   rK   rM   rN   attrrA   r1   )rO   Zfetch_targetsZfetch_holder_namefetch_opZfetch_countrP   Zfetch_target_nameidxr   r   r   has_fetch_operators'  s,   
rX   c                 C   sJ  |   }| }||jv r||}n|j|tjjjdd}||jv r)||}	n|j|tjjj	dd}	t
|||sft|D ]'\}
}||r^||}|jdd|gid|gid|
id q>td|  q>|rkd	}nd
}t||||st|D ]*\}
}t|tst|tjsJ d|
t|f |j|d|gid|	gid|
id qx|S )NTrA   rJ   persistablerE   rG   rH   rT   rJ   ZinputsZoutputsattrsIThe variable %s is not found in program. It is not declared or is pruned.fetch_v2rS   !Wrong type for fetch_list[%s]: %s)cloneglobal_blockvarsrD   
create_varr   r6   r7   FEED_MINIBATCH
FETCH_LISTrR   	enumeratehas_var_prepend_opwarningswarnrX   r-   r   sixstring_typesrJ   	append_op)programrE   
fetch_listfeed_var_namefetch_var_nameuse_fetch_v2tmp_programra   feed_var	fetch_varr<   rA   outrV   rD   r   r   r   _add_feed_fetch_opsT  sd   




rw   c           	      C   sj   t  rdnd}||d}ddd}t }|r!d}t| |||| |r1|r3d}t| |||| d S d S d S )NTF)use_cudaZmem_opt_skip_varsboolz	list[str]Zbuffer_shared_inplace_passZinplace_addto_op_pass)r   Zis_compiled_with_cudar   r   )	rn   enable_inplaceenable_addtoskip_var_namesrx   r\   Z
attr_typesZempty_startup_programZ	pass_namer   r   r   _apply_inplace_addto_pass  s   



r}   Tc                 C   sp   t | tjsJ |du rt }t |tjsJ |t| }|dus*J d|  d | }|r6t	|dd}|S )aR  
    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:
       LodTensor|numpy.ndarray
    NzCannot find zm in scope. Perhaps you need to make the variable persistable by using var.persistable = True in your program.Tr)   )
r-   rk   rl   r   r   Z_Scopefind_var_to_name_strZ
get_tensorr%   )rA   r    return_numpyrD   r5   r   r   r   
_fetch_var  s   

r   c                    sH   dd  t | tr| d } t | tr  fdd| D }d|S  | S )Nc                 S   s\   t | tr
| j S t | tr| S t | tjrt| S t | tr&tt| S t	t| d )Nz$ should be Variable, Operator or str)
r-   r   r>   rA   strrk   rl   r	   id	TypeErrorrD   r   r   r   _to_str  s   



z_to_name_str.<locals>._to_strr   c                    s   g | ]} |qS r   r   )r'   itemr   r   r   r+         z _to_name_str.<locals>.<listcomp>,)r-   tupler.   join)rD   sr   r   r   r     s   


r   c                   C   s   t jd u p	t jdv S Nr   1TTruetrue)r   Z_enable_standalone_executor_r   r   r   r   _is_enable_standalone_executor  s   r   c                   C   s
   t jdv S r   )r   Z"_dy2st_enable_standalone_executor_r   r   r   r   $_is_dy2st_enable_standalone_executor     
r   c            
      C   s   ddl m}  tdd}|d}|  }ttdd}||_t|}t	|D ]\}}| 
 }||_||_|j| q(t| }	|	S )Nr   )fleet_executor_desc_pb2PADDLE_TRAINER_ENDPOINTS r   PADDLE_TRAINER_IDr   )Zdistributed.fleet.protor   osgetenvsplitZFleetExecutorDescintcur_rankr1   rf   ZRankInforankZip_portZcluster_infoappendr   ZFleetExecutorZSerializeToString)
r   Ztrainer_endpoints_strtrainer_endpointsZfleet_exe_descr   nrankr   ZendpointZ	rank_infoZ	fleet_exer   r   r   _prepare_fleet_executor  s   
r   c                 C   s   | j  t|| S r   )r>   Zcached_hash_str_get_program_cache_key)rn   rE   ro   r   r   r   )_get_strong_program_cache_key_for_new_exe  s   
r   c                 C   sB   dd }t | tjr| jn| }||jd tt|  t|| S )Nc                 S   s,   g }t | j D ]}|| q	d|S )N
)r.   rb   keysr   r   )rO   Z	block_strvar_namer   r   r   _get_varname_from_block   s   
z>_get_strong_program_cache_key.<locals>._get_varname_from_blockr   )r-   r   CompiledProgram_programblocksr   r   r   )rn   rE   ro   r   inner_programr   r   r   _get_strong_program_cache_key  s   
r   c                 C   sl   g }t | trt|  }nt | tst | tr)t| D ]\}}|t| 7 }qttt|}t|| S r   )	r-   dictr.   r   r   rf   mapr   r   )rE   ro   Zfeed_var_namesr<   eachfetch_var_namesr   r   r   r     s   
r   c                 C   s   t | tjsO|dusJ dt |tjjrt|n|}t| r*t| g	|} n%t | t
tfrFt| } | jtjkr@td| 	|} n	tdt| t }|| | |S )a  
        Convert numpy.ndarray to Tensor, its only support Tensor without LoD information.
        For higher dimensional sequence data, please use LoDTensor directly.

        Examples:
            >>> import paddle.fluid as fluid
            >>> place = fluid.CPUPlace()
            >>> exe = fluid.executor(place)
            >>> data = np.array(size=(100, 200, 300))
            >>> np_outs = map(lambda x: fluid.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(core.VarDesc.VarType|str): the expected data type of created tensor

        Returns:
            LoDTensor
        Nz:The dtype should be given when feed data is not np.ndarrayz
	Faild to convert input data to a regular ndarray :
	* Usually this means the input data contains nested lists with different lengths. Please consider using 'fluid.create_lod_tensor' to convert it to a LoD-Tensor.z2Convert data of type {} to Tensor is not supported)r-   r3   ndarrayr   r6   r7   r   Zisscalarr4   astyper.   r   rC   Zobject_r   rN   rJ   r/   set)dataplacerC   r5   r   r   r   _as_lodtensor  s0   

r   c                   @   s*   e Zd Zd	ddZdd Zedd ZdS )
FetchHandlerN<   c                 C   s   |d ksJ || _ || _d S r   )var_dictperiod_secs)selfr   r   r   r   r   __init__I  s   
zFetchHandler.__init__c                 C   sH   |D ]}t || tju rtjd||| d  qtjd d S )Nz
{}[0]: {} r   r   )rJ   r3   r   sysstdoutwriterN   )r   res_dictkeyr   r   r   handlerN  s
   zFetchHandler.handlerc                   C   s   t d d S )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   r   r   helpT  s   zFetchHandler.help)Nr   )__name__
__module____qualname__r   r   staticmethodr   r   r   r   r   r   G  s
    
r   c                   @   s6   e Zd Zdd ZdddZdd Zdd	 Zd
d ZdS )_StandaloneExecutorc                 C   s0   t  | _| j| || _|| _|  | _d S r   )r   Place_place	set_place_main_programZ_scope_create_new_executor_new_exe)r   r   Zmain_programr    r   r   r   r   d  s
   
z_StandaloneExecutor.__init__Tc                 C   s2   |  |}| j||| }|rt|ddS |S )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:`LoDTensor`. The default is True.
        Tr)   )_check_fetchr   run_move_to_listr%   )r   r    
feed_namesro   r   tensorsr   r   r   r   k  s   


z_StandaloneExecutor.runc                 C   s   t | j| jj}|S r   )r   ZStandaloneExecutorr   r   r>   )r   new_exer   r   r   r   ~  s   z(_StandaloneExecutor._create_new_executorc                 C   s   |du ri }nt |ttfrt|dksJ d|d }t |ts)tdt| | j }t|	 D ]}|
|sG|| td|  q4|S )a6  
        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:
            feed(list|dict): feed dict or list.

        Returns:
            feed:(list|dict)  updated feed.
        Nr   Not compiled with data parallelr   9feed requires dict as its Parameter. But you passed in %sr]   )r-   r.   r   r1   r   r   rJ   r   ra   r   rg   popri   rj   )r   rE   ra   	feed_namer   r   r   _update_feed  s,   



z _StandaloneExecutor._update_feedc                 C   sX   |d u rg }g }|D ]}t |tr|j}nt |ts$tdt|j|| q
|S )Nz9Required fetch_var shall be str|Variable, but received {})	r-   r   rA   r   r   rN   rJ   r   r   )r   ro   resru   r   r   r   r     s   

z _StandaloneExecutor._check_fetchN)T)r   r   r   r   r   r   r   r   r   r   r   r   r   b  s    
"r   c                   @   s<   e Zd ZG dd deZdd Zdd Zdd Zd	d
 ZdS )_ExecutorCachec                   @   s$   e Zd Zdd Zdd Zdd ZdS )z_ExecutorCache._CachedDatac                 C   s   || _ || _|| _|| _|| _|| _|| _t| j tj	r8| j j
s+t| j j | j _
tt| j j
||| _d S tt| j ||| _d S r   )rn   rE   ro   rp   rq   r   r    r-   r   r   r   r   IrGraph_graph
to_programhashr   r   r   rn   rE   ro   rp   rq   r   r    r   r   r   r     s0   


z#_ExecutorCache._CachedData.__init__c                 C   s   t |tjo| j|jkS r   )r-   r   _CachedDatar   )r   otherr   r   r   __eq__  s
   
z!_ExecutorCache._CachedData.__eq__c                 C   s   | j S r   )r   r   r   r   r   __hash__  s   z#_ExecutorCache._CachedData.__hash__N)r   r   r   r   r   r   r   r   r   r   r     s    r   c                 C   s   t dd| j| _d S )N   )maxsize)r   _get_program_and_executor _get_cached_program_and_executorr   r   r   r   r     s   
z_ExecutorCache.__init__c                 C      | j   d S r   )r   cache_clearr   r   r   r   clear     z_ExecutorCache.clearc                 C   s   |  | |||||||S r   )r   r   r   r   r   r   get_program_and_executor  s
   z'_ExecutorCache.get_program_and_executorc                 C   s  |j }t|tjr|jn|}|j}|j}|j}|j}|j	}|j
}	t|tjs-t|jtjrWt|tjr5|n|j}
|
j}|
|	| t|
j}| }t|drT|j|_|}nd }ddlm}m} | rl|t krl|  |}t|||||dd}tjdd dv r|js|jdkrtd	 n|jdkrtd
 ntd |d u s|jrdnd}|d ur|j rdnd}|s|rt!t"||}t#|||| |$ }t%|||	}||fS )Nlr_shedulerr   )prim_enabled	prim2origT)rn   rE   ro   rp   rq   rr   FLAGS_CONVERT_GRAPH_TO_PROGRAMr   r   z'There are more than 1 block in program.zThere are 1 block in program.zThere are no block in program.F)&rn   r-   r   r   r   rE   ro   rp   rq   r   r    r   _build_strategy_compiler   r   r   hasattrr   Zpaddle.incubate.autogradr   r   r   rw   r   environgetZ_is_start_up_program_Z
num_blocksloggingwarningrz   r{   evalr   r}   r`   r   )r   Zcached_datarn   r   rE   ro   rp   rq   r   r    compiled_programZbuild_strategyZir_graphZconverted_programr   r   rz   r{   r|   Znew_programr   r   r   r   r     sr   




z(_ExecutorCache._get_program_and_executorN)	r   r   r   objectr   r   r   r   r   r   r   r   r   r     s    #r   c                   @   sF  e Zd ZdZd\ddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Ze dd  Zd!d" Zd#d$ Zed%d& Ze			d]d'd(Zed)d* Z	 d+d, Zd-d. Z				/	0		1	2	1	2d^d3d4Zd5d6 Zd7d8 Zd9d: Zd;d< Z d_d=d>Z!d?d@ Z"				A	2			Bd`dCdDZ#				A	2	2			B	dadEdFZ$				A	2	2			B		2dbdGdHZ%	I				2dcdJdKZ&			/	0		2dddLdMZ'dNdO Z(e	2dedPdQZ)edfdRdSZ*				A	2	2			B		2dbdTdUZ+				A	2			B	dgdVdWZ,			2			B	dhdXdYZ-				A	2			B	dgdZd[Z.dS )ir   a'  
    :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.
            # NOTE: If you use CPU to run the program or Paddle is
            # CPU version, you need to specify the CPU_NUM, otherwise,
            # PaddlePaddle will use all the number of the logic core as
            # the CPU_NUM, in that case, the batch size of the input
            # should be greater than CPU_NUM, if not, the process will be
            # failed by an exception.

            # Set place explicitly.
            # if not use_cuda:
            #     os.environ['CPU_NUM'] = str(2)

            # If you don't set place and PaddlePaddle is CPU version
            os.environ['CPU_NUM'] = str(2)

            compiled_prog = paddle.static.CompiledProgram(
                train_program).with_data_parallel(loss_name=loss.name)
            loss_data, = exe.run(compiled_prog, feed={"X": x}, fetch_list=[loss.name])

    Nc                 C   s   |d u rt  }|| _nt || _t | _t | _t | _t | _t | _	t | _
t }|| j t|| _d| _t | _d| _td| _t | _t | _d | _d| _d S )NFZ__auto_checkpoint_executor__)r   Z_current_expected_placer   _get_paddle_placer   program_caches
ctx_cachestrainer_cachesscope_cachesZ
var_cachespruned_program_cachesr   r   r   r   _default_executor_closedpruned_program_scope_cachesZ_prepare_to_run_calledr   generateZ_auto_checkpoint_namer   _enable_interpreter_corer   _executor_cache_fleet_executor_fleet_executor_with_standalone)r   r   Zexpected_placepr   r   r   r   |  s.   
zExecutor.__init__c                 C   r   r   )r  r   r   r   r   r   __del__  s   zExecutor.__del__c                 C      | j |d S r   )r  r   r   program_cache_keyr   r   r   _get_scope_cache  r   zExecutor._get_scope_cachec                 C   r  r   )r  r   r  r   r   r   _get_ctx_cache  r   zExecutor._get_ctx_cachec                 C   r  r   )r  r   r  r   r   r   _get_trainer_cache  r   zExecutor._get_trainer_cachec                 C   r  r   )r  r   r  r   r   r   _get_program_cache  r   zExecutor._get_program_cachec                 C      || j |< d S r   )r  r   r  rn   r   r   r   _add_program_cache  r   zExecutor._add_program_cachec                 C   r  r   )r  r   r  r   r   r   _get_pruned_program_cache  r   z"Executor._get_pruned_program_cachec                 C   r  r   )r  r  r   r   r   _add_pruned_program_cache  r   z"Executor._add_pruned_program_cachec                 C   r  r   )r  r   r  r   r   r   _get_pruned_program_scope_cache  r   z(Executor._get_pruned_program_scope_cachec                 C   r  r   )r  r  r   r   r   _add_pruned_program_scope_cache  r   z(Executor._add_pruned_program_scope_cachec                 C   r  r   )r  )r   Zctx_cache_keyctxr   r   r   _add_ctx_cache  r   zExecutor._add_ctx_cachec                 C   r  r   )r  )r   Ztrainer_cache_keyr  r   r   r   _add_trainer_cache  r   zExecutor._add_trainer_cachec                 C   r  r   )r  )r   Zscope_cache_keyr    r   r   r   _add_scope_cache  r   zExecutor._add_scope_cachec                 C   s   t d| d d S )Nz"use_program_cache is force set to z! by FLAGS_FORCE_USE_PROGRAM_CACHE)r   r   )r   use_program_cacher   r   r   _log_force_set_program_cache  s   
z%Executor._log_force_set_program_cachec                 C   s   |  }|jD ]F}|j dkrK|jdd }|| }||}	|	jtjj	j
kr<t|tjs7t|| j|	j}t|	| |jd}
t||||
 q d S d S )NrE   rH   r   rT   )ra   rI   r>   rJ   rL   rD   rC   r   r6   r7   ZSTRINGSr-   r/   r   r   rF   rU   Zset_feed_variable)r   rn   rE   rp   r    ra   rP   rQ   Zcur_feedrD   rW   r   r   r   
_feed_data  s    


zExecutor._feed_datac                    s$    fddt jt|D }|S )Nc                    s   g | ]	}t  |qS r   )r   Zget_fetch_variable)r'   r<   rq   r    r   r   r+     s    z(Executor._fetch_data.<locals>.<listcomp>)rk   movesr;   r1   )r   ro   rq   r    Zoutsr   r%  r   _fetch_data  s   zExecutor._fetch_datac              
   C   s   g }g }dd }t |D ]F\}}t|tr!|D ]}|||| qqt|trLt|d ttfs>td|||t|d j|d D ]}|||| qBq|||| q||fS )a6  
        Split optimize_ops from fetch_list, which provided to specify program prunning.
        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                 S   sd   t |tr| r| | d S tdt |ts$t |ts$t |tjr+|| d S tdt	|)Nz0The operator in fetch_list is not an optimize_opzOThe item in fetch_list should be str, variable or optimize_op, but received %s.)
r-   r	   _is_optimize_opr   r   r   r   rk   rl   rJ   )_optimize_ops_fetch_listr   r   r   r   _get_targets  s    

z@Executor._split_optimize_ops_in_fetch_list.<locals>._get_targetsr   zRequires fetch_list[{}][0] shall be one of (list, tuple) when type(fetch_list[{}]) is `tuple`, but received fetch_list[{}][0]'s type is `{}`.)rf   r-   r.   r   r   rN   rJ   r   )clsro   r)  r*  r+  indexr   r<   r   r   r   !_split_optimize_ops_in_fetch_list  s*   

z*Executor._split_optimize_ops_in_fetch_listc                 C   s   t |tj}|r|jr|j}n	td dS |}g }t |tr&t| }nt |ts0t |t	rAt
|D ]\}}	|t|	 7 }q4|sX|jD ]}
|
jD ]}| rV|| qKqF|| }|||}|rs||_t|j|_d|_|S |}|S )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 feeded.  

        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   ri   rj   r   r.   r   r   rf   r   rI   r(  r   Z_prune_with_inputr   ZGraphr>   r   Z	_compiled)r,  rn   rE   ro   optimize_opscompiledZorigin_programr   r<   r   rO   rP   targetspruned_programr   r   r   _prune_program  s>   



zExecutor._prune_programc                 C   s   t |tj}|r|jr|j }ntd |S | }t |tr=t|	 D ]}|
|s:|| td|  q'|S t |tsGt |trjt|D ]\}}t|	 D ]}|
|sh|| td|  qUqK|S )ah  
        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   ra   ri   rj   r   r.   r   rg   r   r   rf   )r,  rn   rE   r0  ra   r   r<   r   r   r   r   r   Z  sB   




zExecutor._update_feedc                 C   s@   | j sd| _ | j D ]\}}| j| ~q| j  dS dS )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_trainerclose)r   ktrainer_instancer   r   r   r6    s   zExecutor.closec                 C   s  ddl m} |j}	|jd u}
|
r|j }t|trXt }|D ]2}|| }|
r,||nd }t|tj	sCt
|| t |r@|jnd }|
rMt|||	  |||< q|	| n_t|tsbt|trt }t|D ]H\}}t|tsvtdt }|D ]0}|| }|
r||nd }t|tj	st
|| |j| |r|jnd }|
rt|| |||< q{|| qi|	| t|jdr|jj}t||sJ d| }|j j|j }t
|t |j}t rtd n|	|j|i ttt|}|	 ||! }|rt"|S |S )Nr   LRSchedulerz*Each element of feed list should be a dictr   must be LRSchedulerzCaution!!! When capturing CUDA Graph, the learning rate scheduler would not take any effect! Please set the learning rate manually before each batch!)#paddle.optimizer.lrr:  	_executorr   ra   r-   r   rD   r   r/   r   CPUPlacerC   rF   Zdevice_countZ'feed_and_split_tensor_into_local_scopesr.   r   rf   r   _placesr   Zfeed_tensors_into_local_scopesr   r   rb   	_var_nameZis_cuda_graph_capturingri   rj   r   r   r   r   r%   )r   rn   r    rE   ro   rq   r   return_mergedr:  exer?   ra   Zfeed_tensor_dictr   Zfeed_tensorrD   r   r<   r   r   r5   r   lr_valuelr_varZ	lr_tensorr   r   r   r   r   _run_parallel  sz   







zExecutor._run_parallelrE   rS   TFc                 C   s   t jdd}|dur|dv }| | z| j|||||||||
|	d
}t  |W S  tyD } ztj	t
   W Y d}~dS d}~ww )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:`LoDTensor`. 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.
            return_merged(bool): This parameter indicates whether fetched Tensors (the Tensors
                specified in the fetch list) should be merged according to the execution device dimension.
                If :code:`return_merged` is False, the type of the return value is a two-dimensional list
                of :code:`Tensor` / :code:`LoDTensorArray` ( :code:`return_numpy` is False) or a two-dimensional
                list of :code:`numpy.ndarray` ( :code:`return_numpy` is True). If :code:`return_merged` is True,
                the type of the return value is an one-dimensional list of :code:`Tensor` / :code:`LoDTensorArray`
                ( :code:`return_numpy` is False) or an one-dimensional list of :code:`numpy.ndarray`
                ( :code:`return_numpy` is True). Please see Examples 2 for more details. If the lengths of fetched
                results are variant, please set :code:`return_merged` as False, which denotes that the fetched
                results will not be merged. The default is True, but it is just for the compatibility, and may
                use False as default value in the future version.
            use_prune(bool): This parameter indicates whether the input :code:`Program` will be pruned. 
                If the parameter is True, the program will be pruned accroding 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 overrided to True, and the program will be pruned.
                
        Returns:

            List: The fetched result list.

        NOTES:
            1. If it is multi-card running and the feed parameter is dict type, the input data
               will be evenly sent to different cards. For example, using two GPUs to run the model,
               the input sample number is 3, that is, [0, 1, 2], the sample number on GPU0 is 1,
               that is, [0], and the sample number on GPU1 is 2, that is, [1, 2].
               If the number of samples is less than the number of devices, the program will
               throw an exception, so when running the model, you should make sure that the
               number of samples of the last batch of the data set should be greater than the
               number of CPU cores or GPU cards, if it is less than, it is recommended that
               the batch be discarded.
            2. If the number of CPU cores or GPU cards available is greater than 1, the fetch
               results are spliced together in dimension 0 for the same Tensor values
               (Tensors in fetch_list) on different devices.

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

                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.fluid.layers.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])
                print(array_val)
                # [array([0.02153828], dtype=float32)]

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

                # required: 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()).with_data_parallel(
                        loss_name=loss.name, build_strategy=build_strategy)
                batch_size = 6
                x = np.random.random(size=(batch_size, 1)).astype('float32')

                # Set return_merged as False to fetch unmerged results:
                unmerged_prediction, = exe.run(binary,
                                               feed={'X': x},
                                               fetch_list=[prediction.name],
                                               return_merged=False)
                # If the user uses two GPU cards to run this python code, the printed result will be
                # (2, 3, class_dim). The first dimension value of the printed result is the number of used
                # GPU cards, and the second dimension value is the quotient of batch_size and the
                # number of used GPU cards.
                print("The unmerged prediction shape: {}".format(
                    np.array(unmerged_prediction).shape))
                print(unmerged_prediction)

                # Set return_merged as True to fetch merged results:
                merged_prediction, = exe.run(binary,
                                             feed={'X': x},
                                             fetch_list=[prediction.name],
                                             return_merged=True)
                # 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 merged prediction shape: {}".format(
                    np.array(merged_prediction).shape))
                print(merged_prediction)

                # Out:
                # The unmerged prediction shape: (2, 3, 2)
                # [array([[-0.37620035, -0.19752218],
                #        [-0.3561043 , -0.18697084],
                #        [-0.24129935, -0.12669306]], dtype=float32), array([[-0.24489994, -0.12858354],
                #        [-0.49041364, -0.25748932],
                #        [-0.44331917, -0.23276259]], dtype=float32)]
                # The merged prediction shape: (6, 2)
                # [[-0.37789783 -0.19921964]
                #  [-0.3577645  -0.18863106]
                #  [-0.24274671 -0.12814042]
                #  [-0.24635398 -0.13003758]
                #  [-0.49232286 -0.25939852]
                #  [-0.44514108 -0.2345845 ]]

        ZFLAGS_FORCE_USE_PROGRAM_CACHENr   )
rn   rE   ro   rp   rq   r    r   r"  	use_prunerA  )r   r   r   r#  	_run_implr   Zupdate_autotune_statusrM   rk   reraiser   exc_info)r   rn   rE   ro   rp   rq   r    r   r"  rA  rF  Zforce_use_program_cacher   er   r   r   r     s2    9

zExecutor.runc           %   
   C   s  | j rtd|d u }|d u rt }| |}t|trJ|jrJd|jv r7| jd u r-t | _| j	|||| j
dS d|jv rB|jd }n| j|||dS t|tru|jru|jd }t|}t }|| t|| _d|jv ru|jd }t|trt| jdkr|rd}nd	}t| |d u rt }|}|}| |\}}|rd
}
|
rt|||}| |}|d u rt|tjr| t t!|}t""|}||_#| t t!|d u r| $t t!|| | %||||}| &|| n|}| '||}|}dd }|	r| j(r||| j)r|d u ri }nt|t*t+fr,t|dks(J d|d }t|t,s:t-dt.| | '||}| j/0|||||| j)|\}}| 1|||| t2|drddl3m4} t|j5|snJ d|j5}| }| j6|j7 }t89|g:t;|j<}t=||j7}t>|t? }t@ r|A||B  n|A|| j) |C|t*|D ||S t|tj}|
r|r|jE } n| } | j6D ]F}!| jFGtHI|!}"| j6|! }#|"J dkr|". tjKjLjMkr|"N d
kr|#jOd
kr|#jPd
kr|#jQdkr|!|vrtRd|! qtST| | |sLt|jUtj}$|$r?|jUV|| j) | jW|jU||||||	dS | jX||||||||dS |V|| j) |jYr^| Z|j[|S | jW|||||||	dS )Nz"Attempted to use a closed Executor	fleet_opt)rn   rE   ro   with_standalone_executorZstartup_program)ro   r"  heter_placer   zNow 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.zThere are no operators in the program to be executed. If you pass Program manually, please use fluid.program_guard to ensure the current Program is being used.Tc                 S   sD  t  s
t|t jrdS tjdd dv }ddlm} |j	d ur*|s*t
dt dS t| tjp6t| jtj}|rt| tjrA| n| j}|jrZt|||jdkrZt
dt dS t  d	 dv rjt
d
t dS |jrut
dt dS |jd ur|jjrt
dt dS |jd ur|jjrt
dt dS |S t| tsJ dS )NFr   r   r   fleetz)Standalone executor is not used for fleetr   z1Standalone executor is not used for data parallelZFLAGS_enable_parallel_graphz2Standalone executor is not used for parallel graphz-Standalone executor is not used for inferencez.Standalone executor is not used for CUDA Graphz.Standalone executor is not used for async modeT)r   Zis_compiled_with_mlur-   ZCustomPlacer   r   r   Zpaddle.distributed.fleetrO  Z_role_makerri   rj   UserWarningr   r   r   Z_is_data_parallelr1   Z_get_placesr?  globals_is_inferencer   Zallow_cuda_graph_captureZ
async_moder   )rn   r   Z,use_standalone_executor_for_compiled_programrO  r0  r   r   r   r   _can_use_interpreter_core  s   
z5Executor._run_impl.<locals>._can_use_interpreter_corer   r   r   r   r9  r;  FzNeed feed data for variable %s)r    rE   ro   rq   r   rA  )rE   ro   rp   rq   r    r   r"  )\r  r2   r   _check_fetch_listr-   r   _pipeline_optr  r   _run_using_fleet_executorr  _run_pipeline_heter_pipeline_optr   r   r   r   r   r   r  r1   ra   rI   ri   rj   r   r.  r   r  r   r   r  r   r   r*   Z_share_vars_fromr  r3  r  r   r
  r   r.   r   r   r   rJ   r  r   r$  r   r<  r:  r   rb   r@  r3   r4   r   r   rC   get_variable_tensorr   r>  Zis_compiled_with_ipu
_copy_fromr   r   r   r   r>   r~   cptto_bytesrZ   r6   r7   Z
LOD_TENSORr?   Zstop_gradientis_dataZbelong_to_optimizerr@   acpZ_auto_checkpointr   r   rE  _run_programrR  _run_inferencer=  )%r   rn   rE   ro   rp   rq   r    r   r"  rA  rF  Zuse_default_main_programrM  r  
error_infoZ_origin_fetch_listZ_origin_programr/  	cache_keyZcached_pruned_programZprogram_scope_cacher2  rS  r   r:  r   rC  rD  r   r5   Z
cpu_tensorr0  ra   varnameZvardescZvarobjZhas_compiled_graphr   r   r   rG    sJ  















D





	zExecutor._run_implc	                 C   sF  ddl m}	 |d u ri }nt|ttfr"t|dksJ d|d }t|ts/tdt| |d us7J dt|t	sDtdt| t|t
sQtdt| |rt|||}
| |
}| |
}| |
}|d u rt|||||d	}| |
| ttt|}| j|jd|d
}| }| j|j|d | |
| | |
| |}|}|}n	t|||||d	}| |||| t|drt|j|	sJ d|j}| }| j|j }t !|g"t#|j$}t%&||j}|'|| j( |s| j)|j|ddd|g n
| j*||d
d
d
 |+|, }|- }|r!t.|S |S )Nr   r9  r   r   r   zThe program should not be Emptyz@Executor requires Program as its Parameter. But you passed in %szQThe name of fetch variable requires string as its Parameter. But you passed in %srn   rE   ro   rp   rq   Fr   r;  T)/r<  r:  r-   r.   r   r1   r   r   rJ   r   r   r   r  r  r  rw   r  r   r   r  preparer>   Z	new_scopeZcreate_variablesr  r!  r$  r   r   ra   rb   r@  r3   r4   r   r   rC   r   rY  r   r   r   Zrun_prepared_ctxr~   get_fetch_listr   r%   )r   rn   rE   ro   rp   rq   r    r   r"  r:  rb  cached_programZ
cached_ctxcached_scopeZfetch_list_strr  r   rC  rD  r   r5   arrr   r   r   r   r_    s   








zExecutor._run_programc                 C   s
   | |S r   )r   )r   rB  rE   r   r   r   r`    r   zExecutor._run_inferencec                    s   dd  dd }|d u rg S  |r|gS ||s"J d t|g }t|D ]5\}} |r6|| q(||rSt fdd|D rM|t| q(|| q(td |t|j|S )Nc                 S   s   t | tttjfS r   )r-   r   r   rk   rl   r   r   r   r   <lambda>  s    
z,Executor._check_fetch_list.<locals>.<lambda>c                 S   s   t | ttfS r   )r-   r   r.   r   r   r   r   rj    s    zCurrently , The fetch_list type only should be list or tuple, 
but the input type is {}. For more information please refer to 
the executor.run(...).c                 3   s    | ]} |V  qd S r   r   )r'   vZis_fetch_varr   r   	<genexpr>+  s    z-Executor._check_fetch_list.<locals>.<genexpr>zPRequire fetch_list[{}] 's type shall be one of (Variable, str), but received {}.)	rN   rJ   rf   r   allextendr.   r   r   )r   ro   Zis_tuple_listr   r<   rD   r   rl  r   rT    s.   

zExecutor._check_fetch_listc                 C   s   t tt|d d}|t| W d    n1 sw   Y  |jrLd|jv rNt dd}|t|jd  W d    d S 1 sEw   Y  d S d S d S )Nz_train_desc.prototxtwZ
fleet_desczfleet_desc.prototxt)openr   r   r   
_fleet_opt)r   rn   trainerZfoutr   r   r   _dump_debug_info7  s   "zExecutor._dump_debug_infoc                 C   s|   t |j }||k r|}td||f  |||d d  k r1td|| |f  || |d d< ||d d |  |S )Nz[Pipeline training: setting the pipeline num to %d is enough because there are only %d filesZconcurrency_listr   znPipeline training: setting the 1st element in concurrency_list to %d is enough because there are only %d files)r1   datasetZget_filelistr   
set_thread)r   Zpipeline_optru  Zpipeline_numZfilelist_lengthr   r   r   _adjust_pipeline_resource>  s(   
z"Executor._adjust_pipeline_resourcer   d   c	                 C   s  d}	d}
|j d ur(|j dddkrd}	|j dddkrd}	|j dd	r(d
}
|d u r/t }|d u r5g }|d u r;g }t|t|ksEJ t|tj}|	raddlm} ddl	m
} | }||}|s|jrnt |j}n|jryt |j}nt |j }||j || |	r|| n&|jrt |jj}n|jrt |jj}nt |jj }||j |dkr|
r|t|j d  n|jdkrtd||j n|| || |||| ||fS )Nr   Zworker_classr   ZHeterCpuWorkerr   rs  ZHeterXpuTrainer
use_ps_gpuFTrN  )	FleetUtilZworker_placeszSYou should set thread num first, either in Datasetor in Executor.train_from_dataset)rr  r   r   r1   r-   r   r   Z2paddle.fluid.incubate.fleet.parameter_server.pslibrO  Z,paddle.fluid.incubate.fleet.utils.fleet_utilrz  Zsplit_program_by_devicerU  r   Z_create_trainerrX  Z_set_thread_barrierZ_is_distributedZ_set_programZ_set_heter_inforn   Z_set_thread
thread_numr2   Z
_set_debugZ_set_fetch_var_and_info)r   rn   ru  r    threaddebugro   
fetch_infoprint_periodZis_heterry  r0  rO  rz  Zfuretrs  r   r   r   _prepare_trainerN  sz   	






zExecutor._prepare_trainerc              
   C   s  |j d urPdd l}|d urtdg }| j D ]
}|jr$|| qt	 r2|j
 d}n|j
 d}|d |d |dg || n{|jd ur|jd }|jd }|dkrd	|jvrdd l}|d urttd
g }| j D ]
}|jr|| q}|j
 d}|d |d |dg || n|d u rtdt|}t }|| t|| _n|d u rtd|  g }|j r%|j d }|D ]}t|tr|j}n|}|| jv r|| qt|j d g |ddd|j d< |j d d}|jD ]}|jdkr!| dtj!j"j# qd }| j$||||||||	d\}}|%| |&  |j d u rP|jd u rP| j'||d |j(du r`|j)j(r`t*+d |,|j)j- |jd u r{| j.|j/|0 ||j1}n1|d krg }t2|d |}| 3|}|d u r| j.|j/|0 ||j1}| 4|| n|5|j1 |
d ur|6d}t7||
}|8  | j9| |:  |jd u r| j;| n| j9| |jd u r| j;| |<  |=  |r|>d? }|@ }tA|S d S )Nr   (dataset should be None for pipeline modeInMemoryDatasetFileInstantDatasetr   NoneZpipeline_stagerM  Z
is_fl_modez.dataset should be None for heter pipeline modez)dataset is need and should be initializedsection_programrE   rS   rd  op_rolern   ru  r    r|  r}  ro   r~  r  rn   rs  F0dataset should call set_use_ps_gpu in PsGpu mode)BrU  paddler2   ra   rb   valuesr]  r   r   is_compiled_with_npufluidDatasetFactorycreate_datasetset_batch_sizerv  set_filelistset_use_varrX  r   r   r   r   r   r  _prepare_to_runr-   r   rA   rw   rO   rI   rJ   	_set_attrop_proto_and_checker_makerOpRoleOptimizer  
_set_infer_gen_trainer_descrt  ry  
proto_descr   r   _dynamic_adjust_before_trainr{  init_for_datasetr>   _descru  r   r  r   ZResetDatasetZget_worker_scoper   startrun_from_datasetstopr5  Z_dynamic_adjust_after_trainZ_finish_to_runr~   rf  r   r%   )r   rn   ru  r    r|  is_inferr}  ro   r~  r  fetch_handlerr  	data_varsrD   Zstage_idrM  r  real_fetch_listreal_programru   rq   
main_blockrP   rs  r8  rb  Zscope0Zfetch_monitorri  r   r   r   r   _run_from_dataset  s  






















	






zExecutor._run_from_datasetc              
      s  j d usJ |d u sJ dtd  }| |}|r"|d ur"|S dd lfdd}| } fdd}| \}}|j d< d  | j|||| ||	d\}}|| |  |jd	u ri|jjrit	
d
 ||jj | }| jj|||j}|||g}|r| || |S )Nr  r   c                     s   g }   j D ]
}|jr| | q	t r! j 	d}n j 	d}|
d |d |dg ||  |  |S )Nr  r  r   r  )ra   rb   r  r]  r   r   r  r  r  r  r  rv  r  r  r  )r  rD   ru  )r  rn   r   r   _get_datasetH  s$   





z4Executor._prepare_pipeline_ctx.<locals>._get_datasetc                     s   j d } g } D ]}t|tr|j}n|}||  jv r"|| q	t| g |ddd} | d}|j	D ]}|j
dkrD|dtjjj q4| |fS )Nr  rE   rS   rd  r   r  )rU  r-   r   rA   ra   rb   r   rw   rO   rI   rJ   r  r   r  r  r  )r  r  ru   rq   r  rP   )ro   rn   r   r   _get_real_program_fetch_list\  s0   





zDExecutor._prepare_pipeline_ctx.<locals>._get_real_program_fetch_listr  r  Fr  )rU  r   r  r  r  r  r  ry  r  r   r   r  r{  r  r  r  r>   ru  r  )r   rn   ru  r    r|  r  r}  ro   r~  r  r  r"  rb  r  r  r  r  r  rs  Ztrainer_descr8  r   )ro   r  rn   r   _prepare_pipeline_ctx0  sD   




	

zExecutor._prepare_pipeline_ctxr   c              
   C   s  d|v r|d nd}t tdd}tddd}t|}	d|v s+d	|v s+J d
d	|v rId|v s7J dtd dd |d	 D }
|d }n|d }|dkrddlm} d|vsid|d vsi|d d dkrnt	d ||||
dd|
di |	|\}
}n>|dkrddlm} d|v rd|d v r|d d dksJ dd|v r|d dksJ d|||\}
}ndt| d |
|d	< ||d< t }|| j | j||j||||
|g  d S )Nnum_micro_batchesr   r   r   r   r   r   	schedulertaskszFleet executor need configuration for scheduler, you can choose from 1F1B or Origin. Or you can provide a list of task nodes to init fleet executor directly.task_id_to_rankzUIf you provide tasks to init fleet executor, task_id_to_rank should also be provided.z/fleet executor will use user defined task nodesc                 S   s   g | ]}|  qS r   )Z	task_node)r'   taskr   r   r   r+     r   z<Executor._prepare_fleet_executor_carrier.<locals>.<listcomp>Z1F1B)run1f1bZdist_strategyZ	pp_degreez)Using 1F1B scheduler with pp_degree == 1.ZOrigin)originzBFor pipeline mode, the scheduler should be 1F1B instead of Origin.z=For origin scheduler mode, the num micro batches should be 1.zEFleet_executor only supports 1F1B and Origin scheduler, but received .)r   r   r   r   r1   r   Z-paddle.distributed.fleet.fleet_executor_utilsr  ri   rj   r   r  r   r   r   r   r   r  initr>   )r   Z
carrier_idrn   r    rK  rL  r  r   r   r   r  r  r  r  r  r   r   r   r   _prepare_fleet_executor_carrier  sj   


z(Executor._prepare_fleet_executor_carrierc                 C   sZ  t |||}| |}| |}	|	d u rt }	| ||	 |d u r|js(J d|d u r.g n|}
|}d|jv r<|jd }t||
|||d}|d}|jD ]}|j	dkr]|
dtjjj qM| || |jd }d|v r|d d }td	|  | }| j||
|d
}|| |d d }td|  | }| j|||d}|d}|jD ]}|j	dkr|
dtjjj q|| | j|||	||d |r| ||||	 ddlm} t|dr|j}t||sJ d| }| j|j }t !|g"t#|j$}t%|	|j}|&|| j' | j()| |r+|	*|+ }|, }t-|S d S )Nz2program should have _pipeline_opt to start carrierr  rd  r   rS   r  rK  r  zInserting feed ops for task)rn   rE   rp   zInserting fetch ops for task)rn   ro   rq   )rn   r    rK  rL  r9  r   r;  ).r   r  r  r   r!  rU  rw   rO   rI   rJ   r  r   r  r  r  r  r   task_idZget_program_add_feed_opsZset_program_add_fetch_opsr  r$  r<  r:  r   r   r-   ra   rb   r@  r3   r4   r   r   rC   rY  r   r   r  r   r~   rf  r   r%   )r   rn   rE   rp   rq   ro   rL  rb  rg  rh  Z	real_feedr  r  rP   rK  Z	feed_taskZfeed_programZ
fetch_taskZfetch_programr:  r   rC  rD  r   r5   ri  r   r   r   r   rV    s   












z"Executor._run_using_fleet_executorc           
      C   s   |  }| }||jv r||}n|j|tjjjdd}t	|||sPt
|D ]'\}}||rH||}	|jdd|gid|	gid|id q(td|  q(|S )	NTrY   rE   rG   rH   rT   r[   r]   )r`   ra   rb   rD   rc   r   r6   r7   rd   rR   rf   rg   rh   ri   rj   )
r   rn   rE   rp   rs   ra   rt   r<   rA   rv   r   r   r   r  4	  s0   


zExecutor._add_feed_opsc                 C   s   |  }| }||jv r||}n|j|tjjjdd}|r#d}nd}t	||||s[t
|D ]*\}	}
t|
tsIt|
tjsIJ d|	t|
f |j|d|
gid|gid|	id	 q0|S )
NTrY   r^   rS   r_   rG   rH   rT   r[   )r`   ra   rb   rD   rc   r   r6   r7   re   rX   rf   r-   r   rk   rl   rJ   rm   )r,  rn   ro   rq   rr   rs   ra   ru   rV   r<   rD   r   r   r   r  Q	  s<   

zExecutor._add_fetch_opsc                 C   sJ   |  }| }t|j}tt|D ]}|j| j|kr"|| q|S r   )r`   ra   r1   rI   reversedr;   rJ   Z
_remove_op)r,  rn   Zfetch_op_namers   ra   Zop_numrW   r   r   r   _remove_fetch_opsw	  s   

zExecutor._remove_fetch_opsc                 C   s   |  |||||||||	|
|\}}}ddlm} t|drN|j}t||s)J d| }| j|j }t	
|gt|j}t||j}||| j | j| |s\| j| |rm|d }| }t|S d S )Nr   r9  r   r;  rS   )r  r<  r:  r   r   r-   ra   rb   r@  r3   r4   r   r   rC   r   rY  r   r   r  r  r5  r~   rf  r   r%   )r   rn   ru  r    r|  r  r}  ro   r~  r  r  r"  r  r8  r:  r   rC  rD  r   r5   ri  r   r   r   r   rW  	  s.   
zExecutor._run_pipelinec
           
      C      |  ||||d|||||	
S )a2  
        Infer from a pre-defined Dataset. Dataset is defined in paddle.fluid.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.fluid.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.fluid.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 = []
                dataset.set_filelist(filelist)
                exe.run(paddle.static.default_startup_program())
                exe.infer_from_dataset(program=paddle.static.default_main_program(),
                                       dataset=dataset)

        Tr  
r   rn   ru  r    r|  r}  ro   r~  r  r  r   r   r   infer_from_dataset	  s   AzExecutor.infer_from_datasetc           
   
   C   sf   | j |d |d||||d\}}|d |  | j||d | j|j| |d }	| j|	 |	S )Nr   r  Fr  )	r  r  r  rt  r  r  r>   r  r  )
r   rn   r    r}  ro   r~  r  r  rs  r8  r   r   r   start_heter_trainer	  s"   

	zExecutor.start_heter_trainerc
           
      C   r  )at  
        Train from a pre-defined Dataset. Dataset is defined in paddle.fluid.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.fluid.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.fluid.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 = []
              dataset.set_filelist(filelist)
              exe.run(paddle.static.default_startup_program())
              exe.train_from_dataset(program=paddle.static.default_main_program(),
                                     dataset=dataset)

        Fr  r  r   r   r   train_from_dataset
  s   @zExecutor.train_from_datasetr   )NNN)
NNNrE   rS   NTFTF)NN)NNNr   FNNrx  )
NNNr   FFNNrx  N)NNNr   FFNNrx  NF)r   NNNF)NNrE   rS   NFFrS   )	NNNr   FNNrx  N)NNFNNrx  N)/r   r   r   __doc__r   r  r  r  r  r  r  r  r  r  r  r  r   r!  r   r#  r$  r'  classmethodr.  r3  r   r6  rE  r   rG  r_  r`  rT  rt  rw  r  r  r  r  rV  r  r  r  rW  r  r  r  r   r   r   r   r   /  s    
L

4?
,C
 Q  	U

J
 
i
9
d%
)
F
(r   r  )r   r  )NTr   )E
__future__r   r   r   multiprocessingr   ri   numpyr3   wrapped_decoratorr   rk   Zdata_feederr   r   r   r   r   r	   r
   r   r   r   r   r   r   r[  Ztrainer_factoryr   r   r*   Zincubate.checkpointr   r^  r   	functoolsr   __all__ZScoper   ZNativeConfigZInferNativeConfigZAnalysisConfigZInferAnalysisConfigr   r"   r   r%   r:   r=   rF   rR   rX   rw   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   sl   

(,
#(*
2
<
!
0Ty