reader.py 75.0 KB
Newer Older
S
sneaxiy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
from . import core
16
import sys
S
sneaxiy 已提交
17
import six
18
import numpy as np
S
sneaxiy 已提交
19
import threading
20
import paddle
21
from .framework import Program, Variable, program_guard, default_main_program, default_startup_program, in_dygraph_mode, cpu_places, _current_expected_place
S
sneaxiy 已提交
22
from .executor import global_scope
23
from .data_feeder import DataFeeder, BatchedTensorProvider
24
from .multiprocess_utils import multiprocess_queue_set, CleanupFuncRegistrar, _cleanup_mmap, _cleanup, _set_SIGCHLD_handler
25 26 27
from .dataloader import BatchSampler, Dataset, IterableDataset
from .dataloader.dataloader_iter import _DataLoaderIterSingleProcess, _DataLoaderIterMultiProcess, _DatasetKind, default_collate_fn
from .dataloader.batch_sampler import _InfiniteIterableSampler
S
sneaxiy 已提交
28
from .layers.io import monkey_patch_reader_methods, _copy_reader_var_, double_buffer
S
sneaxiy 已提交
29
from .unique_name import UniqueNameGenerator
30
from .framework import _get_paddle_place, _get_paddle_place_list
31
from paddle.fluid.framework import _set_expected_place, _current_expected_place
32
import logging
33
import warnings
S
sneaxiy 已提交
34

35
### Dygraph DataLoader configs ###
36
import os
37 38
import multiprocessing
import signal
39

40
# NOTE: queue has a different name in python2 and python3
T
tianshuo78520a 已提交
41
import queue
42

43 44 45
# NOTE: [ avoid hanging & failed quickly ] These value is used in getting data from another process
QUEUE_GET_TIMEOUT = 60

46
__all__ = ['PyReader', 'DataLoader', 'default_collate_fn']
Z
Zeng Jinle 已提交
47 48

data_loader_unique_name_generator = UniqueNameGenerator()
S
sneaxiy 已提交
49

50
KEEP_DATA_LOADER_ORDER = True
51
USE_PINNED_MEMORY = None
52 53 54 55 56 57 58 59 60 61


def keep_data_loader_order(*args):
    global KEEP_DATA_LOADER_ORDER
    if len(args) == 0:
        return KEEP_DATA_LOADER_ORDER
    else:
        assert len(args) == 1 and isinstance(args[0], bool)
        KEEP_DATA_LOADER_ORDER = args[0]

S
sneaxiy 已提交
62

63 64 65 66 67 68 69 70 71
def use_pinned_memory(*args):
    global USE_PINNED_MEMORY
    if len(args) == 0:
        return USE_PINNED_MEMORY
    else:
        assert len(args) == 1 and isinstance(args[0], bool)
        USE_PINNED_MEMORY = args[0]


S
sneaxiy 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
def _convert_places(places):
    if not isinstance(places, (list, tuple)):
        places = [places]

    ret = []
    for p in places:
        if not isinstance(p, core.Place):
            tmp = core.Place()
            tmp.set_place(p)
            p = tmp

        ret.append(p)
    return ret


87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
# NOTE(chenweihang): _reader_process_loop must be top level method to be pickled
def _reader_process_loop(batch_reader, data_queue):
    try:
        # set signal handler
        core._set_process_signal_handler()

        # NOTE: [ mmap files clear ] When the child process exits unexpectedly,
        # some shared memory objects may have been applied for but have not yet
        # been put into the inter-process Queue. This part of the object needs
        # to be cleaned up when the process ends.
        CleanupFuncRegistrar.register(_cleanup_mmap)

        for batch in batch_reader():
            tensor_list = core._convert_to_tensor_list(batch)
            data_queue.put(tensor_list)
            core._remove_tensor_list_mmap_fds(tensor_list)
        data_queue.put(None)
    except KeyboardInterrupt:
        # NOTE: Main process will raise KeyboardInterrupt anyways, ignore it in child process
        pass
    except:
        six.reraise(*sys.exc_info())


Z
Zeng Jinle 已提交
111 112 113
class DataLoaderBase(object):
    def __init__(self):
        self._places = None
S
sneaxiy 已提交
114

Z
Zeng Jinle 已提交
115 116
    def __call__(self):
        return self
S
sneaxiy 已提交
117

Z
Zeng Jinle 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    def next(self):
        '''
        Get the next item in the DataLoader object. This method    
        should not be called by users directly. It is used for
        implementing iterator protocol of Python 2.x inside
        PaddlePaddle framework.
        '''
        return self.__next__()

    def __iter__(self):
        raise NotImplementedError()

    def __next__(self):
        raise NotImplementedError()

133 134 135 136 137 138 139 140 141 142 143 144
    @classmethod
    def _check_input_array(cls, item):
        arr = np.asarray(item)
        if arr.dtype == np.object:
            raise TypeError(
                "\n\tFaild to convert input data to a regular ndarray :\n\t* Usually "
                "this means the input data contains nested lists with different lengths. "
                "\n\t* Check the reader function passed to 'decorate_batch_generator'"
                " to locate the data causes this issue.\n\t* Please consider using "
                "'fluid.create_lod_tensor' to convert it to a LoD-Tensor.")
        return arr

Z
Zeng Jinle 已提交
145 146

