o
    NeS                     @   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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mZmZmZmZmZ ddlmZ ddlmZ d dlZddlmZmZ d dlm Z  ddlm!Z!m"Z"m#Z# g dZ$e ddd ej%j&j'dfddZ(G dd de
Z)G dd de*Z+d3ddZ,d3ddZ-dd Z.dd  Z/d!d" Z0				d4d#d$Z1			d5d%d&Z2		d3d'd(Z3d)d* Z4d6d+d,Z5d7d-d.Z6d/d0 Z7d6d1d2Z8dS )8    )print_functionN   )
DataFeeder   )
BlockGuard)templatedoc)core)global_scope)convert_np_dtype_to_dtype_default_main_programdefault_startup_programprogram_guardProgramVariable)LayerHelper)generate)check_dtype
check_type)static_only)_get_paddle_place_current_expected_place_set_expected_place)data	read_filedouble_buffer	py_readercreate_py_reader_by_dataloadTfloat32c           
   	   C   s   t d
i t }t| dtjtjfd t|dttfd t|}tj	t
|D ]}|| du r7d||< d}q(|| dk r?d}q(|rGdg| }|j| |||||dd	}	|	S )a  
    **Data Layer**

    This operator creates the global variable. The global variables can be
    accessed by all the following operators in the graph.

    Note: 
        :code:`paddle.fluid.layers.data` is deprecated as it will be removed in 
        a later version. Please use :code:`paddle.fluid.data` .

        This :code:`paddle.fluid.layers.data` set shape and dtype at compile
        time but does NOT check the shape or the dtype of fed data, the
        :code:`paddle.fluid.data` checks the shape and the dtype of data fed 
        by Executor or ParallelExecutor during run time.

        To feed variable size inputs, users can feed variable size inputs
        directly to this :code:`paddle.fluid.layers.data` and PaddlePaddle will
        fit the size accordingly. Or set -1 on the variable dimension when using
        :code:`paddle.fluid.data` .

        The default :code:`stop_gradient` attribute of the Variable created by
        this API is true, which means the gradient won't be passed backward
        through the data Varaible. Set :code:`var.stop_gradient = False` If
        user would like to pass backward gradient.

    Args:
       name(str): The name/alias of the variable, see :ref:`api_guide_Name`
            for more details.
       shape(list|tuple): Tuple declaring the shape. If :code:`append_batch_size` is
            True and there is no -1 inside :code:`shape`, it should be 
            considered as the shape of the each sample. Otherwise, it should
            be considered as the shape of the batched data.  
       append_batch_size(bool):
          1. If true, it prepends -1 to the shape.
            For example if shape=[1], the resulting shape is [-1, 1]. This will 
            be useful to set different batch size at run time.
          2. If shape contains -1, such as shape=[1, -1].
            append_batch_size will be enforced to be be False (ineffective)
            because PaddlePaddle cannot set more than 1 unknown number on the
            shape.
       dtype(np.dtype|VarType|str): The type of the data. Supported dtype: bool,
            float16, float32, float64, int8, int16, int32, int64, uint8.
       type(VarType): The output type. Supported dtype: VarType.LOD_TENSOR,
            VarType.SELECTED_ROWS, VarType.NCCL_ID. Default: VarType.LOD_TENSOR. 
       lod_level(int): The LoD Level. 0 means the input data is not a sequence.
            Default: 0.
       stop_gradient(bool): A boolean that mentions whether gradient should flow.
            Default: True. 

    Returns:
        The global variable that gives access to the data.

    Return Type:
        Variable

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          data = fluid.layers.data(name='x', shape=[784], dtype='float32')
    r   nameshapeNFr   T)r   r    dtypetypestop_gradient	lod_levelZis_data)r   )r   localsr   sixbinary_type	text_typelisttuplemovesrangelenZcreate_global_variable)
r   r    Zappend_batch_sizer"   r%   r#   r$   helperiZdata_var r1   FD:\Projects\ConvertPro\env\Lib\site-packages\paddle/fluid/layers/io.pyr   +   s,   E
r   c                       s,   e Zd ZdZ fddZ fddZ  ZS )BlockGuardServzl
    BlockGuardServ class.

    BlockGuardServ class is used to create an op with a block in a program.
    c                    s0   t |ts	tdtt| |jj || _d S )Nz$BlockGuardServ takes a ListenAndServ)	
