
    Αi                        S SK r S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK	J
r
  S SKJr  S SKJr  SSKJr  SSKJrJr  SSKJr  SS	KJrJrJrJrJrJrJrJrJr  SS
K J!r!J"r"J#r#  SSK$J%r%J&r&J'r'J(r(J)q)  SSK*J+r+  Sr,/ r-\+" 5       r.Sq/Sq0S r1S r2S r3 S!S jr4 " S S5      r5\" SS9 " S S5      5       r6 " S S\55      r7 " S S\55      r8\" 5        " S S\55      5       r9 " S S \55      r:g)"    N)_set_expected_place)datatype_to_vartype)
deprecated   )core)BatchedTensorProvider
DataFeeder)global_scope)	Program_current_expected_place_get_paddle_place_get_paddle_place_listdefault_main_programdefault_startup_programin_dygraph_modein_pir_modeprogram_guard)$__create_unshared_decorated_reader___copy_reader_var_monkey_patch_reader_methods)CleanupFuncRegistrar_cleanup_cleanup_mmap_set_SIGCHLD_handlermultiprocess_queue_set)UniqueNameGenerator<   Tc                      [        U 5      S:X  a  [        $ [        U 5      S:X  a  [        U S   [        5      (       d   eU S   qg Nr   r   )lenKEEP_DATA_LOADER_ORDER
isinstanceboolargss    R/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/base/reader.pykeep_data_loader_orderr'   D   s>    
4yA~%%4yA~*T!Wd";";;;!%a    c                      [        U 5      S:X  a  [        $ [        U 5      S:X  a  [        U S   [        5      (       d   eU S   qg r   )r    USE_PINNED_MEMORYr"   r#   r$   s    r&   use_pinned_memoryr+   M   s>    
4yA~  4yA~*T!Wd";";;; Gr(   c                    [        U [        [        45      (       d  U /n / nU  H[  n[        U[        R                  5      (       d(  [        R                  " 5       nUR                  U5        UnUR                  U5        M]     U$ N)r"   listtupler   Place	set_placeappend)placesretptmps       r&   _convert_placesr7   V   sh    ftUm,,
C!TZZ((**,CMM!A

1  Jr(   c                     [         R                  " 5         U(       d+  S[        R                  R                   R	                  5       S'   [
        R                  " [        5        U " 5        H@  n[         R                  " U5      nUR                  U5        [         R                  " U5        MB     UR                  S 5        g ! [         a     g   e = f)NF$FLAGS_dataloader_use_file_descriptor)r   _set_process_signal_handlerpaddlebaseglobalsr   registerr   _convert_to_tensor_listput_remove_tensor_list_mmap_fdsKeyboardInterrupt)batch_reader
data_queuedataloader_use_file_descriptorbatchtensor_lists        r&   _reader_process_looprH   f   s    ((*-  KK$$&6 	%%m4!^E66u=KNN;'--k: $ 	t s   B=C   
CCc                   <    \ rS rSrS rS rS rS r\S 5       r	Sr
g)	DataLoaderBase   c                     S U l         g r-   _placesselfs    r&   __init__DataLoaderBase.__init__   s	    r(   c                     U $ r-    rO   s    r&   __call__DataLoaderBase.__call__   s    r(   c                     [         er-   NotImplementedErrorrO   s    r&   __iter__DataLoaderBase.__iter__       !!r(   c                     [         er-   rX   rO   s    r&   __next__DataLoaderBase.__next__   r\   r(   c                     [         R                  " U5      nUR                  [         R                  :X  a  [	        S5      eU$ )NaB  
	Failed to convert input data to a regular ndarray :
	* Usually this means the input data contains nested lists with different lengths. 
	* Check the reader function passed to 'decorate_batch_generator' to locate the data causes this issue.
	* Please consider using 'base.create_lod_tensor' to convert it to a LoD-Tensor.)npasarraydtypeobject_	TypeError)clsitemarrs      r&   _check_input_array!DataLoaderBase._check_input_array   s:    jj99

"J  
r(   rM   N)__name__
__module____qualname____firstlineno__rQ   rU   rZ   r^   classmethodri   __static_attributes__rT   r(   r&   rJ   rJ      s*    "" 
 
r(   rJ   zpaddle.io.DataLoader)	update_toc                   J    \ rS rSr\       SS j5       r\SS j5       rSrg)
DataLoader   Nc                 `    [        5       (       a  [        U UUUUU5      $ [        U UUUUU5      $ )a)  
.. warning::
  This API will be deprecated in the future, it is recommended to use
  :code:`paddle.io.DataLoader` which supports multi-processes acceleration.

.. note::
  **The framework ensures that the data loading order of DataLoader is exactly the same as the user-defined data source.**

Create a DataLoader object for loading data from Python generator.
Data would be prefetched using Python thread and be pushed
into a queue asynchronously.

The created DataLoader object provides 3 methods to set the data source
:code:`set_sample_generator` , :code:`set_sample_list_generator` and
:code:`set_batch_generator` . Please see the following example codes
to know their usages.

If iterable = True, the created DataLoader object is a Python generator
object, which is iterable using for-range loop.

If iterable = False, the created DataLoader object provides
:code:`start()` and :code:`reset()` method to control the data reading
process.

Args:
    feed_list (list(Tensor)|tuple(Tensor)): feed Tensor list.
        The Tensors should be created by :code:`paddle.static.data()`.
    capacity (int): capacity of the queue maintained in DataLoader.
        The unit is batch number. Set larger capacity if your reader
        is fast.
    use_double_buffer (bool, optional): whether to use double_buffer_reader.
        If use_double_buffer=True, the DataLoader would prefetch next
        batch data asynchronously, so it would speed up data feeding
        and occupies a little more CPU or GPU memory, i.e., the memory
        of one batch input data.
    iterable (bool, optional): whether the created DataLoader is iterable.
    return_list (bool, optional): whether the return value on each device is
        presented as a list. It is only valid when iterable=True.
        If return_list=False, the return value on each device would
        be a dict of str -> DenseTensor, where the key of the dict is
        the name of each fed Tensors. If return_list=True, the
        return value on each device would be a list(DenseTensor). It is
        recommended to use return_list=False in static graph mode and
        use return_list=True in dygraph mode.
    use_multiprocess (bool, optional): whether to use multi-process to
        speed up the data loading process in dygraph. Note: this parameter
        only can be used in the dygraph mode. In the static graph mode,
        whether this parameter is set or not has no effect.
        The Default value is False.
    drop_last (bool, optional): whether to drop the last batches whose
        number is less than the CPU core/GPU card number. The default
        value is True. In training phase, users should not set drop_last=False,
        because all CPU cores/GPU cards must read data from DataLoader.
        In inference phase, users can set drop_last=False, so that the
        last batches whose number is less than the CPU core/GPU card
        number can be tested.

Returns:
    loader (DataLoader): the created DataLoader object.

Examples:
    .. code-block:: python
        :name: example_1

        >>> # Example in static graph mode

        >>> import numpy as np

        >>> import paddle
        >>> import paddle.static as static
        >>> import paddle.nn.functional as F


        >>> BATCH_NUM = 10
        >>> BATCH_SIZE = 16
        >>> EPOCH_NUM = 4

        >>> CLASS_NUM = 10

        >>> ITERABLE = True # whether the created DataLoader object is iterable
        >>> USE_GPU = False # whether to use GPU

        >>> DATA_FORMAT = 'batch_generator' # data format of data source user provides

        >>> paddle.enable_static()

        >>> def simple_net(image, label):
        ...     fc_tmp = static.nn.fc(image, size=CLASS_NUM)
        ...     cross_entropy = F.softmax_with_cross_entropy(image, label)
        ...     loss = paddle.mean(cross_entropy)
        ...     sgd = paddle.optimizer.SGD(learning_rate=1e-3)
        ...     sgd.minimize(loss)
        ...     return loss
        ...
        >>> def get_random_images_and_labels(image_shape, label_shape):
        ...     image = np.random.random(size=image_shape).astype('float32')
        ...     label = np.random.random(size=label_shape).astype('int64')
        ...     return image, label
        ...
        >>> # If the data generator yields one sample each time,
        >>> # use DataLoader.set_sample_generator to set the data source.
        >>> def sample_generator_creator():
        ...     def __reader__():
        ...         for _ in range(BATCH_NUM * BATCH_SIZE):
        ...             image, label = get_random_images_and_labels([784], [1])
        ...             yield image, label
        ...
        ...     return __reader__
        ...
        >>> # If the data generator yield list of samples each time,
        >>> # use DataLoader.set_sample_list_generator to set the data source.
        >>> def sample_list_generator_creator():
        ...     def __reader__():
        ...         for _ in range(BATCH_NUM):
        ...             sample_list = []
        ...             for _ in range(BATCH_SIZE):
        ...                 image, label = get_random_images_and_labels([784], [1])
        ...                 sample_list.append([image, label])
        ...
        ...             yield sample_list
        ...
        ...     return __reader__
        ...
        >>> # If the data generator yields a batch each time,
        >>> # use DataLoader.set_batch_generator to set the data source.
        >>> def batch_generator_creator():
        ...     def __reader__():
        ...         for _ in range(BATCH_NUM):
        ...             batch_image, batch_label = get_random_images_and_labels([BATCH_SIZE, 784], [BATCH_SIZE, 1])
        ...             yield batch_image, batch_label
        ...
        ...     return __reader__
        ...
        >>> # If DataLoader is iterable, use for loop to train the network
        >>> def train_iterable(exe, prog, loss, loader):
        ...     for _ in range(EPOCH_NUM):
        ...         for data in loader():
        ...             exe.run(prog, feed=data, fetch_list=[loss])
        ...
        >>> # If DataLoader is not iterable, use start() and reset() method to control the process
        >>> def train_non_iterable(exe, prog, loss, loader):
        ...     for _ in range(EPOCH_NUM):
        ...         loader.start() # call DataLoader.start() before each epoch starts
        ...         try:
        ...             while True:
        ...                 exe.run(prog, fetch_list=[loss])
        ...         except paddle.core.EOFException:
        ...             loader.reset() # call DataLoader.reset() after catching EOFException
        ...
        >>> def set_data_source(loader, places):
        ...     if DATA_FORMAT == 'sample_generator':
        ...         loader.set_sample_generator(sample_generator_creator(), batch_size=BATCH_SIZE, drop_last=True, places=places)
        ...     elif DATA_FORMAT == 'sample_list_generator':
        ...         loader.set_sample_list_generator(sample_list_generator_creator(), places=places)
        ...     elif DATA_FORMAT == 'batch_generator':
        ...         loader.set_batch_generator(batch_generator_creator(), places=places)
        ...     else:
        ...         raise ValueError('Unsupported data format')
        ...
        >>> image = static.data(name='image', shape=[None, 784], dtype='float32')
        >>> label = static.data(name='label', shape=[None, 1], dtype='int64')

        >>> # Define DataLoader
        >>> loader = paddle.base.io.DataLoader.from_generator(feed_list=[image, label], capacity=16, iterable=ITERABLE)

        >>> # Define network
        >>> loss = simple_net(image, label)

        >>> places = static.cuda_places() if USE_GPU else static.cpu_places()
        >>> set_data_source(loader, places)

        >>> exe = static.Executor(places[0])
        >>> exe.run(static.default_startup_program())

        >>> prog = static.CompiledProgram(static.default_main_program())
        >>> if loader.iterable:
        ...     train_iterable(exe, prog, loss, loader)
        >>> else:
        ...     train_non_iterable(exe, prog, loss, loader)

    .. code-block:: python
        :name: example_2

        >>> # Example in dynamic graph mode.

        >>> import numpy as np

        >>> import paddle
        >>> import paddle.nn as nn
        >>> import paddle.optimizer as opt
        >>> import paddle.distributed as dist

        >>> BATCH_SIZE = 16
        >>> BATCH_NUM = 4
        >>> EPOCH_NUM = 4

        >>> IMAGE_SIZE = 784
        >>> CLASS_NUM = 10

        >>> USE_GPU = False # whether to use GPU

        >>> def _get_random_images_and_labels(image_shape):
        ...         image = np.random.random(size=image_shape).astype('float32')
        ...         label = np.random.randint(0, CLASS_NUM, size=BATCH_SIZE).astype('int64')
        ...         return image, label
        ...
        >>> def __reader__():
        ...         for _ in range(BATCH_NUM):
        ...             batch_image, batch_label = _get_random_images_and_labels(
        ...                 [BATCH_SIZE, IMAGE_SIZE])
        ...             yield batch_image, batch_label
        ...
        >>> def random_batch_reader():
        ...     return __reader__
        ...
        >>> class LinearNet(nn.Layer):
        ...     def __init__(self):
        ...         super().__init__()
        ...         self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM)
        ...
        ...     @paddle.jit.to_static
        ...     def forward(self, x):
        ...         return self._linear(x)
        ...
        >>> # set device
        >>> paddle.set_device('gpu' if USE_GPU else 'cpu')

        >>> # doctest: +SKIP('`paddle.jit.to_static` can not run in xdoctest')
        >>> # create network
        >>> layer = LinearNet()
        >>> dp_layer = paddle.DataParallel(layer)
        >>> loss_fn = nn.CrossEntropyLoss()
        >>> adam = opt.Adam(learning_rate=0.001, parameters=dp_layer.parameters())

        >>> # create data loader
        >>> loader = paddle.base.io.DataLoader.from_generator(capacity=5)
        >>> loader.set_batch_generator(random_batch_reader())

        >>> for epoch_id in range(EPOCH_NUM):
        ...     for batch_id, (image, label) in enumerate(loader()):
        ...         out = layer(image)
        ...         loss = loss_fn(out, label)
        ...
        ...         loss.backward()
        ...
        ...         adam.step()
        ...         adam.clear_grad()
        ...         print("Epoch {} batch {}: loss = {}".format(
        ...             epoch_id, batch_id, np.mean(loss.numpy())))
        ...
        >>> # doctest: -SKIP
)r   DygraphGeneratorLoaderGeneratorLoader)	feed_listcapacityuse_double_bufferiterablereturn_listuse_multiprocess	drop_lasts          r&   from_generatorDataLoader.from_generator   sN    L )!   #! r(   c                     [        XU5      $ )a/  
.. warning::
  This API will be deprecated in the future, it is recommended to use
  :code:`paddle.io.DataLoader` which supports multi-processes acceleration.

Create an iterable DataLoader object for loading data from Dataset.
Dataset is only supported in Linux system currently.

Args:
    dataset (InMemoryDataset|QueueDataset): the dataset object.
    places (list(CUDAPlace)|list(CPUPlace)|list(str)): places where the result
        data should be converted. If places is list of string, the string in the list
        can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, where x is the index of the GPUs.
    drop_last (bool, optional): whether to drop the last batch whose
        sample number is less than batch size. If drop_last = True,
        they would be dropped. If drop_last = False, they would be kept.

Returns:
    loader (DataLoader): the created DataLoader object, which can be
        treated as a Python generator.

Examples:

    .. code-block:: python

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

        >>> paddle.enable_static()

        >>> image = static.data(name='image', shape=[None, 784], dtype='float32')
        >>> label = static.data(name='label', shape=[None, 1], dtype='int64')

        >>> dataset = paddle.distributed.QueueDataset()
        >>> dataset.init(
        ...     batch_size=32,
        ...     pipe_command='cat',
        ...     use_var=[image, label])
        >>> dataset.set_filelist(['a.txt', 'b.txt', 'c.txt'])

        >>> loader = paddle.base.io.DataLoader.from_dataset(dataset, static.cpu_places())
)DatasetLoader)datasetr3   r~   s      r&   from_datasetDataLoader.from_dataset  s    X Wi88r(   rT   )NNTTFFTT)rk   rl   rm   rn   staticmethodr   r   rp   rT   r(   r&   rs   rs      s@    V Vp +9 +9r(   rs   c                       \ rS rSrSr      SS jr\S 5       r\S 5       rS r	S r
S	 rS
 rS rS rS rS rS rS rS rS r SS jrSS jrSS jrSrg)rv   i  z
The GeneratorLoader of dygraph

The multiprocess dygraph GeneratorLoader's most functions are different from
static graph GeneratorLoader, Separate implementation to keep code readable.
Nc                 d   S U l         S U l        Xl        [        U l        U(       d  [        S5      eX l        X0l        U(       d  [        R                  " S5        SU l
        U(       d  [        R                  " S5        SU l        X`l        U R                  (       aE  [        R                  S:X  d  [        R                  S:X  a  [        R                  " S5        SU l        U R                  (       a  S U l        S U l        S U l        S U l        ['        5       c  SU l        g ['        5       U l        g )	NPlease give value to capacity.zYPlease NOTE: DygraphGeneratorLoader supports iterable mode only. Change to iterable mode.Tz^Please NOTE: DygraphGeneratorLoader supports returning as list only. Change to return as list.darwinwin32zdNOTE: DygraphGeneratorLoader with multiprocess mode is not currently supported on MacOs and Windows.F)_batch_readerrN   
_feed_listQUEUE_GET_TIMEOUT_timeout
ValueError	_capacity_use_double_bufferwarningswarn	_iterable_return_list_use_multiprocesssysplatform_data_queue_process_blocking_queue_threadr+   _pin_memory)rP   rx   ry   rz   r{   r|   r}   s          r&   rQ   DygraphGeneratorLoader.__init__  s     "#)=>>!"3MMk MMp ! "2!!LLH$(?MMv &+D"!!#D DM  $
 %'/D 	5F5H 	r(   c                     U R                   $ r-   )r   rO   s    r&   queueDygraphGeneratorLoader.queue*  s    ###r(   c                     U R                   $ r-   r   rO   s    r&   r{   DygraphGeneratorLoader.iterable.      ~~r(   c                     U R                   b    U R                   R                  5         M  g ! [        R                   a     Of = f[        R
                  " U R                   5        g r-   )r   
get_nowaitr   Emptyr   removerO   s    r&   _clear_and_remove_data_queue3DygraphGeneratorLoader._clear_and_remove_data_queue2  s`    '$$//1  ( {{  #))$*:*:;s   - AAc                 x    U R                   nUb+  U R                  R                  5         UR                  5         g g r-   )r   r   closejoinrP   threads     r&   _wait_thread_ends(DygraphGeneratorLoader._wait_thread_ends<  s1      &&(KKM r(   c                     U R                   nUb0  UR                  5         [        R                  " [	        U 5      5        g g r-   )r   r   r   _erase_process_pidsid)rP   processs     r&   _wait_process_ends)DygraphGeneratorLoader._wait_process_endsB  s1    --LLN$$RX. r(   c                    U R                  5         U R                  (       a  U R                  5         / U l        / U l        / U l        / U l        [        R                  " [        R                  " 5       U R                  S5      U l        S U l        [        R                  " U R                  U R                  U R                  U R
                  U R                  U R                  U R                   SU R"                  5	      U l        g )NFT)r   r   r   
_var_names_shapes_dtypes_need_check_feedr    init_dense_tensor_blocking_queueVariabler   r   _readercreate_py_readerr   rN   r   r   rO   s    r&   _init_iterable%DygraphGeneratorLoader._init_iterableI  s     !!##% "#DDMMOT^^U 
 ,,JJOOLLLL!!LL##

r(   c                    U R                   (       Gag  U R                  5         [        R                  " U R                  5      U l        [        R                  " U R
                  5        [        R                  " [        U R                  U R
                  S4S9U l        SU R                  l        U R                  R                  5         [        R                  " [!        U 5      U R                  R"                  /5        [%        5         [&        R(                  " 5       U l        [&        R,                  " U R.                  [1        5       4S9U l        SU R2                  l        U R2                  R                  5         g [&        R,                  " U R4                  [1        5       4S9U l        SU R2                  l        U R2                  R                  5         g )NFtargetr%   T)r   r   multiprocessingQueuer   r   r   addProcessrH   r   r   daemonstartr   _set_process_pidsr   pidr   	threadingEvent_thread_done_eventThread$_reader_thread_loop_for_multiprocessr   r   %_reader_thread_loop_for_singleprocessrO   s    r&   _startDygraphGeneratorLoader._starta  sN   !!!--/.44T^^DD #&&t'7'78+33+(($*:*:EBDM $(DMM MM! ""2d8dmm.?.?-@A " '0oo&7D#$++@@-/1DL #'DLLLL $++AA-/1DL #'DLLLL r(   c                     U R                   R                  5         U R                  5         U R                  (       a  U R	                  5         g g r-   )r   resetr   r   r   rO   s    r&   _resetDygraphGeneratorLoader._reset  s8     !!##% "r(   c                     U R                   (       d   S5       eU R                  c   S5       eU R                  5         U R                  5         U $ NzDataLoader is not iterablez)Data source of DataLoader has not set yet)r{   r   r   r   rO   s    r&   rZ   DygraphGeneratorLoader.__iter__  sL    }}:::}!!- 	
7	
- 	r(   c                      [         R                  R                  U R                  R	                  5       S   5      $ ! [
         a    U R                  5         e f = f)Nr   )r   eagerread_next_tensor_listr   read_next_listStopIterationr   rO   s    r&   r^   DygraphGeneratorLoader.__next__  sP    	::33++-a0   	KKM	s	   9< Ac                 l    U R                   R                  5         U R                  R                  5         g r-   )r   setr   r   rO   s    r&   _exit_thread_expectedly.DygraphGeneratorLoader._exit_thread_expectedly  s&    ##%""$r(   c                     U R                   R                  5         U R                  R                  5         [        R
                  " S5        g )Nz-DataLoader reader thread raised an exception!)r   r   r   killloggingerrorrO   s    r&   _exit_thread_unexpectedly0DygraphGeneratorLoader._exit_thread_unexpectedly  s3    ##%!!#EFr(   c                 0   [         R                  " S[        [        U 5      5      -   5        [	        U5        U R
                  R                  5       (       d   U R                  R                  U R                  S9nU R
                  R                  5       (       d~  Ubk   [         R                  " 5       nU H  nUR                  U5        M     U R                   R#                  U5      (       d  U R                   R%                  5         OU R'                  5         U R
                  R                  5       (       d  M  g g ! [         a-  nU R                  5         [        R                  " S5        UeS nAff = f! [         a  nU R                  5         UeS nAff = f)NDataloader_)timeoutzLDataLoader reader thread failed to read data from the multiprocessing.Queue.)r   set_current_thread_namestrr   r   r   is_setr   getr   	Exceptionr   r   r   DenseTensorArrayr2   r   pushr   r   )rP   legacy_expected_placerG   earraytensors         r&   r   ;DygraphGeneratorLoader._reader_thread_loop_for_multiprocess  sM   $$]SD]%BC12))0022 #..224==2I **1133*  $ 5 5 7&1F!LL0 '2#3388?? 00668
 002I ))0022   ..0b $ %  668 s1   #D: A)E4 :
E1(E,,E14
F>FFc                     [         R                  " S[        [        U 5      5      -   5        [	        U5        U R                  5        H  n[         R                  " 5       nU H  n[        U[         R                  5      (       dM  U R                  U5      n[         R                  " 5       nUR                  U[         R                  " 5       5        UnUR                  U5        M     U R                  R                  U5      (       a  M    O   U R                  R                  5         S U l        g ! ["         a>  nU R                  R%                  5         S U l        [&        R(                  " S5        UeS nAff = f)Nr   z4DygraphDataLoader reader thread raised an exception.)r   r   r   r   r   r   r   r"   DenseTensorri   r   CPUPlacer2   r   r   r   r   r   r   r   warning)rP   r   sampler   rg   r6   r   s          r&   r   <DygraphGeneratorLoader._reader_thread_loop_for_singleprocess  s"   	((RX)FG 56,,.--/"D%dD,<,<==#66t<"..0dmmo6"LL& # ++0077 /   &&(DL 	  %%'DLOOF G	s   DD. %D. .
E689E11E6c                     US:  d   S5       e[        U[        [        45      (       a  [        U5      nO[	        U5      nU R                  [        R                  " XUS9US9  U $ )Nr    batch_size must be larger than 0
batch_sizer~   r3   )r"   r.   r/   r   r   set_sample_list_generatorr;   rF   )rP   readerr  r~   r3   s        r&   set_sample_generator+DygraphGeneratorLoader.set_sample_generator  sf     A~AAA~ftUm,,+F3F&v.F&&LL)L 	' 	
 r(   c                    ^ [        U[        [        45      (       a  [        U5      nO[	        U5      nU4S jnU R                  X25        U $ )Nc               3      >#    T" 5        He  n / nU  HV  n[        U5       HD  u  p4[        U5      [        U5      :  a  UR                  U/5        M1  X   R                  U5        MF     MX     Uv   Mg     g 7fr-   )	enumerater    r2   )rF   slotsitemsirg   r  s        r&   __batch_reader_impl__ODygraphGeneratorLoader.set_sample_list_generator.<locals>.__batch_reader_impl__	  se     "E#,U#3u:E
2!LL$0!HOOD1	 $4 #  "s   A2A5)r"   r.   r/   r   r   set_batch_generator)rP   r  r3   r  s    `  r&   r
  0DygraphGeneratorLoader.set_sample_list_generator  sC    ftUm,,+F3F&v.F		 	  !6?r(   c                     [        U[        [        45      (       a  [        U5      nO[	        U5      nXl        Uc
  [        5       n[        U5      U l        [        U R                  5      S:X  d   S5       eU $ )Nr   z-Number of places must be 1 in imperative mode)
r"   r.   r/   r   r   r   r   r7   rN   r    rP   r  r3   s      r&   r  *DygraphGeneratorLoader.set_batch_generator  sn    ftUm,,+F3F&v.F#>,.F&v.4<< A% 	
;	
% r(   )r   r   r   r   r   r   r   r   r   rN   r   r   r   r   r   r   r   r   r   r   )NNTTTFTNr-   )rk   rl   rm   rn   __doc__rQ   propertyr   r{   r   r   r   r   r   r   rZ   r^   r   r   r   r   r  r
  r  rp   rT   r(   r&   rv   rv     s     7
r $ $  </
0'!R&%G
)3V> :>(r(   rv   c                       \ rS rSr      SS jrS rS rS r\S 5       r	\S 5       r
S	 rS
 rS rS rS rS r SS jrSS jrSS jrSrg)rw   i&  Nc                 P   S U l         S U l        S U l        S U l        Xl        SU l        X`l        [        5       U l        U(       d  [        S5      eX@l
        XPl        U R                  (       d  [        S5      eX0l        X l        U R                  (       d  U R                  5         g g )NFr   z0Feed list must be given under static graph mode.)_tensor_readerrN   r   _queuer   _exited
_drop_lastr'   _keep_orderr   r   r   r   r   r   _init_non_iterable)rP   rx   ry   rz   r{   r|   r~   s          r&   rQ   GeneratorLoader.__init__'  s     ###13=>>!'NOO"3!~~##% r(   c                     U R                   nUb=  U R                  (       a+  U R                  R                  5         UR	                  5         g g g r-   )r   r   r!  r   r   r   s     r&   r   !GeneratorLoader._wait_thread_endsC  s:     $..KKKKM #1r(   c                    U R                  5         U R                   Vs/ s H  oR                  PM     snU l        U R                   Vs/ s H  oR                  PM     snU l        [        5       (       aV  U R                   Vs/ s H  n[        UR                     PM     snU l	        U R                   Vs/ s H  nSPM     snU l
        OdU R                   Vs/ s H  oR                  PM     snU l	        U R                   Vs/ s H  oR                  R                  5       PM     snU l
        [        R                  " [        R                  " 5       U R                   U R"                  5      U l        S U l        [        R(                  " U R*                  U R                  U R
                  U R                  U R                  U R,                  U R.                  U R0                  S5	      U l        g s  snf s  snf s  snf s  snf s  snf s  snf )NF)r   r   namer   shaper   r   r   rc   r   r   descneed_check_feedr   r   r   r   r$  r!  r   r   r   rN   r   r#  )rP   vs     r&   r   GeneratorLoader._init_iterableK  sz    +/??;?a66?;)-9A9==6:oo6E#AGG,oDL 59OO$DOqUO$DD!-1__=_GG_=DL26//%2AQ&&(/%D! ;;MMOT^^T-=-=
 ,,JJOOLLLL!!LL##OO

! <9 %E=%s#   G/
G4G97G>H#Hc                 P   / n/ n/ n/ n/ n/ nU R                    H  nUR                  UR                  5        UR                  UR                  5        UR                  [        UR                  5      5        UR                  UR                  5        [        5       (       a$  UR                  S5        UR                  S5        M  UR                  [        UR                  R                  5       5      5        UR                  UR                  5        M     [        S5      n[        S5      n	[        S5      n
[        5       R                  U5      n[        R                  " XR                   U R"                  5      U l        U R"                  (       a  ['        5       R)                  5       nO[+        5       R)                  5       nUR-                  U	S9nU Vs/ s H  n[        U5      PM     nnUR/                  SSU/0SU/0UUUUUS.S	9  UR                  R1                  U5        S
Ul        S
Ul        U R"                  (       a   UnUnU R$                  R6                  Ul        O;[9        ['        5       R)                  5       U5      nS
Ul        S
Ul        [;        U5      nU R<                  (       a  [?        SU0 U
S9nUR6                  Ul        UnUU l         ['        5       R)                  5       R/                  SSU R@                  /0SU R                   0SU RB                  0S	9  g s  snf )Nr   lod_tensor_blocking_queuer   double_buffer)r*  blocking_queueOut)shape_concat
lod_levelsdtypesr-  ranks)typeinputsoutputsattrsTcreate_double_buffer_readerreadReaderr~   )"r   r2   rc   extendr+  r    r   intr,  r-  	lod_level!data_loader_unique_name_generatorr
   varr   r   r   r$  r!  r   current_blockr   
create_var	append_op
set_dtypespersistablestop_gradientr   r   r   r   r   r   r#  )rP   r6  r7  r5  r8  shapesr-  	feed_data
queue_namereader_namedouble_buffer_namerD  block
reader_vart	dtype_intmain_prog_varr  double_buffer_readers                      r&   r%  "GeneratorLoader._init_non_iterablei  s   
IMM)//*	0LLY__-.MM)//*}}&&q)!!!$&&s9>>+I+I+K'LM!!)"5"56 ) 7'

 88JK>On  ,;;!1!1
 (*88:E+-;;=E%%;%7
%+,VSVV	,#$zl3ZL) ,(##2	 	 	
 	""6*!%
#'
 &M"F;;,,FL-$&446
M +/M'(,M%0?F""#G-'	$  *0 &)F,,.88t||n-DOO,0	 	9 	
] -s   L#c                     U R                   $ r-   )r!  rO   s    r&   r   GeneratorLoader.queue  s    {{r(   c                     U R                   $ r-   r   rO   s    r&   r{   GeneratorLoader.iterable  r   r(   c                     U R                   (       d   S5       eU R                  c   S5       eU R                  5         U R                  5         U $ r   )r{   r   r   r   rO   s    r&   rZ   GeneratorLoader.__iter__  sL    }}:::}"". 	
7	
. 	r(   c                 b    U R                   (       aK  U R                  R                  5       n[        [	        U5      5       H  nX   R                  5       X'   M     U$ U R                  R                  5       $ ! [         a,    U R                  R                  5         U R                  5         e f = fr-   )r   r   r   ranger    _move_to_list	read_nextr   r!  r   r   )rP   datar  s      r&   r^   GeneratorLoader.__next__  s    	  ||224s4y)A"g335DG *||--// 	KKKKM	s   AA8 A8 86B.c                 T    U R                   (       a   S5       eU R                  5         g )Nz4start() cannot be called when DataLoader is iterable)r   r   rO   s    r&   r   GeneratorLoader.start  $    >> 	
B	
! 	r(   c                 T    U R                   (       a   S5       eU R                  5         g )Nz4reset() cannot be called when DataLoader is iterable)r   r   rO   s    r&   r   GeneratorLoader.reset  re  r(   c                    ^  U 4S jn[         R                  " U[        5       4S9T l        ST R                  l        T R                  R                  5         g )Nc                   >  [         R                  " S[        [        T5      5      -   5        [	        U 5        TR
                  R                  S5      (       d4  TR                  (       a  g TR
                  R                  S5      (       d  M4  TR                  5        H  n[         R                  " 5       nU H  n[        U[         R                  5      (       dM  TR                  U5      n[         R                  " 5       nUR                  U[         R                  " 5       5        UnUR                  U5        M     TR
                  R!                  U5      (       a  M    O   TR
                  R#                  5         S Tl        g ! [&         a>  nTR
                  R)                  5         S Tl        [*        R,                  " S5        UeS nAff = f)Nr   r   z$Your reader has raised an exception!)r   r   r   r   r   r!  wait_for_initedr"  r   r   r"   r   ri   r   r  r2   r   r   r   r   r   r   r  )r   tensorsr   rg   r6   r   rP   s         r&   __thread_main__/GeneratorLoader._start.<locals>.__thread_main__  sQ   ,,]SD]-JK#$9:++55a88|| ++55a88  $224G 113E ')$0@0@AA#'#:#:4#@D"&"2"2"4CGGD$--/:#&DT* !(  ;;++E22  5 !!##   "# FG	s+   A'F + F CF %F 
G9GGr   T)r   r   r   r   r   r   )rP   rl  s   ` r&   r   GeneratorLoader._start  sG    	@ !''"*A*C)E
 #r(   c                     U R                   R                  5         SU l        U R                  nUb  UR	                  5         SU l        U R
                  R                  5         g )NTF)r!  r   r"  r   r   r   r   r   s     r&   r   GeneratorLoader._reset  sH    KKMr(   c                    US:  d   S5       e[        U[        [        45      (       a  [        U5      nO[	        U5      nSn[        5       (       d'  U R                   H  nUR                  S:w  d  M  Sn  O   U(       a%  U R                  [        R                  " XUS9US9  U $ [        U R                  [        R                  " 5       UUUS9nU R                  XS9  U $ )Nr   r  FTr  r	  )rx   placer  	generatorr~   )r"   r.   r/   r   r   r   r   rB  r
  r;   rF   r   r   r  r  )rP   r  r  r~   r3   has_lodfs          r&   r  $GeneratorLoader.set_sample_generator"  s     A~AAA~ftUm,,+F3F&v.F}}__;;!#"G %
 **Y 	 +   +//mmo% #F $$V$;r(   c                 n  ^ ^^^ [        U[        [        45      (       a  [        U5      nO[	        U5      n[        [        5       [        5       5         [        T R                  [        R                  " 5       S9mUU4S jnUmS S S 5        UU 4S jnT R                  XB5        T $ ! , (       d  f       N(= f)N)rx   rr  c               3   P   >#    T" 5        H  n TR                  U 5      v   M     g 7fr-   )feed)rg   feederr  s    r&   decorate_readerBGeneratorLoader.set_sample_list_generator.<locals>.decorate_readerM  s!     "HD ++d++ %s   #&c               3      >#    T" 5        H.  n TR                    Vs/ s H  oUR                     PM     snv   M0     g s  snf 7fr-   )r   r*  )r  rD  paddle_readerrP   s     r&   __tensor_reader_impl__IGeneratorLoader.set_sample_list_generator.<locals>.__tensor_reader_impl__S  s4     &26//B/3SXX/BB )Bs   A>A)r"   r.   r/   r   r   r   r   r	   r   r   r  r  )rP   r  r3   r{  r  rz  r~  s   ``   @@r&   r
  )GeneratorLoader.set_sample_list_generatorC  s    ftUm,,+F3F&v.F79gi0//F, ,M 1	C 	  !7@! 10s   1B&&
B4c                    [        U[        [        45      (       a  [        U5      nO[	        U5      nXl        U R                  (       a  Uc   S5       e[        U5      U l        U $ Ub  [        R                  " S5        U $ )Nz1Places cannot be None when DataLoader is iterablez7places would be omitted when DataLoader is not iterable)r"   r.   r/   r   r   r   r   r7   rN   r   infor  s      r&   r  #GeneratorLoader.set_batch_generatorZ  s}    ftUm,,+F3F&v.F$>>% C% +62DL 	 !M r(   )r   r#  r   r"  r   r   r$  r   rN   r!  r   r   r   r   r   r   r   )NNTTFTr  r-   )rk   rl   rm   rn   rQ   r   r   r%  r  r   r{   rZ   r^   r   r   r   r   r  r
  r  rp   rT   r(   r&   rw   rw   &  s     &8
<Z
x    %N :>B.r(   rw   c                       \ rS rSrSr     SS jr\S 5       r\S 5       rS r	S r
S	 rS
 r SS jrSS jrSS jrSrg)PyReaderim  a	  
Create a reader object for data feeding in Python.
Data would be prefetched using Python thread and be pushed
into a queue asynchronously. Data in the queue would be extracted
automatically when `Executor.run(...)` is called.

Args:
    feed_list (list(Variable)|tuple(Variable)): feed variable list.
        The variables should be created by :code:`paddle.static.data()`.
    capacity (int): capacity of the queue maintained in PyReader.
        The unit is batch number. Set larger capacity if your reader
        is fast.
    use_double_buffer (bool): whether to use double_buffer_reader.
        If use_double_buffer=True, PyReader would prefetch next
        batch data asynchronously, so it would speed up data feeding
        and occupies a little more CPU or GPU memory, i.e., the memory
        of one batch input data.
    iterable (bool): whether the created PyReader is iterable.
    return_list (bool): whether the return value on each device is
        presented as a list. It is only valid when iterable=True.
        If return_list=False, the return value on each device would
        be a dict of str -> DenseTensor, where the key of the dict is
        the name of each fed variables. If return_list=True, the
        return value on each device would be a list(DenseTensor). It is
        recommended to use return_list=False in static graph mode and
        use return_list=True in dygraph mode.

Returns:
    the created reader object.

Return type:
    reader(Reader)

Examples:

    1. If iterable = False, the created PyReader object is almost the
       same as :code:`base.layers.py_reader()`. Operators would be
       inserted into the program. User should call :code:`start()`
       before each epoch and catch :code:`base.core.EOFException`
       thrown by :code:`Executor.run()` when epoch ends. Once the
       exception is caught, user should call :code:`reset()` to reset
       the reader manually.

    .. code-block:: python
        :name: example_1

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

        >>> paddle.enable_static()

        >>> EPOCH_NUM = 3
        >>> ITER_NUM = 5
        >>> BATCH_SIZE = 3

        >>> def network(image, label):
        ...     # User-defined network, here is an example of softmax regression.
        ...     predict = paddle.static.nn.fc(x=image, size=10, activation='softmax')
        ...     return paddle.nn.functional.cross_entropy(
        ...         input=predict, label=label,
        ...         reduction='none', use_softmax=False
        ...     )

        >>> def reader_creator_random_image_and_label(height, width):
        ...     def reader():
        ...         for i in range(ITER_NUM):
        ...             fake_image = np.random.uniform(low=0,
        ...                                             high=255,
        ...                                             size=[height, width])
        ...             fake_label = np.ones([1])
        ...             yield fake_image, fake_label
        ...     return reader

        >>> image = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32')
        >>> label = paddle.static.data(name='label', shape=[None, 1], dtype='int64')

        >>> reader = base.io.PyReader(feed_list=[image, label],
        ...                             capacity=4,
        ...                             iterable=False)

        >>> user_defined_reader = reader_creator_random_image_and_label(784, 784)
        >>> reader.decorate_sample_list_generator(
        ...     paddle.batch(user_defined_reader, batch_size=BATCH_SIZE))
        >>> loss = network(image, label)
        >>> executor = base.Executor(base.CPUPlace())
        >>> executor.run(base.default_startup_program())
        >>> for i in range(EPOCH_NUM):
        ...     reader.start()
        ...     while True:
        ...         try:
        ...             executor.run(feed=None)
        ...         except base.core.EOFException:
        ...             reader.reset()
        ...             break

    2. If iterable=True, the created PyReader object is decoupled with
       the program. No operator would be inserted into the program.
       In this case, the created reader is a Python generator, which
       is iterable. User should feed the data yielded from PyReader
       object into :code:`Executor.run(feed=...)`.

    .. code-block:: python
        :name: example_2

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

        >>> paddle.enable_static()

        >>> EPOCH_NUM = 3
        >>> ITER_NUM = 5
        >>> BATCH_SIZE = 10

        >>> def network(image, label):
        ...     # User-defined network, here is an example of softmax regression.
        ...     predict = paddle.static.nn.fc(x=image, size=10, activation='softmax')
        ...     return paddle.nn.functional.cross_entropy(
        ...         input=predict, label=label,
        ...         reduction='none', use_softmax=False
        ...     )

        >>> def reader_creator_random_image(height, width):
        ...     def reader():
        ...         for i in range(ITER_NUM):
        ...             fake_image = np.random.uniform(low=0, high=255, size=[height, width])
        ...             fake_label = np.ones([1])
        ...             yield fake_image, fake_label
        ...     return reader

        >>> image = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32')
        >>> label = paddle.static.data(name='label', shape=[None, 1], dtype='int64')
        >>> reader = base.io.PyReader(feed_list=[image, label], capacity=4, iterable=True, return_list=False)

        >>> user_defined_reader = reader_creator_random_image(784, 784)
        >>> reader.decorate_sample_list_generator(
        ...     paddle.batch(user_defined_reader, batch_size=BATCH_SIZE),
        ...         base.core.CPUPlace())

        >>> loss = network(image, label)
        >>> executor = base.Executor(base.CPUPlace())
        >>> executor.run(base.default_startup_program())

        >>> for _ in range(EPOCH_NUM):
        ...     for data in reader():
        ...         executor.run(feed=data, fetch_list=[loss])

    3. If return_list=True, the return values would be presented as list instead of dict.
       This is usually used in dygraph mode.

    .. code-block:: python
        :name: example_3

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

        >>> ITER_NUM = 5
        >>> BATCH_SIZE = 10

        >>> def reader_creator_random_image(height, width):
        ...     def reader():
        ...         for i in range(ITER_NUM):
        ...             yield np.random.uniform(low=0, high=255, size=[height, width]), \
        ...                 np.random.random_integers(low=0, high=9, size=[1])
        ...     return reader

        >>> place = base.CPUPlace()
        >>> with base.dygraph.guard(place):
        ...     py_reader = base.io.PyReader(capacity=2, return_list=True)
        ...     user_defined_reader = reader_creator_random_image(784, 784)
        ...     py_reader.decorate_sample_list_generator(
        ...         paddle.batch(user_defined_reader, batch_size=BATCH_SIZE),
        ...         place)
        ...     for image, label in py_reader():
        ...         relu = paddle.nn.functional.relu(image)
Nc                 <    [         R                  XX4U5      U l        g r-   )rs   r   _loader)rP   rx   ry   rz   r{   r|   s         r&   rQ   PyReader.__init__"  s     "00!2k
r(   c                 .    U R                   R                  $ r-   )r  r   rO   s    r&   r   PyReader.queue.  s    ||!!!r(   c                 .    U R                   R                  $ r-   )r  r{   rO   s    r&   r{   PyReader.iterable2  s    ||$$$r(   c                 6    U R                   R                  5       $ r-   )r  rZ   rO   s    r&   rZ   PyReader.__iter__6      ||$$&&r(   c                 6    U R                   R                  5       $ r-   )r  r^   rO   s    r&   r^   PyReader.__next__9  r  r(   c                 8    U R                   R                  5         g)a_  
Start the data feeding thread.
Can only call when the reader object is not iterable.

Example:
    .. code-block:: python

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

        >>> paddle.enable_static()

        >>> BATCH_SIZE = 10

        >>> def generator():
        ...     for i in range(5):
        ...         yield np.random.uniform(low=0, high=255, size=[784, 784]),

        >>> image = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32')
        >>> reader = base.io.PyReader(feed_list=[image], capacity=4, iterable=False)
        >>> reader.decorate_sample_list_generator(
        ...     paddle.batch(generator, batch_size=BATCH_SIZE))

        >>> executor = base.Executor(base.CPUPlace())
        >>> executor.run(base.default_startup_program())
        >>> for i in range(3):
        ...     reader.start()
        ...     while True:
        ...         try:
        ...             executor.run(feed=None)
        ...         except base.core.EOFException:
        ...             reader.reset()
        ...             break
N)r  r   rO   s    r&   r   PyReader.start<      H 	r(   c                 8    U R                   R                  5         g)a  
Reset the reader object when :code:`base.core.EOFException` raises.
Can only call when the reader object is not iterable.

Example:
    .. code-block:: python

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

        >>> paddle.enable_static()

        >>> BATCH_SIZE = 10

        >>> def generator():
        ...     for i in range(5):
        ...         yield np.random.uniform(low=0, high=255, size=[784, 784]),

        >>> image = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32')
        >>> reader = base.io.PyReader(feed_list=[image], capacity=4, iterable=False)
        >>> reader.decorate_sample_list_generator(
        ...     paddle.batch(generator, batch_size=BATCH_SIZE))

        >>> executor = base.Executor(base.CPUPlace())
        >>> executor.run(base.default_startup_program())
        >>> for i in range(3):
        ...     reader.start()
        ...     while True:
        ...         try:
        ...             executor.run(feed=None)
        ...         except base.core.EOFException:
        ...             reader.reset()
        ...             break
N)r  r   rO   s    r&   r   PyReader.resetb  r  r(   c                 <    U R                   R                  XX45        g)a
  
Set the data source of the PyReader object.

The provided :code:`sample_generator` should be a Python generator,
which yields list(numpy.ndarray)-typed data of each sample.

:code:`places` must be set when the PyReader object is iterable.

If all inputs have no lods, this method is faster than
:code:`decorate_sample_list_generator(paddle.batch(sample_generator, ...))` .

Args:
    sample_generator (generator): Python generator that yields
        list(numpy.ndarray)-typed sample data.
    batch_size (int): batch size. Must be larger than 0.
    drop_last (bool): Whether to drop the last batch when sample number
        is less than batch_size.
    places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
        be provided when PyReader is iterable.

Example:
    .. code-block:: python

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

        >>> paddle.enable_static()

        >>> EPOCH_NUM = 3
        >>> ITER_NUM = 15
        >>> BATCH_SIZE = 3

        >>> def network(image, label):
        ...     # User-defined network, here is an example of softmax regression.
        ...     predict = paddle.static.nn.fc(x=image, size=10, activation='softmax')
        ...     return paddle.nn.functional.cross_entropy(
        ...         input=predict, label=label,
        ...         reduction='none', use_softmax=False
        ...     )

        >>> def random_image_and_label_generator(height, width):
        ...     def generator():
        ...         for i in range(ITER_NUM):
        ...             fake_image = np.random.uniform(low=0,
        ...                                             high=255,
        ...                                             size=[height, width])
        ...             fake_label = np.array([1])
        ...             yield fake_image, fake_label
        ...     return generator

        >>> image = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32')
        >>> label = paddle.static.data(name='label', shape=[None, 1], dtype='int64')
        >>> reader = base.io.PyReader(feed_list=[image, label], capacity=4, iterable=True)

        >>> user_defined_generator = random_image_and_label_generator(784, 784)
        >>> reader.decorate_sample_generator(user_defined_generator,
        ...                                     batch_size=BATCH_SIZE,
        ...                                     places=[base.CPUPlace()])
        >>> loss = network(image, label)
        >>> executor = base.Executor(base.CPUPlace())
        >>> executor.run(base.default_startup_program())

        >>> for _ in range(EPOCH_NUM):
        ...     for data in reader():
        ...         executor.run(feed=data, fetch_list=[loss])
N)r  r  )rP   sample_generatorr  r~   r3   s        r&   decorate_sample_generator"PyReader.decorate_sample_generator  s    L 	)))	
r(   c                 :    U R                   R                  X5        g)aT	  
Set the data source of the PyReader object.

The provided :code:`reader` should be a Python generator,
which yields list(numpy.ndarray) typed batched data.

:code:`places` must be set when the PyReader object is iterable.

Args:
    reader (generator): Python generator that yields
        list(numpy.ndarray)-typed batched data.
    places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
        be provided when PyReader is iterable.

Example:
    .. code-block:: python

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

        >>> paddle.enable_static()

        >>> EPOCH_NUM = 3
        >>> ITER_NUM = 15
        >>> BATCH_SIZE = 3

        >>> def network(image, label):
        ...     # User-defined network, here is an example of softmax regression.
        ...     predict = paddle.static.nn.fc(x=image, size=10, activation='softmax')
        ...     return paddle.nn.functional.cross_entropy(
        ...         input=predict, label=label,
        ...         reduction='none', use_softmax=False
        ...     )

        >>> def random_image_and_label_generator(height, width):
        ...     def generator():
        ...         for i in range(ITER_NUM):
        ...             fake_image = np.random.uniform(low=0,
        ...                                             high=255,
        ...                                             size=[height, width])
        ...             fake_label = np.ones([1])
        ...             yield fake_image, fake_label
        ...     return generator

        >>> image = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32')
        >>> label = paddle.static.data(name='label', shape=[None, 1], dtype='int64')
        >>> reader = base.io.PyReader(feed_list=[image, label], capacity=4, iterable=True)

        >>> user_defined_generator = random_image_and_label_generator(784, 784)
        >>> reader.decorate_sample_list_generator(
        ...     paddle.batch(user_defined_generator, batch_size=BATCH_SIZE),
        ...     base.core.CPUPlace())

        >>> loss = network(image, label)
        >>> executor = base.Executor(base.core.CPUPlace())
        >>> executor.run(base.default_startup_program())

        >>> for _ in range(EPOCH_NUM):
        ...     for data in reader():
        ...         executor.run(feed=data, fetch_list=[loss])
N)r  r
  r  s      r&   decorate_sample_list_generator'PyReader.decorate_sample_list_generator  s    ~ 	..v>r(   c                 :    U R                   R                  X5        g)a	  
Set the data source of the PyReader object.

The provided :code:`reader` should be a Python generator,
which yields numpy.ndarray-typed or DenseTensor-typed batched data.

:code:`places` must be set when the PyReader object is iterable.

Args:
    reader (generator): Python generator that yields DenseTensor-typed
        batched data.
    places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
        be provided when PyReader is iterable.

Example:
    .. code-block:: python

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

        >>> paddle.enable_static()

        >>> EPOCH_NUM = 3
        >>> ITER_NUM = 15
        >>> BATCH_SIZE = 3

        >>> def network(image, label):
        ...     # User-defined network, here is an example of softmax regression.
        ...     predict = paddle.static.nn.fc(x=image, size=10, activation='softmax')
        ...     return paddle.nn.functional.cross_entropy(
        ...         input=predict, label=label,
        ...         reduction='none', use_softmax=False
        ...     )

        >>> def random_image_and_label_generator(height, width):
        ...     def generator():
        ...         for i in range(ITER_NUM):
        ...             batch_image = np.random.uniform(low=0,
        ...                                             high=255,
        ...                                             size=[BATCH_SIZE, height, width])
        ...             batch_label = np.ones([BATCH_SIZE, 1])
        ...             batch_image = batch_image.astype('float32')
        ...             batch_label = batch_label.astype('int64')
        ...             yield batch_image, batch_label
        ...     return generator

        >>> image = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32')
        >>> label = paddle.static.data(name='label', shape=[None, 1], dtype='int64')
        >>> reader = base.io.PyReader(feed_list=[image, label], capacity=4, iterable=True)

        >>> user_defined_generator = random_image_and_label_generator(784, 784)
        >>> reader.decorate_batch_generator(user_defined_generator, base.CPUPlace())

        >>> loss = network(image, label)
        >>> executor = base.Executor(base.CPUPlace())
        >>> executor.run(base.default_startup_program())

        >>> for _ in range(EPOCH_NUM):
        ...     for data in reader():
        ...         executor.run(feed=data, fetch_list=[loss])
N)r  r  r  s      r&   decorate_batch_generator!PyReader.decorate_batch_generator  s    ~ 	((8r(   )r  )NNTTFr  r-   )rk   rl   rm   rn   r  rQ   r  r   r{   rZ   r^   r   r   r  r  r  rp   rT   r(   r&   r  r  m  sv    qj 

 " " % %''$L$N DHH
T??B?9r(   r  c                   &    \ rS rSrS rS rS rSrg)r   iU  c                    [        U[        R                  R                  R                  R
                  5      (       d   S5       e[        5       (       a   S5       e[        U[        [        45      (       a  [        U5      nO[        U5      n[        U5      n[        UR                  5      U:  d    S[        UR                  5       SU 35       eUR                  S:w  a4  UR                  U:w  a$  [        R                  " SUR                   S35        UR!                  U5        [        U[        R                  R                  R                  R"                  5      (       aE  UR$                  U:  a5  [        R                  " SUR$                   S35        UR'                  U5        Xl        UR*                  R,                  R.                   Vs/ s H"  nUR0                  (       d  M  UR2                  PM$     nn[4        R6                  " UR                  U[9        U5      UR*                  R:                  U5      U l        g s  snf )	Nz#dataset must be type of DatasetBasez2DatasetLoader is not supported in dygraph mode yetzFilelist number of dataset z$ must be not less than place number r   zthread_num z# which is set in Dataset is ignoredz
queue_num )r"   r;   distributedfleetr   DatasetBaser   r.   r/   r   r   r    filelist
thread_numr   r  _set_threadInMemoryDataset	queue_num_set_queue_num_dataset
proto_descmulti_slot_descr  is_usedr*  r   IterableDatasetWrapperr7   r  _iterable_dataset)rP   r   r3   r~   r  slot	use_slotss          r&   rQ   DatasetLoader.__init__V  s   V''--55AA
 
 	10	1 
 #$$ 	
@	
$ ftUm,,+F3F&v.F[
7##$
2 	
)#g.>.>*?)@@deodpq	
2 "w'9'9Z'GOOg0011TU 	J' ++1199II  !!J.OOW..//RS "":.  **::@@
@|| DII@ 	 
 "&!<!<OOF#))"

s   I)Ic                     U R                   R                  5         U R                   R                  5         U R                  R	                  5         U $ r-   )r  _finish_to_run_prepare_to_runr  r   rO   s    r&   rZ   DatasetLoader.__iter__  s9    $$&%%'%%'r(   c                 6    U R                   R                  5       $ r-   )r  _nextrO   s    r&   r^   DatasetLoader.__next__  s    %%++--r(   )r  r  N)rk   rl   rm   rn   rQ   rZ   r^   rp   rT   r(   r&   r   r   U  s    1
f.r(   r   r   );r   r   r   r   r   r   numpyra   r;   paddle.base.frameworkr   paddle.pir.corer   paddle.utilsr    r   data_feederr   r	   executorr
   	frameworkr   r   r   r   r   r   r   r   r   	layers.ior   r   r   multiprocess_utilsr   r   r   r   r   unique_namer   r   __all__rC  r!   r*   r'   r+   r7   rH   rJ   rs   rv   rw   r  r   rT   r(   r&   <module>r     s      
     5 / #  : "
 
 
 
  -  
$7$9 !  )$" >B< 6 ,-F9 F9 .F9R
z^ zz	Dn DN
 d9~ d9 d9N;.N ;.r(   