class DataLoader(object):
147 148 149 150 151 152 153 154
    """
    DataLoader prodives an iterator which iterates given dataset
    once by the batch_sampler.

    DataLoader supports single-process and multi-prcess data loading,
    multi-process workers will be used to load data asynchronously if
    :attr:`num_workers` is set as a positive number.

K
Kaipeng Deng 已提交
155
    DataLoader supports map-style dataset and iterable-style dataset.
156

K
Kaipeng Deng 已提交
157 158 159 160 161 162 163
    For map-style datast(can get a sample from dataset with a given
    index), please see :code:`paddle.io.Dataset`.

    For iterable-style datast(get samples from dataset iteratively,
    like a Python iterator), please see :code:`paddle.io.IterableDataset`.

    For :code:`batch_sampler` please see :code:`paddle.io.BatchSampler`
164

165 166 167 168 169 170
    .. note::
        GPU tensor operation is not supported in subprocess currently,
        please don't use GPU tensor operations in pipeline which will
        be performed in subprocess, such as dataset transforms, collte_fn,
        etc. Numpy array and CPU tensor operation is supported.

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    **Disable automatic batching**

    In certain cases such as some NLP tasks, instead of automatic batching,
    handling batching manually in dataset is needed by users. For these
    cases, automatic batching is disabled if both :attr:`batch_size` and
    :attr:`batch_sampler` is set as None, each data got from :attr:`dataset`
    should be batched data and will be processed with function define by
    :attr:`collate_fn` or :attr:`default_collate_fn`.


    .. note::
        When automatic batching is disabled, :attr:`default_collate_fn` will
        do nothing to data from dataset.


186 187
    Args:  
        dataset(Dataset): the dataset to load data from, should be an
188 189
            instance of subclass of :code:`paddle.io.Dataset` or
            :code:`paddle.io.IterableDataset`.
190 191
        feed_list (list(Tensor)|tuple(Tensor)): feed Tensor list.
            The Tensors should be created by :code:`paddle.static.data()`.
192 193
            :attr:`feed_list` must be set if :attr:`return_list` is
            False. Default None.
194
        places(list(Place)|tuple(Place)|list(str)|optional): a list of Place,
195 196
            to put data onto, :attr:`places` can be None, if 
            :attr:`places` is None, default place(CPUPlace or CUDAPlace(0))
197 198 199
            will be used. Default None. 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.
200 201
        return_list (bool): whether the return value on each device is 
            presented as a list. If :attr:`return_list=False`, the return
K
Kaipeng Deng 已提交
202
            value on each device would be a dict of str -> Tensor, where
203
            the key of the dict is the name of each fed Tensors. If 
204
            :attr:`return_list=True`, the return value on each device would
K
Kaipeng Deng 已提交
205
            be a list(Tensor). :attr:`return_list` can only be True
206
            in dynamic graph mode. Default True.
207 208 209
        batch_sampler(BatchSampler): an instance of `paddle.io.BatchSampler`
            to generate batch indices to draw samples from :attr:`dataset`
            and combine a batch. Default None.
210
        batch_size(int|None): sample number in a mini-batch, a substitution
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
            parameter for :attr:`batch_sampler`, if :attr:`batch_sampler`
            is not set, a default `paddle.io.BatchSampler` will be used
            and initialize by :attr:`batch_size`, :attr:`shuffle` and
            :attr:`drop_last`. Default 1.
        shuffle(bool): whther to shuffle indices order before genrate
            batch indices, a substitution parameter for :attr:`batch_sampler`
            see :attr:`batch_size`. Default False.
        drop_last(bool): whether drop the last incomplete batch dataset size
            is not divisible by the batch size, a substitution parameter
            for :attr:`batch_sampler`, see :attr:`batch_size`. Default False
        collate_fn(callable): function to generate mini-batch data by merging
            the sample list, None for only stack each fields of sample in axis
            0(same as :attr::`np.stack(..., axis=0)`). Default None
        num_workers(int): the number of subprocess to load data, 0 for no
            subprocess used and loading data in main process. Default 0
        use_buffer_reader (bool): whether to use bufferred reader. 
            If use_buffer_reader=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. Default True.
        use_shared_memory (bool): whether to use shared memory to speed up
            putting data into inter-process queue, set :attr:`use_shared_memory`
            as True only when the shared memory space on your machine(e.g.
            space of '/dev/shm' on Linux operating sysytem) is large enough.
            Shared memory will only be enabled in multi-process mode(num_workers
            > 0). Default True.
        timeout(int): the timeout value for getting data form output queue
            of subprocesses. Default 0.
        worker_init_fn(callable): init function which will be called with
            worker id on each subproces starting if not set as None. Default
            None.

    Returns:
244
        DataLoader: an iterable object for data iterating, each elemnet of the generated data is a Tensor.
245 246 247 248 249 250

    Examples:
        
        .. code-block:: python

            import numpy as np
251 252

            import paddle
K
Kaipeng Deng 已提交
253 254
            import paddle.nn as nn
            import paddle.nn.functional as F
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
            from paddle.io import Dataset, BatchSampler, DataLoader

            BATCH_NUM = 20
            BATCH_SIZE = 16
            EPOCH_NUM = 4

            IMAGE_SIZE = 784
            CLASS_NUM = 10

            # define a random dataset
            class RandomDataset(Dataset):
                def __init__(self, num_samples):
                    self.num_samples = num_samples

                def __getitem__(self, idx):
                    image = np.random.random([IMAGE_SIZE]).astype('float32')
                    label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64')
                    return image, label

                def __len__(self):
                    return self.num_samples

277 278
            dataset = RandomDataset(BATCH_NUM * BATCH_SIZE)

K
Kaipeng Deng 已提交
279
            class SimpleNet(nn.Layer):
280 281
                def __init__(self):
                    super(SimpleNet, self).__init__()
K
Kaipeng Deng 已提交
282
                    self.fc = nn.Linear(IMAGE_SIZE, CLASS_NUM)
283 284 285 286

                def forward(self, image, label=None):
                    return self.fc(image)

K
Kaipeng Deng 已提交
287 288 289
            simple_net = SimpleNet()
            opt = paddle.optimizer.SGD(learning_rate=1e-3,
                                      parameters=simple_net.parameters())
290 291

            loader = DataLoader(dataset,
K
Kaipeng Deng 已提交
292
                                batch_size=BATCH_SIZE,
293 294 295 296 297
                                shuffle=True,
                                drop_last=True,
                                num_workers=2)

            for e in range(EPOCH_NUM):
K
Kaipeng Deng 已提交
298 299 300 301 302 303 304 305
                for i, (image, label) in enumerate(loader()):
                    out = simple_net(image)
                    loss = F.cross_entropy(out, label)
                    avg_loss = paddle.mean(loss)
                    avg_loss.backward()
                    opt.minimize(avg_loss)
                    simple_net.clear_gradients()
                    print("Epoch {} batch {}: loss = {}".format(e, i, np.mean(loss.numpy())))
306 307


308 309 310 311
    .. note::
        For reading iterable dataset with multiprocess Dataloader,
        please see :code:`paddle.io.IterableDataset`

312 313 314 315 316 317
    """

    def __init__(self,
                 dataset,
                 feed_list=None,
                 places=None,
318
                 return_list=True,
319 320 321 322 323 324 325 326 327
                 batch_sampler=None,
                 batch_size=1,
                 shuffle=False,
                 drop_last=False,
                 collate_fn=None,
                 num_workers=0,
                 use_buffer_reader=True,
                 use_shared_memory=True,
                 timeout=0,
K
Kaipeng Deng 已提交
328 329
                 worker_init_fn=None,
                 persistent_workers=False):
330 331 332 333 334 335 336 337 338 339 340 341 342 343
        self.return_list = return_list
        self.collate_fn = collate_fn
        self.use_buffer_reader = use_buffer_reader
        self.worker_init_fn = worker_init_fn

        assert isinstance(dataset, Dataset), \
            "dataset should be subclass instance of paddle.io.Dataset"
        self.dataset = dataset

        if not return_list and not in_dygraph_mode():
            assert feed_list is not None, \
                    "feed_list should be set when return_list=False"
        self.feed_list = feed_list

344 345
        if places is None:
            places = _current_expected_place()
346 347 348 349
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
350 351 352 353 354
        self.places = _convert_places(places)

        assert num_workers >= 0, "num_workers should be a non-negative value"
        if num_workers > 0 and (sys.platform == 'darwin' or
                                sys.platform == 'win32'):
355 356 357
            warnings.warn(
                "DataLoader with multi-process mode is not supported on MacOs and Windows currently." \
                " Please use signle-process mode with num_workers = 0 instead")
358 359 360 361 362 363 364 365 366 367
            num_workers = 0
        self.num_workers = num_workers

        self.use_shared_memory = use_shared_memory
        if use_shared_memory and num_workers == 0:
            self.use_shared_memory = False

        assert timeout >= 0, "timeout should be a non-negative value"
        self.timeout = timeout

368 369 370 371 372 373 374 375 376 377 378 379
        if isinstance(dataset, IterableDataset):
            self.dataset_kind = _DatasetKind.ITER
            if shuffle:
                raise ValueError(
                    "IterableDataset not support shuffle, but got shuffle={}".
                    format(shuffle))
            if batch_sampler is not None:
                raise ValueError(
                    "IterableDataset expect unspecified batch_sampler")
        else:
            self.dataset_kind = _DatasetKind.MAP

380 381 382 383 384
        if batch_sampler is not None:
            assert batch_size == 1 and not shuffle and not drop_last, \
                "batch_size/shuffle/drop_last should not be set when " \
                "batch_sampler is given"
            self.batch_sampler = batch_sampler
385 386 387 388
            self.batch_size = None
        elif batch_size is None:
            self.batch_sampler = None
            self.batch_size = None
389
        else:
390 391
            assert batch_size > 0, \
                "batch_size should be None or a positive value when " \
392
                "batch_sampler is not given"
393
            self.batch_size = batch_size
394 395 396 397 398 399 400 401 402
            if isinstance(dataset, IterableDataset):
                self.batch_sampler = _InfiniteIterableSampler(dataset,
                                                              batch_size)
            else:
                self.batch_sampler = BatchSampler(
                    dataset=dataset,
                    batch_size=batch_size,
                    shuffle=shuffle,
                    drop_last=drop_last)