isinstanceListenAndServ	TypeErrorsuperr3   __init__r/   main_programserver)selfr:   	__class__r1   r2   r8      s   

zBlockGuardServ.__init__c                    s*   |d urdS | j   tt| |||S )NF)r:   complete_opr7   r3   __exit__)r;   exc_typeexc_valexc_tbr<   r1   r2   r?      s   
zBlockGuardServ.__exit__)__name__
__module____qualname____doc__r8   r?   __classcell__r1   r1   r<   r2   r3      s    r3   c                   @   s:   e Zd ZdZdddZdd Zdd	 Zd
d Zdd ZdS )r5   a  
    **ListenAndServ Layer**

    ListenAndServ is used to create a rpc server bind and listen
    on specific TCP port, this server will run the sub-block when
    received variables from clients.

    Args:
        endpoint(string): IP:port string which the server will listen on.
        inputs(list): a list of variables that the server will get from clients.
        fan_in(int): how many client are expected to report to this server, default: 1.
        optimizer_mode(bool): whether to run the server as a parameter server, default: True.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            with fluid.program_guard(main):
                serv = layers.ListenAndServ(
                    "127.0.0.1:6170", ["X"], optimizer_mode=False)
                with serv.do():
                    x = layers.data(
                        shape=[32, 32],
                        dtype='float32',
                        name="X",
                        append_batch_size=False)
                    fluid.initializer.Constant(value=1.0)(x, main.global_block())
                    layers.scale(x=x, scale=10.0, out=out_var)

            exe = fluid.Executor(place)
            exe.run(main)
    r   Tc                 C   s,   t d| _|| _g | _|| _|| _|| _d S )Nlisten_and_serv)r   r/   inputsoutputsendpointfan_inoptimizer_mode)r;   rK   rI   rL   rM   r1   r1   r2   r8      s   

zListenAndServ.__init__c                 C   s   t | S N)r3   )r;   r1   r1   r2   do   s   zListenAndServ.doc           	      C   s   | j j}| }|  }t }t }|jD ]@}| jr7d|jv r6d|jv r6||jd j	 ||jd j	 q|j
D ]}||D ]}||| ||| qAq:q||fS )NZGradParam)r/   r9   current_blockparent_blockr*   opsrM   rI   appendr   input_namesinputvar)	r;   r9   rQ   rR   paramsZgradsopZinameZin_var_namer1   r1   r2   get_params_and_grads   s$   

z"ListenAndServ.get_params_and_gradsc                 C   s,   | j j}| j}|dksJ ||}|S )Nr   )r/   r9   rQ   
parent_idxblock)r;   progr[   rR   r1   r1   r2   rR      s
   

zListenAndServ.parent_blockc              
   C   sV   ddl m} | jj}| }|  }|jdd| jii | j| j	|g|j