403

404 405
        self.auto_collate_batch = self.batch_sampler is not None

406 407 408 409 410
        self.pin_memory = False
        if in_dygraph_mode():
            self.pin_memory = True if use_pinned_memory(
            ) is None else use_pinned_memory()

K
Kaipeng Deng 已提交
411 412 413
        self._persistent_workers = persistent_workers
        self._iterator = None

414
    def __len__(self):
415 416 417
        if self.dataset_kind == _DatasetKind.ITER:
            raise ValueError("length of IterableDataset not supported")
        else:
418
            if self.auto_collate_batch:
419
                return len(self.batch_sampler)
420 421
            else:
                return len(self.dataset)
422 423 424 425

    def __iter__(self):
        if self.num_workers == 0:
            return _DataLoaderIterSingleProcess(self)
K
Kaipeng Deng 已提交
426 427 428 429 430 431
        elif self._persistent_workers:
            if self._iterator is None:
                self._iterator = _DataLoaderIterMultiProcess(self)
            else:
                self._iterator._reset()
            return self._iterator
432 433 434 435 436 437
        else:
            return _DataLoaderIterMultiProcess(self)

    def __call__(self):
        return self.__iter__()

Z
Zeng Jinle 已提交
438 439 440 441 442
    @staticmethod
    def from_generator(feed_list=None,
                       capacity=None,
                       use_double_buffer=True,
                       iterable=True,
443
                       return_list=False,
444 445
                       use_multiprocess=False,
                       drop_last=True):
Z
Zeng Jinle 已提交
446
        """
K
Kaipeng Deng 已提交
447 448 449 450
        .. warning::
          This API will be deprecated in the future, it is recommended to use
          :code:`paddle.io.DataLoader` which supports multi-processes acceleration.

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

Z
Zeng Jinle 已提交
454 455 456 457 458 459 460 461
        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.
462
        
Z
Zeng Jinle 已提交
463 464 465 466 467
        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
468
        process.
Z
Zeng Jinle 已提交
469 470

        Args:  
471 472
            feed_list (list(Tensor)|tuple(Tensor)): feed Tensor list.
                The Tensors should be created by :code:`fluid.data()`.
Z
Zeng Jinle 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485
            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): 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): whether the created DataLoader 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 -> LoDTensor, where the key of the dict is 
486
                the name of each fed Tensors. If return_list=True, the 
Z
Zeng Jinle 已提交
487 488
                return value on each device would be a list(LoDTensor). It is
                recommended to use return_list=False in static graph mode and
489 490 491 492 493 494
                use return_list=True in dygraph mode.  
            use_multiprocess (bool): 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.
495 496 497 498 499 500 501
            drop_last (bool): 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. 
Z
Zeng Jinle 已提交
502 503 504 505

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

506
        Examples 1:
Z
Zeng Jinle 已提交
507 508
            
            .. code-block:: python
S
sneaxiy 已提交
509

510 511 512
                '''
                Example in static graph mode
                '''
Z
Zeng Jinle 已提交
513
                import numpy as np
514

515 516 517 518 519
                import paddle
                import paddle.static as static
                import paddle.nn.functional as F


Z
Zeng Jinle 已提交
520 521 522 523 524 525 526 527 528 529 530
                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 

531 532
                paddle.enable_static()

Z
Zeng Jinle 已提交
533
                def simple_net(image, label):
534 535 536 537
                    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)
Z
Zeng Jinle 已提交
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
                    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
H
Huihuang Zheng 已提交
577

Z
Zeng Jinle 已提交
578
                    return __reader__
579

Z
Zeng Jinle 已提交
580 581 582 583 584
                # 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])
585

Z
Zeng Jinle 已提交
586 587 588 589 590 591 592
                # 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])
593
                        except paddle.core.EOFException:
Z
Zeng Jinle 已提交
594 595 596 597 598 599 600 601 602 603 604
                            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')
605

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

Z
Zeng Jinle 已提交
609
                # Define DataLoader 
610
                loader = paddle.io.DataLoader.from_generator(feed_list=[image, label], capacity=16, iterable=ITERABLE)
611

Z
Zeng Jinle 已提交
612 613
                # Define network
                loss = simple_net(image, label)
S
sneaxiy 已提交
614

Z
Zeng Jinle 已提交
615 616 617
                # Set data source of DataLoader
                #
                # If DataLoader is iterable, places must be given and the number of places must be the same with device number.  
618 619
                #  - If you are using GPU, call `paddle.static.cuda_places()` to get all GPU places. 
                #  - If you are using CPU, call `paddle.static.cpu_places()` to get all CPU places. 
Z
Zeng Jinle 已提交
620 621
                # 
                # If DataLoader is not iterable, places can be None.
622
                places = static.cuda_places() if USE_GPU else static.cpu_places()
Z
Zeng Jinle 已提交
623
                set_data_source(loader, places)
S
sneaxiy 已提交
624

625 626
                exe = static.Executor(places[0])
                exe.run(static.default_startup_program())
H
Huihuang Zheng 已提交
627

628
                prog = static.CompiledProgram(static.default_main_program()).with_data_parallel(loss_name=loss.name)
629

Z
Zeng Jinle 已提交
630 631 632 633 634 635
                if loader.iterable:
                    train_iterable(exe, prog, loss, loader)
                else:
                    train_non_iterable(exe, prog, loss, loader)


636 637 638 639
        Examples 2:

            .. code-block:: python

Z
Zeng Jinle 已提交
640
                '''
641
                Example in dynamic graph mode. 
Z
Zeng Jinle 已提交
642
                '''
643
                import numpy as np
644

645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
                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, label_shape):
                        image = np.random.random(size=image_shape).astype('float32')
                        label = np.random.random(size=label_shape).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], [BATCH_SIZE, CLASS_NUM])
                            yield batch_image, batch_label

                def random_batch_reader():
                    return __reader__

                class LinearNet(nn.Layer):
                    def __init__(self):
                        super(LinearNet, self).__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')

                # 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.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())))

        Examples 3:
708 709 710

            .. code-block:: python

711 712 713 714 715
                '''
                Example of `drop_last` using in static graph multi-cards mode
                '''
                import paddle
                import paddle.static as static
716 717 718 719 720 721
                import numpy as np
                import os

                # We use 2 CPU cores to run inference network 
                os.environ['CPU_NUM'] = '2'

722 723
                paddle.enable_static()

724 725 726 727 728 729
                # The data source has only 3 batches, which can not be
                # divided evenly to each CPU core
                def batch_generator():  
                    for i in range(3):
                        yield np.array([i+1]).astype('float32'), 

730
                x = static.data(name='x', shape=[None], dtype='float32')  
731 732 733
                y = x * x

                def run_inference(drop_last): 
734
                    loader = paddle.io.DataLoader.from_generator(feed_list=[x],
735
                            capacity=8, drop_last=drop_last)
736
                    loader.set_batch_generator(batch_generator, static.cpu_places())
737

738 739
                    exe = static.Executor(paddle.CPUPlace())
                    prog = static.CompiledProgram(static.default_main_program())
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
                    prog = prog.with_data_parallel()

                    result = []
                    for data in loader():
                        each_ret, = exe.run(prog, feed=data, fetch_list=[y])
                        result.extend(each_ret)
                    return result

                # Set drop_last to True, so that the last batch whose
                # number is less than CPU core number would be discarded.
                print(run_inference(drop_last=True)) # [1.0, 4.0]

                # Set drop_last to False, so that the last batch whose
                # number is less than CPU core number can be tested.
                print(run_inference(drop_last=False)) # [1.0, 4.0, 9.0]
Z
Zeng Jinle 已提交
755
        """
756 757 758 759 760 761
        if in_dygraph_mode():
            return DygraphGeneratorLoader(feed_list, capacity,
                                          use_double_buffer, iterable,
                                          return_list, use_multiprocess)
        else:
            return GeneratorLoader(feed_list, capacity, use_double_buffer,
762
                                   iterable, return_list, drop_last)
Z
Zeng Jinle 已提交
763 764 765 766

    @staticmethod
    def from_dataset(dataset, places, drop_last=True):
        """
K
Kaipeng Deng 已提交
767 768 769 770
        .. warning::
          This API will be deprecated in the future, it is recommended to use
          :code:`paddle.io.DataLoader` which supports multi-processes acceleration.

Z
Zeng Jinle 已提交
771 772
        Create an iterable DataLoader object for loading data from Dataset.    
        Dataset is only supported in Linux system currently.
773

Z
Zeng Jinle 已提交
774 775
        Args:
            dataset (InMemoryDataset|QueueDataset): the dataset object.
776 777 778
            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.   
Z
Zeng Jinle 已提交
779 780 781
            drop_last (bool): 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. 
782

Z
Zeng Jinle 已提交
783 784 785
        Returns:
            loader (DataLoader): the created DataLoader object, which can be 
                treated as a Python generator.   
786

Z
Zeng Jinle 已提交
787 788 789
        Examples:

            .. code-block:: python
790

791 792 793 794
                import paddle
                import paddle.static as static

                paddle.enable_static()
795

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

799 800 801 802 803
                dataset = paddle.distributed.QueueDataset()
                dataset.init(
                    batch_size=32,
                    pipe_command='cat',
                    use_var=[image, label])
Z
Zeng Jinle 已提交
804
                dataset.set_filelist(['a.txt', 'b.txt', 'c.txt'])
805

806
                loader = paddle.io.DataLoader.from_dataset(dataset, static.cpu_places())
Z
Zeng Jinle 已提交
807 808
        """
        return DatasetLoader(dataset, places, drop_last)
S
sneaxiy 已提交
809

S
sneaxiy 已提交
810

811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
class DygraphGeneratorLoader(DataLoaderBase):
    """
    The GeneratorLoader of dygraph

    The multiprocess dygraph GeneratorLoader's most functions are different from 
    static graph GeneratorLoader, Separate implementation to keep code readable.
    """

    def __init__(self,
                 feed_list=None,
                 capacity=None,
                 use_double_buffer=True,
                 iterable=True,
                 return_list=True,
                 use_multiprocess=False):
        self._batch_reader = None
        self._places = None
        self._feed_list = feed_list

        if not capacity:
            raise ValueError("Please give value to capacity.")
        self._capacity = capacity
        self._use_double_buffer = use_double_buffer

        if not iterable:
836 837
            warnings.warn(
                "Please NOTE: DygraphGeneratorLoader supports iterable mode only. Change to iterable mode."
838 839 840
            )
        self._iterable = True
        if not return_list:
841 842
            warnings.warn(
                "Please NOTE: DygraphGeneratorLoader supports returning as list only. Change to return as list."
843 844 845 846 847 848 849
            )
        self._return_list = True

        # NOTE: the multiprocessing in different platform is incompatible, we will solve it later
        self._use_multiprocess = use_multiprocess
        if self._use_multiprocess and (sys.platform == 'darwin' or
                                       sys.platform == 'win32'):
850 851
            warnings.warn(
                "NOTE: DygraphGeneratorLoader with multiprocess mode is not currently supported on MacOs and Windows."
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
            )
            self._use_multiprocess = False

        if self._use_multiprocess:
            # NOTE: the multiprocessing.Queue used to save loading data in self._process
            self._data_queue = None
            # NOTE: this process is used to load data asynchronously from self._batch_reader
            self._process = None

        # NOTE: the C++ LoDTensorBlockingQueue instance
        self._blocking_queue = None
        # NOTE: 1. In multiprocess mode, this thread is used to get next batch data from
        # self._data_queue, then push it into self._blocking_queue; 2. In singleprocess
        # mode, this thread is used to get next batch data from self._batch_reader, then 
        # push it into self._blocking_queue
        self._thread = None
868 869
        self._pin_memory = True if use_pinned_memory(
        ) is None else use_pinned_memory()
870 871 872 873 874 875 876 877 878

    @property
    def queue(self):
        return self._blocking_queue

    @property
    def iterable(self):
        return self._iterable

879 880 881 882 883 884 885 886 887 888
    def _clear_and_remove_data_queue(self):
        if self._data_queue is not None:
            while True:
                try:
                    self._data_queue.get_nowait()
                except queue.Empty:
                    break
            global multiprocess_queue_set
            multiprocess_queue_set.remove(self._data_queue)

889 890 891 892 893 894 895 896 897 898 899
    def _wait_thread_ends(self):
        thread = self._thread
        if thread is not None:
            self._blocking_queue.close()
            thread.join()

    def _wait_process_ends(self):
        process = self._process
        if process is not None:
            process.join()
            # erase process id
900
            core._erase_process_pids(id(self))
901

902 903 904 905 906 907 908 909 910
    def _init_iterable(self):
        self._wait_thread_ends()
        if self._use_multiprocess:
            self._wait_process_ends()
        self._var_names = []
        self._shapes = []
        self._dtypes = []
        self._need_check_feed = []
        self._blocking_queue = core.init_lod_tensor_blocking_queue(
911
            core.Variable(), self._capacity, False)
912
        self._reader = None
913 914
        self._reader = core.create_py_reader(
            self.queue, self._var_names, self._shapes, self._dtypes,
915 916
            self._need_check_feed, self._places, self._use_double_buffer, True,
            self._pin_memory)
917 918 919

    def _start(self):
        if self._use_multiprocess:
920 921 922
            # clear old _data_queue and remove it from multiprocess_queue_set
            self._clear_and_remove_data_queue()
            # set data_queue and process
923
            self._data_queue = multiprocessing.Queue(self._capacity)
924 925 926
            # add _data_queue into global queue set
            global multiprocess_queue_set
            multiprocess_queue_set.add(self._data_queue)
927
            self._process = multiprocessing.Process(
928 929
                target=_reader_process_loop,
                args=(self._batch_reader, self._data_queue))
930 931 932 933 934 935 936 937 938
            self._process.daemon = True
            self._process.start()

            # Set child process signal handler
            # NOTE: [ avoiding hang ] 1. if the child process dies due to bus error/segfault
            # or just hang, the main process will hang waiting for data, so here need to deal 
            # with SIGSEGV and SIGBUS of child process; 2. if the main process end before child
            # process, it shuts the all its daemonic children down with a SIGTERM (instead of 
            # joining them without a timeout), so here nedd to deal with SIGTERM.
939 940
            core._set_process_pids(id(self), [self._process.pid])
            _set_SIGCHLD_handler()
941 942 943 944

            # Set reader_thread
            self._thread_done_event = threading.Event()
            self._thread = threading.Thread(
945 946
                target=self._reader_thread_loop_for_multiprocess,
                args=(_current_expected_place(), ))
947 948 949
            self._thread.daemon = True
            self._thread.start()
        else:
950
            self._thread = threading.Thread(
951 952
                target=self._reader_thread_loop_for_singleprocess,
                args=(_current_expected_place(), ))
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
            self._thread.daemon = True
            self._thread.start()

    def _reset(self):
        self._reader.reset()
        self._wait_thread_ends()
        if self._use_multiprocess:
            self._wait_process_ends()

    def __iter__(self):
        assert self.iterable, "DataLoader is not iterable"
        assert self._batch_reader is not None, \
            "Data source of DataLoader has not set yet"

        self._init_iterable()
        self._start()
        return self

    def __next__(self):
        try:
            return self._reader.read_next_var_list()
        except StopIteration:
            self._reset()
            six.reraise(*sys.exc_info())