dgdd d S )Nr   )DistributedModerH   X )rK   ZFaninZoptimize_blocksZdistributed_modeZgrad_to_block_idr#   rI   rJ   attrs)Z$incubate.fleet.parameter_server.moder^   r/   r9   rQ   rR   	append_oprI   rK   rL   ZSYNC)r;   r^   r9   rQ   rR   r1   r1   r2   r>      s   
zListenAndServ.complete_opN)r   T)	rC   rD   rE   rF   r8   rO   rZ   rR   r>   r1   r1   r1   r2   r5      s    
!
r5   c              
   C   s   t |tksJ |du rg }nt|tr|g}t |tksJ | d}tt|} tdi t }tj	
 }|jdd|id|id| d||tj	jjid	 |r`|jd
d|idg id| id	 dS dS )ak  
    Send variables to the server side, and get vars from server
    side when server have finished running server side program.

    Args:
        endpoints (str): comma separated IP:PORT pairs in the order
                   of send_vars to send
        send_vars (list): variables to send to server
        sync (bool): whether to wait the request finish

    N,Sendsendr_   Out	endpointsepmapra   Zsend_barrier)re   )r#   r*   r4   r   splitsetr   r&   r   Zop_proto_and_checker_makerZkOpRoleAttrNamerc   ZOpRoleZRPC)rh   Z	send_varsZdummy_outputsyncri   r/   Zrpc_op_role_namer1   r1   r2   re     s8   



re   c                 C   s   t |tksJ |du rg }nt|tr|g}t |tksJ | d}tt|} tdi t }|jdd|id|i| |dd |rP|jd	d|id
| id |S )aY  
    Receive variables from server side

    Args:
        endpoints (str): comma separated IP:PORT pairs in the order
                   of send_vars to send
        get_vars (list): vars to get from server after send completes.
        sync (bool): whether to wait the request finish

    Returns:
        list: list of received variables
    Nrd   Recvrecvr_   rg   )rh   ri   ra   Zfetch_barrierrh   )r#   rJ   rb   )rm   )	r#   r*   r4   r   rj   rk   r   r&   rc   )rh   Zget_varsZdummy_inputrl   ri   r/   r1   r1   r2   rm   /  s,   

rm   c                    s.   fdd  fdd}|_ d_d_S )Nc                     s   t  } |  j}| S rN   )r	   Zfind_varr   Z
get_reader)scoperW   readerr1   r2   __get_reader__Y  s   z3monkey_patch_reader_methods.<locals>.__get_reader__c                      s
       S rN   )resetr1   )rr   r1   r2   rs   ^     
z*monkey_patch_reader_methods.<locals>.resetT)rs   r$   persistable)rq   rs   r1   )rr   rq   r2   monkey_patch_reader_methodsW  s   rv   c                 C   sV   | j |jtjjjd}|j|j  |j	|j
  |j|j  d|_|S )N)r   r#   T)
create_varr   r   VarDescVarTypeZREADERdescZ
set_shapesshapes
set_dtypesdtypesZset_lod_levels
lod_levelsru   )r\   rW   Znew_varr1   r1   r2   _copy_reader_var_g  s   r   c           
      C   s   |j }i }|D ]}g ||< ||}|D ]}|| | | qq|j}i }|D ]}g ||< ||}|D ]}|| | | q6q)| j|j||| d}	|	S )Nra   )	rU   rV   rT   rW   Zoutput_namesoutputrc   r#   Z	all_attrs)
r\   rY   Zinput_param_namesZnew_input_map
param_name	arg_namesZarg_nameZoutput_param_namesZnew_output_mapZnew_opr1   r1   r2   _copy_reader_create_op_p  s,   

r   c              
      s  d urOt tstdtt g g g }g }g g }	D ],}
|
j ||
j |t	|
j |
j |
j
 |	t|
j  q!n.dd D dd D }	g }g }D ]}|| |t	| qcd u r}dgt	 dd D }|d u rtd}td}td	}nd
|dg}d
|dg}d
|d	g}t |}t|| dt  }|j|d}|jdd|gid|gi|||	|dd |j d|_tt  |}t||rt|d}j|_|_jd _ d _!d_"fddfdd  fdd}fdd}fdd}|_ _#|_$ _%|_&|_'S )Nz2feed_list should be a list of Variable instead of c                 S      g | ]}t |qS r1   )r
   .0dtr1   r1   r2   
<listcomp>      z_py_reader.<locals>.<listcomp>c                 S   s   g | ]}d qS )r   r1   r   r1   r1   r2   r     s    r   c                 S   r   r1   )int)r   tr1   r1   r2   r     r   Zlod_tensor_blocking_queueZcreate_py_readerr   _queuerq   Fr   Zblocking_queuerg   )shape_concatr~   r}   need_check_feedranksra   Tc                    s:    fdd}t j|t fd_dj_j  d S )Nc              
      s   zBt |   D ]3}t }|D ]}t|tjs&t }||t  |}|| qjr1 n 	| jr; nq 
  W d S  tye } z   td tjt   W Y d }~d S d }~ww )Nz.Your decorated reader has raised an exception!)r   r   ZLoDTensorArrayr4   Z	LoDTensorrk   CPUPlacerT   exitedpushclose	Exceptionkillloggingwarnr'   reraisesysexc_info)Zlegacy_expected_placeZtensorsarrayitemtmpex)
feed_queuefuncrq   r1   r2   __provider_thread__  s.   


zE_py_reader.<locals>.start_provide_thread.<locals>.__provider_thread__)targetargsT)	threadingThreadr   threaddaemonstart)r   r   )r   rq   r   r2   start_provide_thread  s   z(_py_reader.<locals>.start_provide_threadc                    s
   |  _ d S rN   tensor_providerr   rp   r1   r2   __set_tensor_provider__  rt   z+_py_reader.<locals>.__set_tensor_provider__c           	   
      s   t t t G }|d u r1g }d}tD ]\}}}t|}|t||||d |d7 }qdd |D  t|t d}|j	ddW d    n1 sQw   Y   fd	d
}| d S )Nr   )r   r"   r    r%   r   c                 S   s   g | ]}|j qS r1   r   )r   	feed_datar1   r1   r2   r     s    z=_py_reader.<locals>.__set_paddle_reader__.<locals>.<listcomp>)	feed_listplaceF)Zmulti_devicesc                   3   s&     D ]  fddD V  qd S )Nc                    s   g | ]} | qS r1   r1   )r   Z	data_nameslotsr1   r2   r     r   zZ_py_reader.<locals>.__set_paddle_reader__.<locals>.__tensor_provider__.<locals>.<listcomp>r1   r1   Z
data_namespaddle_readerr   r2   __tensor_provider__  s   
zF_py_reader.<locals>.__set_paddle_reader__.<locals>.__tensor_provider__)
r   r   zipstrrT   r   r   r   r   Zdecorate_reader)	r   Zactual_feed_listcounterr"   r    r%   r   Zfeederr   )r   r}   r   r~   r{   r   r2   __set_paddle_reader__   s2   
z)_py_reader.<locals>.__set_paddle_reader__c                      s<      j d urjd urd_j   d_d S d S d S )NTF)r   r   r   joinr1   )current_reset_methodrq   r1   r2   	__reset__  s   

z_py_reader.<locals>.__reset__c                      s    j  d S rN   r   r1   )rq   r   r1   r2   	__start__"  s   z_py_reader.<locals>.__start__)(r4   r*   r6   r   r#   rT   r"   extendr    r.   r%   r   rz   r   unique_namer   r	   rW   r   Zinit_lod_tensor_blocking_queuer   rQ   rw   rc   r|   ru   r   r   rv   r   rs   r   r   r   r   Zdecorate_tensor_providerZdecorate_paddle_readerZdecorate_batch_generatorZdecorate_sample_list_generatorr   )capacityr{   r}   r~   r   use_double_bufferr   r   r   r   r   r    Z	dtype_intZ
queue_nameZreader_nameZdouble_buffer_namerW   startup_blkstartup_varmain_prog_varZdouble_buffer_readerr   r   r   r1   )	r   r   r}   r   r   r~   rq   r{   r   r2   
_py_reader  s   





!r   c                 C   s   t d t| |||||dS )a[  
	:api_attr: Static Graph

    Create a Python reader for data feeding in Python

    This operator returns a Reader Variable.
    The Reader provides :code:`decorate_paddle_reader()` and
    :code:`decorate_tensor_provider()` to set a Python generator as the data
    source and feed the data from the data source to the Reader Variable. 
    When :code:`Executor::Run()` is invoked in C++ side, the data from the 
    generator would be read automatically. Unlike :code:`DataFeeder.feed()`,
    the data reading process and :code:`Executor::Run()` process can run in 
    parallel using :code:`py_reader`. The :code:`start()` method of the Reader
    should be called when each pass begins, while the :code:`reset()` method 
    should be called when the pass ends and :code:`fluid.core.EOFException` raises.

    Note:
       :code:`Program.clone()` method cannot clone :code:`py_reader`. You can 
       refer to :ref:`api_fluid_Program` for more details.
       
       The :code:`read_file` call needs to be in the program block of :code:`py_reader`.
       You can refer to :ref:`api_fluid_layers_read_file` for more details.

    Args:
       capacity(int): The buffer capacity maintained by :code:`py_reader`.
       shapes(list|tuple): List of tuples which declaring data shapes. shapes[i] 
            represents the i-th data shape.
       dtypes(list|tuple): List of strings which declaring data type. Supported dtype:
            bool, float16, float32, float64, int8, int16, int32, int64, uint8.
       lod_levels(list|tuple): List of ints which declaring data lod_level.
       name(basestring): The default value is None. Normally there is no
            need for user to set this property. For more information, please
            refer to :ref:`api_guide_Name`.
       use_double_buffer(bool): Whether use double buffer or not. The double buffer is 
            for pre-reading the data of the next batch and copy the data asynchronously 
            from CPU to GPU. Default is True.

    Returns:
       A Reader from which we can get feeding data.

    Return Type:
       Variable

    Examples:
       1. The basic usage of :code:`py_reader` is as follows:
       
       .. code-block:: python
    
         import paddle
         import paddle.fluid as fluid
         import paddle.dataset.mnist as mnist

         def network(image, label):
             # user defined network, here a softmax regession example
             predict = fluid.layers.fc(input=image, size=10, act='softmax')
             return fluid.layers.cross_entropy(input=predict, label=label)

         reader = fluid.layers.py_reader(capacity=64,
                                         shapes=[(-1, 1, 28, 28), (-1, 1)],
                                         dtypes=['float32', 'int64'])
         reader.decorate_paddle_reader(
             paddle.reader.shuffle(paddle.batch(mnist.train(), batch_size=5),
                                   buf_size=1000))

         img, label = fluid.layers.read_file(reader)
         loss = network(img, label)

         fluid.Executor(fluid.CUDAPlace(0)).run(fluid.default_startup_program())
         exe = fluid.ParallelExecutor(use_cuda=True)
         for epoch_id in range(10):
             reader.start()
             try:
                 while True:
                     exe.run(fetch_list=[loss.name])
             except fluid.core.EOFException:
                 reader.reset()

         fluid.io.save_inference_model(dirname='./model',
                                       feeded_var_names=[img.name, label.name],
                                       target_vars=[loss],
                                       executor=fluid.Executor(fluid.CUDAPlace(0)))

       2. When training and testing are both performed, two different
       :code:`py_reader` should be created with different names, e.g.:

       .. code-block:: python
    
         import paddle
         import paddle.fluid as fluid
         import paddle.dataset.mnist as mnist

         def network(reader):
             img, label = fluid.layers.read_file(reader)
             # User defined network. Here a simple regression as example
             predict = fluid.layers.fc(input=img, size=10, act='softmax')
             loss = fluid.layers.cross_entropy(input=predict, label=label)
             return fluid.layers.mean(loss)

         # Create train_main_prog and train_startup_prog
         train_main_prog = fluid.Program()
         train_startup_prog = fluid.Program()
         with fluid.program_guard(train_main_prog, train_startup_prog):
             # Use fluid.unique_name.guard() to share parameters with test program
             with fluid.unique_name.guard():
                 train_reader = fluid.layers.py_reader(capacity=64,
                                                       shapes=[(-1, 1, 28, 28),
                                                               (-1, 1)],
                                                       dtypes=['float32', 'int64'],
                                                       name='train_reader')
                 train_reader.decorate_paddle_reader(
                     paddle.reader.shuffle(paddle.batch(mnist.train(), batch_size=5),
                                           buf_size=500))
                 train_loss = network(train_reader)  # some network definition
                 adam = fluid.optimizer.Adam(learning_rate=0.01)
                 adam.minimize(train_loss)

         # Create test_main_prog and test_startup_prog
         test_main_prog = fluid.Program()
         test_startup_prog = fluid.Program()
         with fluid.program_guard(test_main_prog, test_startup_prog):
             # Use fluid.unique_name.guard() to share parameters with train program
             with fluid.unique_name.guard():
                 test_reader = fluid.layers.py_reader(capacity=32,
                                                      shapes=[(-1, 1, 28, 28), (-1, 1)],
                                                      dtypes=['float32', 'int64'],
                                                      name='test_reader')
                 test_reader.decorate_paddle_reader(paddle.batch(mnist.test(), 512))
                 test_loss = network(test_reader)

         fluid.Executor(fluid.CUDAPlace(0)).run(train_startup_prog)
         fluid.Executor(fluid.CUDAPlace(0)).run(test_startup_prog)

         train_exe = fluid.ParallelExecutor(use_cuda=True,
                                            loss_name=train_loss.name,
                                            main_program=train_main_prog)
         test_exe = fluid.ParallelExecutor(use_cuda=True,
                                           loss_name=test_loss.name,
                                           main_program=test_main_prog)
         for epoch_id in range(10):
             train_reader.start()
             try:
                 while True:
                    train_exe.run(fetch_list=[train_loss.name])
             except fluid.core.EOFException:
                 train_reader.reset()

         test_reader.start()
         try:
             while True:
                 test_exe.run(fetch_list=[test_loss.name])
         except fluid.core.EOFException:
             test_reader.reset()
    zpaddle.fluid.layers.py_reader() may be deprecated in the near future. Please use paddle.fluid.io.DataLoader.from_generator() instead.r   r{   r}   r~   r   r   r   r   r   r   r1   r1   r2   r   0  s     r   c              	   C   s    t d t| ddd|||dS )ax  
	:api_attr: Static Graph

    The OP creates a Python reader for data feeding in Python, it is similar
    to :ref:`api_fluid_layers_py_reader` except that it can read data from
    the list of feed variables.

    Parameters:
        capacity (int): The buffer capacity maintained by :code:`py_reader`. Its unit
            is batch number. Set larger :attr:`capacity` if the reader is fast.
        feed_list (list(Variable)): The feed variables, are usually created by
            :code:`fluid.data()`.
        name (str, optional): Normally there is no need for user to set this property.
            For more information, please refer to :ref:`api_guide_Name`. Default: None.
        use_double_buffer (bool, optional): Whether use double buffer. If it's True,
            the OP would prefetch next batch data asynchronously. Default: True.

    Returns:
        Reader: A Reader for data feeding. The data types of read data are the same as the data types of variables of :attr:`feed_list`.

    Examples:
        .. code-block:: python

          import paddle
          import paddle.fluid as fluid
          import paddle.dataset.mnist as mnist

          def network(img, label):
              # User defined network. Here a simple regression as example
              predict = fluid.layers.fc(input=img, size=10, act='softmax')
              loss = fluid.layers.cross_entropy(input=predict, label=label)
              return fluid.layers.mean(loss)

          MEMORY_OPT = False
          USE_CUDA = False

          image = fluid.data(name='image', shape=[None, 1, 28, 28], dtype='float32')
          label = fluid.data(name='label', shape=[None, 1], dtype='int64')
          reader = fluid.layers.create_py_reader_by_data(capacity=64,
                                                         feed_list=[image, label])
          reader.decorate_paddle_reader(
              paddle.reader.shuffle(paddle.batch(mnist.train(), batch_size=5), buf_size=500))
          img, label = fluid.layers.read_file(reader)
          loss = network(img, label) # The definition of custom network and the loss function

          place = fluid.CUDAPlace(0) if USE_CUDA else fluid.CPUPlace()
          exe = fluid.Executor(place)
          exe.run(fluid.default_startup_program())

          build_strategy = fluid.BuildStrategy()
          build_strategy.memory_optimize = True if MEMORY_OPT else False
          exec_strategy = fluid.ExecutionStrategy()
          compiled_prog = fluid.compiler.CompiledProgram(
          fluid.default_main_program()).with_data_parallel(
              loss_name=loss.name,
              build_strategy=build_strategy,
              exec_strategy=exec_strategy)

          for epoch_id in range(2):
          reader.start()
          try:
              while True:
                  exe.run(compiled_prog, fetch_list=[loss.name])
          except fluid.core.EOFException:
              reader.reset()
    zpaddle.fluid.layers.create_py_reader_by_data() may be deprecated in the near future. Please use paddle.fluid.io.DataLoader.from_generator() instead.N)r   r{   r}   r~   r   r   r   r   )r   r   r   r   r1   r1   r2   r     s   Fr   c           	      C   sf   t | }t  }|j|d}|j| d|id|gi|d}d|_t  }t||}t|| t	|S )Nr   UnderlyingReaderrg   ra   T)
r   r   rQ   rw   rc   ru   r   r   r   rv   )	op_typerq   rb   var_namer   r   Z
startop_opZmain_prog_blockr   r1   r1   r2   "__create_shared_decorated_reader__,  s   



r   c                 C   sN   |d ur|nt | }t  }|j|d}|j| d|id|gi|d t|S )Nr   r   rg   ra   )r   r   rQ   rw   rc   rv   )r   rq   rb   r   Znew_reader_nameZmain_blkZ
new_readerr1   r1   r2   $__create_unshared_decorated_reader__;  s   
r   c                 C   s2   t  }|durtt| |d< td| ||dS )a  
    Wrap a double buffer reader. The class Reader contains DecoratedReader and FileReader. Moreover, the DecoratedReader is inherited by CustomReader and BufferedReader. This function is related to BufferedReader. The data will copy to target place with a double buffer queue. If the target place is None, the place that executor perform on will be used.


    Args:
        reader (Variable): The Reader Variable need to be wrapped.
        place (Place|str, optional): The place of target data, such as CPU, GPU, and if use GPU, it's necessary to point out which card is involved. Default is the sample place of executor perform.
            if ``place`` is string, It can be ``cpu``, ``gpu:x``, where ``x`` is the ndex of the GPUs. 
        name (str, optional): Variable name. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Default is None. 

    Returns:
        Variable(Reader): wrapped reader with double buffer.

    Examples:
        ..  code-block:: python
          
            import paddle.fluid as fluid
            reader = fluid.layers.py_reader(capacity=64,
                                            shapes=[(-1, 1, 28, 28), (-1, 1)],
                                            dtypes=['float32', 'int64'],
                                            use_double_buffer=False)
            reader = fluid.layers.double_buffer(reader)
            image, label = fluid.layers.read_file(reader)
    Nr   Zcreate_double_buffer_readerr   )dictr   r   upperr   )rq   r   r   rb   r1   r1   r2   r   F  s   r   c                    sZ   t d  fddtt| j D } jdd| gid|id t|dkr+|d	 S |S )
a  
	:api_attr: Static Graph

    Execute the given reader and get data via it.

    A reader is also a Variable. It can be a raw reader generated by
    `fluid.layers.open_files()` or a decorated one generated by
    `fluid.layers.double_buffer()` .

    Args:

        reader(Variable): The reader to execute.

    Returns:
        Tuple[Variable]: Data read from the given reader.

    Examples:
        .. code-block:: python
          
           import paddle.fluid as fluid
           reader = fluid.layers.py_reader(capacity=64,
                                           shapes=[(-1, 1, 28, 28), (-1, 1)],
                                           dtypes=['float32', 'int64'])
           image, label = fluid.layers.read_file(reader)
    r   c                    s   g | ]	} j d ddqS )Tr   )r$   r"   )Z"create_variable_for_type_inference)r   r   r/   r1   r2   r     s    zread_file.<locals>.<listcomp>readReaderrg   )r#   rI   rJ   r   r   )r   r-   r.   rz   r{   rc   )rq   outr1   r   r2   r   i  s   
r   c                 C   sB   t di t }d|i}|dur||d< |jdi d| i|d dS )a  
    Load operator will load a LoDTensor / SelectedRows variable from disk file.

    Args:
        out(Variable): The LoDTensor / SelectedRows need to be loaded..

        file_path(STRING): Variable will be loaded from "file_path".

        load_as_fp16(BOOLEAN): If true, the tensor will be first loaded and then converted to float16 data type. Otherwise, the tensor will be directly loaded without data type conversion. Default is false..
    Returns:
        None

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            tmp_tensor = fluid.layers.create_tensor(dtype='float32')
            fluid.layers.load(tmp_tensor, "./tmp_tensor.bin")
    r   	file_pathNload_as_fp16rg   ra   )r   )r   r&   rc   )r   r   r   r/   rb   r1   r1   r2   r     s
   r   )NT)NNTN)NNTrN   )NN)9
__future__r   multiprocessingosr'   r   r   Zdata_feederr   Zcontrol_flowr   Zlayer_function_generatorr   r`   r   executorr	   Z	frameworkr
   r   r   r   r   r   Zlayer_helperr   r   r   r   r   r   Zpaddle.fluid.frameworkr   r   r   r   __all__rx   ry   Z
LOD_TENSORr   r3   objectr5   re   rm   rv   r   r   r   r   r   r   r   r   r   r   r1   r1   r1   r2   <module>   sh    ^
c
-(	
 ,
 -
R

#)