978 979 980 981 982 983 984 985 986
    def _exit_thread_expectedly(self):
        self._thread_done_event.set()
        self._blocking_queue.close()

    def _exit_thread_unexpectedly(self):
        self._thread_done_event.set()
        self._blocking_queue.kill()
        logging.error("DataLoader reader thread raised an exception!")

987 988 989 990
    def _reader_thread_loop_for_multiprocess(self, legacy_expected_place):
        # See _DataLoaderIterSingleProcess._thread_loop() for why set expected place here.
        _set_expected_place(legacy_expected_place)

991 992 993 994 995 996 997
        while not self._thread_done_event.is_set():
            try:
                # NOTE: [ avoid hanging ] Even with carefully designed data dependencies 
                # (i.e., a put() always corresponding to a get()), hanging on get() can 
                # still happen when data in queue is corrupted (e.g., due to 
                # Queue.cancel_join_thread or unexpected exit). So we set a timeout whenever 
                # we try to get data from `data_queue`
998 999 1000 1001 1002 1003 1004
                # NOTE: [ avoid failed quickly ] Here, the time setting of QUEUE_GET_TIMEOUT
                # is relatively long, currently it is 60 seconds, because in some models,
                # if the reader child process starts with a heavy burden, the child process
                # has no enough time to put the data in the queue when the main process
                # start trying to get data from queue. At this time, the child thread needs
                # to wait slightly longer
                tensor_list = self._data_queue.get(timeout=QUEUE_GET_TIMEOUT)
1005 1006 1007 1008
            except:
                # NOTE [ avoid handing ] After adding the shared memory mechanism, not only
                # the queue.Empty exception will occur here, but other exceptions will also
                # occur, such as mmap failure. If it is not handled here, it will hang.
1009
                self._exit_thread_unexpectedly()
1010 1011
                logging.error(
                    "DataLoader reader thread failed to read data from the multiprocessing.Queue."
1012
                )
1013
                six.reraise(*sys.exc_info())
1014 1015

            if not self._thread_done_event.is_set():
1016
                if tensor_list is not None:
1017 1018
                    try:
                        array = core.LoDTensorArray()
1019 1020
                        for tensor in tensor_list:
                            array.append(tensor)
1021 1022 1023
                        if not self._blocking_queue.push(array):
                            self._blocking_queue.close()
                    except:
1024
                        self._exit_thread_unexpectedly()
1025 1026
                        six.reraise(*sys.exc_info())
                else:
1027
                    self._exit_thread_expectedly()
1028

1029
    def _reader_thread_loop_for_singleprocess(self, legacy_expected_place):
1030
        try:
1031 1032 1033
            # See _DataLoaderIterSingleProcess._thread_loop() for why set expected place here.
            _set_expected_place(legacy_expected_place)

1034 1035 1036 1037
            for sample in self._batch_reader():
                array = core.LoDTensorArray()
                for item in sample:
                    if not isinstance(item, core.LoDTensor):
1038
                        item = self._check_input_array(item)
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
                        tmp = core.LoDTensor()
                        tmp.set(item, core.CPUPlace())
                        item = tmp

                    array.append(item)

                if not self._blocking_queue.push(array):
                    break

            self._blocking_queue.close()
            self._thread = None
        except Exception:
            self._blocking_queue.kill()
            self._thread = None
            logging.warning(
                "DygraphDataLoader reader thread raised an exception.")
            six.reraise(*sys.exc_info())

    def set_sample_generator(self,
                             reader,
                             batch_size,
                             drop_last=True,
                             places=None):
        assert batch_size > 0, "batch_size must be larger than 0"
1063 1064 1065 1066
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
1067 1068 1069 1070 1071 1072 1073
        self.set_sample_list_generator(
            paddle.batch(
                reader, batch_size=batch_size, drop_last=drop_last),
            places=places)
        return self

    def set_sample_list_generator(self, reader, places=None):
1074 1075 1076 1077 1078
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)

1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        def __batch_reader_impl__():
            for batch in reader():
                slots = []
                for items in batch:
                    for i, item in enumerate(items):
                        if len(slots) < len(items):
                            slots.append([item])
                        else:
                            slots[i].append(item)
                yield slots

        self.set_batch_generator(__batch_reader_impl__, places)
        return self

    def set_batch_generator(self, reader, places=None):
1094 1095 1096 1097
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
1098
        self._batch_reader = reader
1099 1100
        if places is None:
            places = _current_expected_place()
1101 1102
        self._places = _convert_places(places)
        assert len(self._places) == 1, \
1103
            "Number of places must be 1 in imperative mode"
1104 1105 1106
        return self


Z
Zeng Jinle 已提交
1107
class GeneratorLoader(DataLoaderBase):
S
sneaxiy 已提交
1108
    def __init__(self,
1109 1110
                 feed_list=None,
                 capacity=None,
S
sneaxiy 已提交
1111
                 use_double_buffer=True,
1112
                 iterable=True,
1113 1114
                 return_list=False,
                 drop_last=True):
S
sneaxiy 已提交
1115
        self._tensor_reader = None
Z
Zeng Jinle 已提交
1116
        self._places = None
S
sneaxiy 已提交
1117
        self._thread = None
1118
        self._queue = None
1119
        self._feed_list = feed_list
1120 1121 1122
        self._exited = False
        self._drop_last = drop_last
        self._keep_order = keep_data_loader_order()
1123 1124
        if not capacity:
            raise ValueError("Please give value to capacity.")
1125 1126 1127 1128
        self._iterable = iterable
        self._return_list = return_list
        if not self._feed_list:
            raise Exception("Feed list must be given under static mode.")
S
sneaxiy 已提交
1129 1130 1131 1132
        self._use_double_buffer = use_double_buffer
        self._capacity = capacity
        if not self._iterable:
            self._init_non_iterable()
S
sneaxiy 已提交
1133

Z
Zeng Jinle 已提交
1134
    def _wait_thread_ends(self):
1135
        # Get self._thread first to prevent data race, because __thread_main__
Z
Zeng Jinle 已提交
1136 1137 1138 1139 1140 1141 1142 1143
        # would set self._thread be None at the end
        thread = self._thread
        if thread is not None and self._iterable:
            self._queue.close()
            thread.join()

    def _init_iterable(self):
        self._wait_thread_ends()
1144 1145 1146 1147 1148 1149
        self._var_names = [v.name for v in self._feed_list]
        self._shapes = [v.shape for v in self._feed_list]
        self._dtypes = [v.dtype for v in self._feed_list]
        self._need_check_feed = [
            v.desc.need_check_feed() for v in self._feed_list
        ]
1150 1151
        self._queue = core.init_lod_tensor_blocking_queue(
            core.Variable(), self._capacity, self._keep_order)
1152
        self._reader = None
S
sneaxiy 已提交
1153
        self._reader = core.create_py_reader(
1154
            self.queue, self._var_names, self._shapes, self._dtypes,
1155
            self._need_check_feed, self._places, self._use_double_buffer,
1156
            self._drop_last, False)
S
sneaxiy 已提交
1157 1158 1159 1160 1161 1162 1163

    def _init_non_iterable(self):
        lod_levels = []
        dtypes = []
        shape_concat = []
        ranks = []
        shapes = []
1164
        need_check_feed = []
S
sneaxiy 已提交
1165 1166 1167 1168 1169 1170 1171

        for feed_data in self._feed_list:
            dtypes.append(feed_data.dtype)
            shape_concat.extend(feed_data.shape)
            ranks.append(len(feed_data.shape))
            shapes.append(feed_data.shape)
            lod_levels.append(feed_data.lod_level)
1172
            need_check_feed.append(int(feed_data.desc.need_check_feed()))
S
sneaxiy 已提交
1173

Z
Zeng Jinle 已提交
1174 1175 1176 1177
        queue_name = data_loader_unique_name_generator(
            'lod_tensor_blocking_queue')
        reader_name = data_loader_unique_name_generator('create_py_reader')
        double_buffer_name = data_loader_unique_name_generator('double_buffer')
S
sneaxiy 已提交
1178

S
sneaxiy 已提交
1179
        var = global_scope().var(queue_name)
1180 1181 1182 1183 1184 1185 1186
        self._queue = core.init_lod_tensor_blocking_queue(var, self._capacity,
                                                          self._keep_order)

        if self._keep_order:
            block = default_main_program().current_block()
        else:
            block = default_startup_program().current_block()
S
sneaxiy 已提交
1187

1188
        reader_var = block.create_var(name=reader_name)
S
sneaxiy 已提交
1189

1190
        dtype_int = [int(t) for t in dtypes]
1191
        block.append_op(
S
sneaxiy 已提交
1192 1193
            type='create_py_reader',
            inputs={'blocking_queue': [queue_name]},
1194
            outputs={'Out': [reader_var]},
S
sneaxiy 已提交
1195 1196 1197
            attrs={
                'shape_concat': shape_concat,
                'lod_levels': lod_levels,
1198 1199
                'dtypes': dtype_int,
                'need_check_feed': need_check_feed,
S
sneaxiy 已提交
1200 1201 1202
                'ranks': ranks
            })

1203 1204 1205
        reader_var.desc.set_dtypes(dtypes)
        reader_var.persistable = True
        reader_var.stop_gradient = True
S
sneaxiy 已提交
1206

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
        if self._keep_order:
            main_prog_var = reader_var
            reader = main_prog_var
            reader.reset = self._queue.reset
        else:
            main_prog_var = _copy_reader_var_(
                default_main_program().current_block(), reader_var)

            main_prog_var.stop_gradient = True
            main_prog_var.persistable = True
S
sneaxiy 已提交
1217

1218
            reader = monkey_patch_reader_methods(main_prog_var)
S
sneaxiy 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232

        if self._use_double_buffer:
            double_buffer_reader = double_buffer(
                reader, name=double_buffer_name)
            # we return a double buffer reader. However, the reset method comes from
            # py_reader.
            double_buffer_reader.reset = reader.reset
            reader = double_buffer_reader

        self._reader = reader

        default_main_program().current_block().append_op(
            type='read',
            inputs={'Reader': [self._reader]},
1233 1234
            outputs={'Out': self._feed_list},
            attrs={'drop_last': self._drop_last})
S
sneaxiy 已提交
1235 1236 1237 1238 1239 1240 1241 1242

    @property
    def queue(self):
        return self._queue

    @property
    def iterable(self):
        return self._iterable
S
sneaxiy 已提交
1243

Z
Zeng Jinle 已提交
1244 1245
    def __iter__(self):
        assert self.iterable, "DataLoader is not iterable"
S
sneaxiy 已提交
1246
        assert self._tensor_reader is not None, \
Z
Zeng Jinle 已提交
1247
            "Data source of DataLoader has not set yet"
S
sneaxiy 已提交
1248

Z
Zeng Jinle 已提交
1249
        self._init_iterable()
S
sneaxiy 已提交
1250
        self._start()
Z
Zeng Jinle 已提交
1251 1252 1253 1254
        return self

    def __next__(self):
        try:
1255 1256
            if self._return_list:
                return self._reader.read_next_list()
1257
            else:
1258
                return self._reader.read_next()
Z
Zeng Jinle 已提交
1259 1260 1261 1262 1263 1264
        except StopIteration:
            self._queue.close()
            self._reset()
            six.reraise(*sys.exc_info())

    def start(self):
1265 1266
        assert not self._iterable, "start() cannot be called when DataLoader is iterable"
        self._start()
Z
Zeng Jinle 已提交
1267 1268

    def reset(self):
1269 1270
        assert not self._iterable, "reset() cannot be called when DataLoader is iterable"
        self._reset()
Z
Zeng Jinle 已提交
1271 1272

    def _start(self):
1273
        def __thread_main__(legacy_expected_place):
Z
Zeng Jinle 已提交
1274
            try:
1275 1276 1277
                # See _DataLoaderIterSingleProcess._thread_loop() for why set expected place here.
                _set_expected_place(legacy_expected_place)

1278 1279 1280 1281
                while not self._queue.wait_for_inited(1):
                    if self._exited:
                        return

Z
Zeng Jinle 已提交
1282 1283 1284 1285
                for tensors in self._tensor_reader():
                    array = core.LoDTensorArray()
                    for item in tensors:
                        if not isinstance(item, core.LoDTensor):
1286
                            item = self._check_input_array(item)
Z
Zeng Jinle 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
                            tmp = core.LoDTensor()
                            tmp.set(item, core.CPUPlace())
                            item = tmp

                        array.append(item)

                    if not self._queue.push(array):
                        break

                self._queue.close()
                self._thread = None
            except Exception as ex:
Z
Zeng Jinle 已提交
1299
                self._queue.kill()
Z
Zeng Jinle 已提交
1300
                self._thread = None
1301
                logging.warning('Your reader has raised an exception!')
Z
Zeng Jinle 已提交
1302 1303
                six.reraise(*sys.exc_info())

1304 1305
        self._thread = threading.Thread(
            target=__thread_main__, args=(_current_expected_place(), ))
Z
Zeng Jinle 已提交
1306 1307
        self._thread.daemon = True
        self._thread.start()
S
sneaxiy 已提交
1308

S
sneaxiy 已提交
1309
    def _reset(self):
1310
        self._queue.close()
1311
        self._exited = True
Z
Zeng Jinle 已提交
1312 1313 1314 1315
        thread = self._thread
        if thread is not None:
            thread.join()

1316
        self._exited = False
1317 1318
        self._reader.reset()

Z
Zeng Jinle 已提交
1319 1320 1321 1322 1323 1324
    def set_sample_generator(self,
                             reader,
                             batch_size,
                             drop_last=True,
                             places=None):
        assert batch_size > 0, "batch_size must be larger than 0"
1325 1326 1327 1328
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
1329 1330 1331 1332 1333 1334 1335
        has_lod = False
        for f in self._feed_list:
            if f.lod_level != 0:
                has_lod = True
                break

        if has_lod:
1336 1337 1338 1339 1340
            self.set_sample_list_generator(
                paddle.batch(
                    reader, batch_size=batch_size, drop_last=drop_last),
                places=places)
        else:
1341 1342 1343 1344 1345 1346 1347
            reader = BatchedTensorProvider(
                feed_list=self._feed_list,
                place=core.CPUPlace(),
                batch_size=batch_size,
                generator=reader,
                drop_last=drop_last)
            self.set_batch_generator(reader, places=places)
Z
Zeng Jinle 已提交
1348 1349 1350
        return self

    def set_sample_list_generator(self, reader, places=None):
1351 1352 1353 1354
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
1355 1356 1357 1358
        with program_guard(Program(), Program()):
            feeder = DataFeeder(
                feed_list=self._feed_list, place=core.CPUPlace())
            paddle_reader = feeder.decorate_reader(reader, multi_devices=False)
Z
Zeng Jinle 已提交
1359

1360 1361 1362
        def __tensor_reader_impl__():
            for slots in paddle_reader():
                yield [slots[var.name] for var in self._feed_list]
Z
Zeng Jinle 已提交
1363 1364 1365 1366 1367

        self.set_batch_generator(__tensor_reader_impl__, places)
        return self

    def set_batch_generator(self, reader, places=None):
1368 1369 1370 1371
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
Z
Zeng Jinle 已提交
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
        self._tensor_reader = reader
        if self._iterable:
            assert places is not None, "Places cannot be None when DataLoader is iterable"
            self._places = _convert_places(places)
        else:
            if places is not None:
                logging.info(
                    'places would be ommited when DataLoader is not iterable')
        return self


class PyReader(DataLoaderBase):
1384
    r"""
Z
Zeng Jinle 已提交
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
    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:`fluid.layers.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 -> LoDTensor, where the key of the dict is 
T
tianshuo78520a 已提交
1406
            the name of each fed variables. If return_list=True, the 
Z
Zeng Jinle 已提交
1407 1408 1409 1410 1411
            return value on each device would be a list(LoDTensor). It is
            recommended to use return_list=False in static graph mode and
            use return_list=True in dygraph mode. 

    Returns:
G
guofei 已提交
1412 1413 1414 1415
        the created reader object.

    Return type:
        reader(Reader)
Z
Zeng Jinle 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434

    Examples:
        1. If iterable = False, the created PyReader object is almost the
           same as :code:`fluid.layers.py_reader()`. Operators would be 
           inserted into the program. User should call :code:`start()` 
           before each epoch and catch :code:`fluid.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

           import paddle
           import paddle.fluid as fluid
           import numpy as np

           EPOCH_NUM = 3
           ITER_NUM = 5
           BATCH_SIZE = 3
G
guofei 已提交
1435 1436 1437 1438 1439
           
           def network(image, label):
               # User-defined network, here is an example of softmax regression.
               predict = fluid.layers.fc(input=image, size=10, act='softmax')           
               return fluid.layers.cross_entropy(input=predict, label=label)
Z
Zeng Jinle 已提交
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450

           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

G
guofei 已提交
1451 1452
           image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
           label = fluid.data(name='label', shape=[None, 1], dtype='int64')
Z
Zeng Jinle 已提交
1453 1454 1455 1456 1457 1458 1459 1460

           reader = fluid.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))
G
guofei 已提交
1461 1462
           loss = network(image, label)
           executor = fluid.Executor(fluid.CPUPlace())
Z
Zeng Jinle 已提交
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
           executor.run(fluid.default_startup_program())
           for i in range(EPOCH_NUM):
               reader.start()
               while True:
                   try:
                       executor.run(feed=None)
                   except fluid.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

           import paddle
           import paddle.fluid as fluid
           import numpy as np

           EPOCH_NUM = 3
           ITER_NUM = 5
           BATCH_SIZE = 10

G
guofei 已提交
1490 1491 1492 1493 1494
           def network(image, label):
               # User-defined network, here is an example of softmax regression.
               predict = fluid.layers.fc(input=image, size=10, act='softmax')           
               return fluid.layers.cross_entropy(input=predict, label=label)

Z
Zeng Jinle 已提交
1495 1496 1497
           def reader_creator_random_image(height, width):
               def reader():
                   for i in range(ITER_NUM):
G
guofei 已提交
1498 1499 1500
                       fake_image = np.random.uniform(low=0, high=255, size=[height, width])
                       fake_label = np.ones([1])
                       yield fake_image, fake_label 
Z
Zeng Jinle 已提交
1501 1502
               return reader

G
guofei 已提交
1503 1504 1505
           image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
           label = fluid.data(name='label', shape=[None, 1], dtype='int64')
           reader = fluid.io.PyReader(feed_list=[image, label], capacity=4, iterable=True, return_list=False)
Z
Zeng Jinle 已提交
1506 1507 1508 1509

           user_defined_reader = reader_creator_random_image(784, 784)
           reader.decorate_sample_list_generator(
               paddle.batch(user_defined_reader, batch_size=BATCH_SIZE),
G
guofei 已提交
1510 1511 1512 1513 1514 1515
                   fluid.core.CPUPlace())
           
           loss = network(image, label)
           executor = fluid.Executor(fluid.CPUPlace())
           executor.run(fluid.default_startup_program())
           
Z
Zeng Jinle 已提交
1516 1517
           for _ in range(EPOCH_NUM):
               for data in reader():
G
guofei 已提交
1518
                   executor.run(feed=data, fetch_list=[loss])
Z
Zeng Jinle 已提交
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572


        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

           import paddle
           import paddle.fluid as fluid
           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 = fluid.CPUPlace()
           with fluid.dygraph.guard(place):
               py_reader = fluid.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 = fluid.layers.relu(image)
    """

    def __init__(self,
                 feed_list=None,
                 capacity=None,
                 use_double_buffer=True,
                 iterable=True,
                 return_list=False):
        self._loader = DataLoader.from_generator(
            feed_list, capacity, use_double_buffer, iterable, return_list)

    @property
    def queue(self):
        return self._loader.queue

    @property
    def iterable(self):
        return self._loader.iterable

    def __iter__(self):
        return self._loader.__iter__()

    def __next__(self):
        return self._loader.__next__()
S
sneaxiy 已提交
1573 1574

    def start(self):
S
add doc  
sneaxiy 已提交
1575 1576 1577
        '''
        Start the data feeding thread. 
        Can only call when the reader object is not iterable.  
1578
        
G
guofei 已提交
1579 1580
	Example:
	    .. code-block:: python
Z
Zeng Jinle 已提交
1581
    
H
Huihuang Zheng 已提交
1582 1583 1584 1585
                import paddle
                import paddle.fluid as fluid
                import numpy as np

1586 1587 1588 1589 1590 1591
                BATCH_SIZE = 10

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

G
guofei 已提交
1592
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
1593 1594 1595 1596
                reader = fluid.io.PyReader(feed_list=[image], capacity=4, iterable=False)
                reader.decorate_sample_list_generator(
                    paddle.batch(generator, batch_size=BATCH_SIZE))

G
guofei 已提交
1597
                executor = fluid.Executor(fluid.CPUPlace())
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
                executor.run(fluid.default_startup_program())
                for i in range(3):
                    reader.start()
                    while True:
                        try:
                            executor.run(feed=None)
                        except fluid.core.EOFException:
                            reader.reset()
                            break

Z
Zeng Jinle 已提交
1608 1609
	    '''
        self._loader.start()
S
sneaxiy 已提交
1610

S
sneaxiy 已提交
1611
    def reset(self):
S
add doc  
sneaxiy 已提交
1612 1613 1614
        '''
        Reset the reader object when :code:`fluid.core.EOFException` raises. 
        Can only call when the reader object is not iterable.
1615 1616 1617 1618
        
        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
1619 1620 1621 1622
                import paddle
                import paddle.fluid as fluid
                import numpy as np

1623 1624 1625 1626 1627 1628
                BATCH_SIZE = 10

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

G
guofei 已提交
1629
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
1630 1631 1632 1633
                reader = fluid.io.PyReader(feed_list=[image], capacity=4, iterable=False)
                reader.decorate_sample_list_generator(
                    paddle.batch(generator, batch_size=BATCH_SIZE))

G
guofei 已提交
1634
                executor = fluid.Executor(fluid.CPUPlace())
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
                executor.run(fluid.default_startup_program())
                for i in range(3):
                    reader.start()
                    while True:
                        try:
                            executor.run(feed=None)
                        except fluid.core.EOFException:
                            reader.reset()
                            break        

S
add doc  
sneaxiy 已提交
1645
        '''
Z
Zeng Jinle 已提交
1646
        self._loader.reset()
S
sneaxiy 已提交
1647

S
sneaxiy 已提交
1648 1649 1650 1651 1652 1653 1654 1655 1656
    def decorate_sample_generator(self,
                                  sample_generator,
                                  batch_size,
                                  drop_last=True,
                                  places=None):
        '''
        Set the data source of the PyReader object.
        
        The provided :code:`sample_generator` should be a Python generator,
1657
        which yields list(numpy.ndarray)-typed data of each sample.
S
sneaxiy 已提交
1658 1659 1660 1661

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

        If all inputs have no lods, this method is faster than 
S
sneaxiy 已提交
1662
        :code:`decorate_sample_list_generator(paddle.batch(sample_generator, ...))` .
S
sneaxiy 已提交
1663 1664 1665

        Args:
            sample_generator (generator): Python generator that yields
1666
                list(numpy.ndarray)-typed sample data.
S
sneaxiy 已提交
1667 1668 1669 1670 1671
            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.
1672 1673 1674 1675

        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
1676 1677 1678
                import paddle.fluid as fluid
                import numpy as np

1679 1680 1681
                EPOCH_NUM = 3
                ITER_NUM = 15
                BATCH_SIZE = 3
G
guofei 已提交
1682 1683 1684 1685 1686
        
                def network(image, label):
                    # User-defined network, here is an example of softmax regression.
                    predict = fluid.layers.fc(input=image, size=10, act='softmax')           
                    return fluid.layers.cross_entropy(input=predict, label=label)
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697

                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

G
guofei 已提交
1698 1699
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
                label = fluid.data(name='label', shape=[None, 1], dtype='int64')
1700 1701 1702 1703 1704
                reader = fluid.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,
G
guofei 已提交
1705 1706 1707 1708
                                                 places=[fluid.CPUPlace()])
                loss = network(image, label)
                executor = fluid.Executor(fluid.CPUPlace())
                executor.run(fluid.default_startup_program())
1709 1710 1711

                for _ in range(EPOCH_NUM):
                    for data in reader():
G
guofei 已提交
1712
                        executor.run(feed=data, fetch_list=[loss])
1713
    
S
sneaxiy 已提交
1714
        '''
Z
Zeng Jinle 已提交
1715 1716
        self._loader.set_sample_generator(sample_generator, batch_size,
                                          drop_last, places)
S
sneaxiy 已提交
1717

S
sneaxiy 已提交
1718
    def decorate_sample_list_generator(self, reader, places=None):
S
add doc  
sneaxiy 已提交
1719 1720 1721 1722
        '''
        Set the data source of the PyReader object. 

        The provided :code:`reader` should be a Python generator,
S
sneaxiy 已提交
1723
        which yields list(numpy.ndarray) typed batched data. 
S
add doc  
sneaxiy 已提交
1724 1725 1726 1727
        
        :code:`places` must be set when the PyReader object is iterable.

        Args:
S
sneaxiy 已提交
1728 1729 1730 1731
            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.
1732 1733 1734 1735
        
        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
1736 1737 1738 1739
                import paddle
                import paddle.fluid as fluid
                import numpy as np

1740 1741 1742 1743
                EPOCH_NUM = 3
                ITER_NUM = 15
                BATCH_SIZE = 3

G
guofei 已提交
1744 1745 1746 1747 1748
                def network(image, label):
                    # User-defined network, here is an example of softmax regression.
                    predict = fluid.layers.fc(input=image, size=10, act='softmax')           
                    return fluid.layers.cross_entropy(input=predict, label=label)

1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
                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

G
guofei 已提交
1759 1760
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
                label = fluid.data(name='label', shape=[None, 1], dtype='int64')
1761 1762 1763 1764 1765
                reader = fluid.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),
G
guofei 已提交
1766 1767 1768 1769 1770
                    fluid.core.CPUPlace())
                
                loss = network(image, label)
                executor = fluid.Executor(fluid.core.CPUPlace())
                executor.run(fluid.default_startup_program())
1771 1772 1773

                for _ in range(EPOCH_NUM):
                    for data in reader():
G
guofei 已提交
1774
                        executor.run(feed=data, fetch_list=[loss])
1775
                 
S
add doc  
sneaxiy 已提交
1776
        '''
Z
Zeng Jinle 已提交
1777
        self._loader.set_sample_list_generator(reader, places)
S
sneaxiy 已提交
1778

S
sneaxiy 已提交
1779
    def decorate_batch_generator(self, reader, places=None):
S
add doc  
sneaxiy 已提交
1780 1781 1782 1783
        '''
        Set the data source of the PyReader object.

        The provided :code:`reader` should be a Python generator,
S
sneaxiy 已提交
1784
        which yields numpy.ndarray-typed or LoDTensor-typed batched data.
S
add doc  
sneaxiy 已提交
1785 1786 1787 1788 1789 1790

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

        Args:
            reader (generator): Python generator that yields LoDTensor-typed
                batched data.
S
sneaxiy 已提交
1791
            places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
S
sneaxiy 已提交
1792
                be provided when PyReader is iterable.
1793 1794 1795 1796

        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
1797 1798 1799
                import paddle.fluid as fluid
                import numpy as np

1800 1801 1802
                EPOCH_NUM = 3
                ITER_NUM = 15
                BATCH_SIZE = 3
G
guofei 已提交
1803 1804 1805 1806 1807
               
                def network(image, label):
                    # User-defined network, here is an example of softmax regression.
                    predict = fluid.layers.fc(input=image, size=10, act='softmax')           
                    return fluid.layers.cross_entropy(input=predict, label=label)
1808 1809 1810 1811 1812 1813 1814 1815

                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])
G
guofei 已提交
1816 1817
                            batch_image = batch_image.astype('float32')
                            batch_label = batch_label.astype('int64')
1818 1819 1820
                            yield batch_image, batch_label
                    return generator

G
guofei 已提交
1821 1822
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
                label = fluid.data(name='label', shape=[None, 1], dtype='int64')
1823 1824 1825
                reader = fluid.io.PyReader(feed_list=[image, label], capacity=4, iterable=True)

                user_defined_generator = random_image_and_label_generator(784, 784)
G
guofei 已提交
1826 1827 1828 1829 1830
                reader.decorate_batch_generator(user_defined_generator, fluid.CPUPlace())
                
                loss = network(image, label)
                executor = fluid.Executor(fluid.CPUPlace())
                executor.run(fluid.default_startup_program())
1831 1832 1833

                for _ in range(EPOCH_NUM):
                    for data in reader():
G
guofei 已提交
1834
                        executor.run(feed=data, fetch_list=[loss])
1835

S
add doc  
sneaxiy 已提交
1836
        '''
Z
Zeng Jinle 已提交
1837 1838 1839 1840 1841
        self._loader.set_batch_generator(reader, places)


class DatasetLoader(DataLoaderBase):
    def __init__(self, dataset, places, drop_last):
1842
        assert isinstance(dataset, paddle.distributed.fleet.dataset.
Z
Zeng Jinle 已提交
1843 1844 1845
                          DatasetBase), "dataset must be type of DatasetBase"
        assert not in_dygraph_mode(
        ), "DatasetLoader is not supported in dygraph mode yet"
1846 1847 1848 1849
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
Z
Zeng Jinle 已提交
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859

        thread_num = len(places)

        assert len(dataset.filelist) >= thread_num, \
            "Filelist number of dataset {} must be not less than place number {}".format(len(dataset.filelist), thread_num)

        if dataset.thread_num != 0 and dataset.thread_num != thread_num:
            logging.warn('thread_num {} which is set in Dataset is ignored'.
                         format(dataset.thread_num))

1860
        dataset._set_thread(thread_num)
Z
Zeng Jinle 已提交
1861

1862
        if isinstance(dataset, paddle.distributed.fleet.dataset.
Z
Zeng Jinle 已提交
1863 1864 1865
                      InMemoryDataset) and dataset.queue_num > thread_num:
            logging.warn("queue_num {} which is set in Dataset is ignored".
                         format(dataset.queue_num))
1866
            dataset._set_queue_num(thread_num)
Z
Zeng Jinle 已提交
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885

        self._dataset = dataset
        use_slots = [
            slot.name for slot in dataset.proto_desc.multi_slot_desc.slots
            if slot.is_used
        ]

        self._iterable_dataset = core.IterableDatasetWrapper(
            dataset.dataset, use_slots,
            _convert_places(places), dataset.proto_desc.batch_size, drop_last)

    def __iter__(self):
        self._dataset._finish_to_run()
        self._dataset._prepare_to_run()
        self._iterable_dataset._start()
        return self

    def __next__(self):
        return self._iterable_dataset._next()