reader.py 79.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
17
import numpy as np
S
sneaxiy 已提交
18
import threading
19
import paddle
20
import time
N
niuliling123 已提交
21
import copy
22

23 24 25 26 27 28 29 30 31 32 33
from .framework import (
    Program,
    Variable,
    program_guard,
    default_main_program,
    default_startup_program,
    _non_static_mode,
    cpu_places,
    _current_expected_place,
    _in_eager_without_dygraph_check,
)
S
sneaxiy 已提交
34
from .executor import global_scope
35
from .data_feeder import DataFeeder, BatchedTensorProvider
36 37 38 39 40 41 42
from .multiprocess_utils import (
    multiprocess_queue_set,
    CleanupFuncRegistrar,
    _cleanup_mmap,
    _cleanup,
    _set_SIGCHLD_handler,
)
43
from .dataloader import BatchSampler, Dataset, IterableDataset, Subset
44 45 46 47 48 49
from .dataloader.dataloader_iter import (
    _DataLoaderIterSingleProcess,
    _DataLoaderIterMultiProcess,
    _DatasetKind,
    default_collate_fn,
)
50
from .dataloader.batch_sampler import _InfiniteIterableSampler
51 52 53
from .layers.io import (
    monkey_patch_reader_methods,
    _copy_reader_var_,
54
    __create_unshared_decorated_reader__,
55
)
S
sneaxiy 已提交
56
from .unique_name import UniqueNameGenerator
57
from .framework import _get_paddle_place, _get_paddle_place_list
58
from paddle.fluid.framework import _set_expected_place, _current_expected_place
59
import logging
60
import warnings
S
sneaxiy 已提交
61

62
### Dygraph DataLoader configs ###
63
import os
64 65
import multiprocessing
import signal
66

T
tianshuo78520a 已提交
67
import queue
68

69 70 71
# NOTE: [ avoid hanging & failed quickly ] These value is used in getting data from another process
QUEUE_GET_TIMEOUT = 60

72
__all__ = ['PyReader', 'DataLoader', 'default_collate_fn']
Z
Zeng Jinle 已提交
73 74

data_loader_unique_name_generator = UniqueNameGenerator()
S
sneaxiy 已提交
75

76
KEEP_DATA_LOADER_ORDER = True
77
USE_PINNED_MEMORY = None
78 79 80 81 82 83 84 85 86 87
# AutoTune Flags
USE_AUTOTUNE = False
TUNING_STEPS = 500


def set_autotune_config(use_autotune, tuning_steps=500):
    global USE_AUTOTUNE
    USE_AUTOTUNE = use_autotune
    global TUNING_STEPS
    TUNING_STEPS = tuning_steps
88 89 90 91 92 93 94 95 96 97


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 已提交
98

99 100 101 102 103 104 105 106 107
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 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
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


123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
# 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:
144
        raise
145 146


147
class DataLoaderBase:
Z
Zeng Jinle 已提交
148 149
    def __init__(self):
        self._places = None
S
sneaxiy 已提交
150

Z
Zeng Jinle 已提交
151 152
    def __call__(self):
        return self
S
sneaxiy 已提交
153

Z
Zeng Jinle 已提交
154 155 156 157 158 159
    def __iter__(self):
        raise NotImplementedError()

    def __next__(self):
        raise NotImplementedError()

160 161 162
    @classmethod
    def _check_input_array(cls, item):
        arr = np.asarray(item)
163
        if arr.dtype == np.object_:
164 165 166 167 168
            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 "
169 170
                "'fluid.create_lod_tensor' to convert it to a LoD-Tensor."
            )
171 172
        return arr

Z
Zeng Jinle 已提交
173

174
class AuToTune:
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    def __init__(self, loader):
        self.loader = loader
        self.max_num_worker = multiprocessing.cpu_count() / 2

    def __call__(self):
        # use default loader
        if (not USE_AUTOTUNE) or (not self.need_autotune()):
            return self.loader.num_workers

        # get autotune loader
        auto_tune_loader = self.get_autotune_loader()
        if auto_tune_loader is None:
            return self.loader.num_workers

        # pick the best num_workers
        auto_tune_start = time.time()
        logging.debug("========= DataLoader Auto Tune =========")
192 193 194
        logging.debug(
            "User config for DataLoader: " + str(self.loader.num_workers)
        )
195 196
        best_num_workers = 0
        min_cost = float("inf")
197 198 199
        logging.debug(
            "Tuning Range for num_workers: 0 ~ " + str(self.max_num_worker)
        )
200 201 202 203 204 205 206 207
        num_workers = 0
        while num_workers < self.max_num_worker:
            auto_tune_loader.num_workers = num_workers
            avg_cost = self.evaluate_reader_cost(auto_tune_loader)
            if min_cost * 0.75 > avg_cost:
                min_cost = avg_cost
                best_num_workers = num_workers
            else:
208 209 210 211 212 213
                update_num = self.is_best(
                    auto_tune_loader,
                    best_num_workers,
                    min_cost,
                    self.max_num_worker,
                )
214 215 216 217
                if update_num == best_num_workers:
                    break
                else:
                    best_num_workers = update_num
218 219 220 221 222 223
            logging.debug(
                "num_workers: "
                + str(num_workers)
                + " avg_cost: "
                + str(avg_cost)
            )
224
            num_workers += 2
225 226 227 228 229 230 231 232
        logging.info(
            "auto_tune dataLoader best_num_workers: " + str(best_num_workers)
        )
        logging.debug(
            "AutoTuning Cost for DataLoader: "
            + str(time.time() - auto_tune_start)
            + ' seconds'
        )
233 234 235 236 237

        # tune the default loader's num_workers
        return best_num_workers

    def need_autotune(self):
238
        if sys.platform == 'darwin' or sys.platform == 'win32':
239 240 241 242 243 244 245 246 247 248
            return False
        else:
            return True

    def get_sub_dataset(self, dataset, batch_size):
        num_samples = min(batch_size * TUNING_STEPS, len(dataset))
        sub_dataset = Subset(dataset, indices=list(range(num_samples)))
        return sub_dataset

    def get_autotune_loader(self):
N
niuliling123 已提交
249
        loader = copy.copy(self.loader)
250
        batch_size = self.loader.batch_sampler.batch_size
251 252 253
        if isinstance(
            self.loader.batch_sampler, paddle.io.DistributedBatchSampler
        ):
254 255 256 257 258 259 260 261
            dataset = self.loader.batch_sampler.dataset
            sub_dataset = self.get_sub_dataset(dataset, batch_size)
            loader.batch_sampler = paddle.io.DistributedBatchSampler(
                dataset=sub_dataset,
                batch_size=batch_size,
                num_replicas=self.loader.batch_sampler.nranks,
                rank=self.loader.batch_sampler.local_rank,
                shuffle=self.loader.batch_sampler.shuffle,
262 263
                drop_last=self.loader.batch_sampler.drop_last,
            )
264 265 266 267 268 269
        elif isinstance(self.loader.batch_sampler, paddle.io.BatchSampler):
            dataset = self.loader.batch_sampler.sampler.data_source
            sub_dataset = self.get_sub_dataset(dataset, batch_size)
            loader.batch_sampler = paddle.io.BatchSampler(
                dataset=sub_dataset,
                batch_size=batch_size,
270 271
                drop_last=self.loader.batch_sampler.drop_last,
            )
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
        else:
            loader = None
        return loader

    def evaluate_reader_cost(self, reader):
        costs = []
        avg_cost = 0
        start = time.time()
        for i, data in enumerate(reader):
            costs.append(time.time() - start)
            start = time.time()
        if len(costs) > 2:
            avg_cost = sum(costs[2:]) / len(costs[2:])
        else:
            avg_cost = sum(costs[0:]) / len(costs[0:])
        return avg_cost

    def is_best(self, reader, best_workers, best_time, num_work_boundary):
        step = 0
        num_workers = best_workers + 1
        boundary = 1
        while num_workers < num_work_boundary and step < 5:
            self.loader.num_workers = num_workers
            time = self.evaluate_reader_cost(reader)
296 297 298 299 300 301
            logging.debug(
                "for back num_workers: "
                + str(num_workers)
                + " avg_cost: "
                + str(time)
            )
302
            step += 1
303
            if time < best_time * 0.70 * boundary:
304 305 306 307 308 309 310
                return num_workers
            else:
                num_workers += 1
            boundary *= 0.80
        return best_workers


311
class DataLoader:
312 313 314 315 316 317 318 319
    """
    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 已提交
320
    DataLoader supports map-style dataset and iterable-style dataset.
321

K
Kaipeng Deng 已提交
322 323 324 325 326 327 328
    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`
329

330 331 332 333 334 335
    .. 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.

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    **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.


351
    Args:
352
        dataset(Dataset): the dataset to load data from, should be an
353 354
            instance of subclass of :code:`paddle.io.Dataset` or
            :code:`paddle.io.IterableDataset`.
355
        feed_list (list(Tensor)|tuple(Tensor), optional): feed Tensor list.
356
            The Tensors should be created by :code:`paddle.static.data()`.
357 358
            :attr:`feed_list` must be set if :attr:`return_list` is
            False. Default None.
359
        places(list(Place)|tuple(Place)|list(str), optional): a list of Place,
360
            to put data onto, :attr:`places` can be None, if
361
            :attr:`places` is None, default place(CPUPlace or CUDAPlace(0))
362 363 364
            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.
365
        return_list (bool, optional): whether the return value on each device is
366
            presented as a list. If :attr:`return_list=False`, the return
K
Kaipeng Deng 已提交
367
            value on each device would be a dict of str -> Tensor, where
368
            the key of the dict is the name of each fed Tensors. If
369
            :attr:`return_list=True`, the return value on each device would
K
Kaipeng Deng 已提交
370
            be a list(Tensor). :attr:`return_list` can only be True
371
            in dynamic graph mode. Default True.
372
        batch_sampler(BatchSampler, optional): an instance of `paddle.io.BatchSampler`
373 374
            to generate batch indices to draw samples from :attr:`dataset`
            and combine a batch. Default None.
375
        batch_size(int|None, optional): sample number in a mini-batch, a substitution
376 377 378 379
            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.
380
        shuffle(bool, optional): whther to shuffle indices order before genrate
381 382
            batch indices, a substitution parameter for :attr:`batch_sampler`
            see :attr:`batch_size`. Default False.
383
        drop_last(bool, optional): whether drop the last incomplete batch dataset size
384 385
            is not divisible by the batch size, a substitution parameter
            for :attr:`batch_sampler`, see :attr:`batch_size`. Default False
386
        collate_fn(callable, optional): function to generate mini-batch data by merging
387 388
            the sample list, None for only stack each fields of sample in axis
            0(same as :attr::`np.stack(..., axis=0)`). Default None
389
        num_workers(int, optional): the number of subprocess to load data, 0 for no
390
            subprocess used and loading data in main process. Default 0
391
        use_buffer_reader (bool, optional): whether to use bufferred reader.
392
            If use_buffer_reader=True, the DataLoader would prefetch
393
            batch data asynchronously, so it would speed up data feeding
394 395
            and occupies a little more CPU or GPU memory, i.e., the memory
            of one batch input data. Default True.
396 397 398
        prefetch_factor (int, optional): Number of batch data the DataLoader would prefetch
            if use_buffer_reader=True. Default 2.
        use_shared_memory (bool, optional): whether to use shared memory to speed up
399 400 401 402 403
            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.
404
        timeout(int, optional): the timeout value for getting data form output queue
405
            of subprocesses. Default 0.
406
        worker_init_fn(callable, optional): init function which will be called with
407 408 409 410
            worker id on each subproces starting if not set as None. Default
            None.

    Returns:
411
        DataLoader: an iterable object for data iterating, each elemnet of the generated data is a Tensor.
412 413

    Examples:
414

415 416 417
        .. code-block:: python

            import numpy as np
418 419

            import paddle
K
Kaipeng Deng 已提交
420 421
            import paddle.nn as nn
            import paddle.nn.functional as F
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
            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

444 445
            dataset = RandomDataset(BATCH_NUM * BATCH_SIZE)

K
Kaipeng Deng 已提交
446
            class SimpleNet(nn.Layer):
447
                def __init__(self):
448
                    super().__init__()
K
Kaipeng Deng 已提交
449
                    self.fc = nn.Linear(IMAGE_SIZE, CLASS_NUM)
450 451 452 453

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

K
Kaipeng Deng 已提交
454 455 456
            simple_net = SimpleNet()
            opt = paddle.optimizer.SGD(learning_rate=1e-3,
                                      parameters=simple_net.parameters())
457 458

            loader = DataLoader(dataset,
K
Kaipeng Deng 已提交
459
                                batch_size=BATCH_SIZE,
460 461 462 463 464
                                shuffle=True,
                                drop_last=True,
                                num_workers=2)

            for e in range(EPOCH_NUM):
K
Kaipeng Deng 已提交
465 466 467 468 469 470 471 472
                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())))
473 474


475 476 477 478
    .. note::
        For reading iterable dataset with multiprocess Dataloader,
        please see :code:`paddle.io.IterableDataset`

479 480
    """

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
    def __init__(
        self,
        dataset,
        feed_list=None,
        places=None,
        return_list=True,
        batch_sampler=None,
        batch_size=1,
        shuffle=False,
        drop_last=False,
        collate_fn=None,
        num_workers=0,
        use_buffer_reader=True,
        prefetch_factor=2,
        use_shared_memory=True,
        timeout=0,
        worker_init_fn=None,
        persistent_workers=False,
    ):
500 501 502
        self.return_list = return_list
        self.collate_fn = collate_fn
        self.use_buffer_reader = use_buffer_reader
503
        self.prefetch_factor = prefetch_factor
504 505 506 507
        self.worker_init_fn = worker_init_fn

        self.dataset = dataset

J
Jiabin Yang 已提交
508
        if not return_list and not _non_static_mode():
509 510 511
            assert (
                feed_list is not None
            ), "feed_list should be set when return_list=False"
512 513
        self.feed_list = feed_list

514 515
        if places is None:
            places = _current_expected_place()
516 517 518 519
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
520 521 522
        self.places = _convert_places(places)

        assert num_workers >= 0, "num_workers should be a non-negative value"
523 524 525
        if num_workers > 0 and (
            sys.platform == 'darwin' or sys.platform == 'win32'
        ):
526
            warnings.warn(
527 528 529
                "DataLoader with multi-process mode is not supported on MacOs and Windows currently."
                " Please use signle-process mode with num_workers = 0 instead"
            )
530 531 532
            num_workers = 0
        self.num_workers = num_workers

533 534
        assert prefetch_factor > 0, "prefetch_factor should be a positive value"

535 536 537 538 539 540 541
        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

542 543 544 545
        if isinstance(dataset, IterableDataset):
            self.dataset_kind = _DatasetKind.ITER
            if shuffle:
                raise ValueError(
546 547 548 549
                    "IterableDataset not support shuffle, but got shuffle={}".format(
                        shuffle
                    )
                )
550 551
            if batch_sampler is not None:
                raise ValueError(
552 553
                    "IterableDataset expect unspecified batch_sampler"
                )
554 555 556
        else:
            self.dataset_kind = _DatasetKind.MAP

557
        if batch_sampler is not None:
558 559
            assert batch_size == 1 and not shuffle and not drop_last, (
                "batch_size/shuffle/drop_last should not be set when "
560
                "batch_sampler is given"
561
            )
562
            self.batch_sampler = batch_sampler
563 564 565 566
            self.batch_size = None
        elif batch_size is None:
            self.batch_sampler = None
            self.batch_size = None
567
        else:
568 569
            assert batch_size > 0, (
                "batch_size should be None or a positive value when "
570
                "batch_sampler is not given"
571
            )
572
            self.batch_size = batch_size
573
            if isinstance(dataset, IterableDataset):
574
                self.batch_sampler = _InfiniteIterableSampler(
575 576
                    dataset, batch_size
                )
577
            else:
578 579 580 581 582 583
                self.batch_sampler = BatchSampler(
                    dataset=dataset,
                    batch_size=batch_size,
                    shuffle=shuffle,
                    drop_last=drop_last,
                )
584

585
        self.drop_last = drop_last
586 587
        self.auto_collate_batch = self.batch_sampler is not None

588
        self.pin_memory = False
J
Jiabin Yang 已提交
589
        if _non_static_mode():
590 591 592
            self.pin_memory = (
                True if use_pinned_memory() is None else use_pinned_memory()
            )
593

K
Kaipeng Deng 已提交
594 595
        self._persistent_workers = persistent_workers
        self._iterator = None
596
        self.num_workers = AuToTune(self).__call__()
K
Kaipeng Deng 已提交
597

598
    def __len__(self):
599 600 601
        if self.dataset_kind == _DatasetKind.ITER:
            raise ValueError("length of IterableDataset not supported")
        else:
602
            if self.auto_collate_batch:
603
                return len(self.batch_sampler)
604 605
            else:
                return len(self.dataset)
606 607 608 609

    def __iter__(self):
        if self.num_workers == 0:
            return _DataLoaderIterSingleProcess(self)
K
Kaipeng Deng 已提交
610 611 612 613 614 615
        elif self._persistent_workers:
            if self._iterator is None:
                self._iterator = _DataLoaderIterMultiProcess(self)
            else:
                self._iterator._reset()
            return self._iterator
616 617 618 619 620 621
        else:
            return _DataLoaderIterMultiProcess(self)

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

Z
Zeng Jinle 已提交
622
    @staticmethod
623 624 625 626 627 628 629 630 631
    def from_generator(
        feed_list=None,
        capacity=None,
        use_double_buffer=True,
        iterable=True,
        return_list=False,
        use_multiprocess=False,
        drop_last=True,
    ):
Z
Zeng Jinle 已提交
632
        """
K
Kaipeng Deng 已提交
633 634 635 636
        .. warning::
          This API will be deprecated in the future, it is recommended to use
          :code:`paddle.io.DataLoader` which supports multi-processes acceleration.

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

640
        Create a DataLoader object for loading data from Python generator.
Z
Zeng Jinle 已提交
641 642 643 644
        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
645
        :code:`set_sample_generator` , :code:`set_sample_list_generator` and
Z
Zeng Jinle 已提交
646 647
        :code:`set_batch_generator` . Please see the following example codes
        to know their usages.
648

Z
Zeng Jinle 已提交
649 650 651
        If iterable = True, the created DataLoader object is a Python generator
        object, which is iterable using for-range loop.

652
        If iterable = False, the created DataLoader object provides
Z
Zeng Jinle 已提交
653
        :code:`start()` and :code:`reset()` method to control the data reading
654
        process.
Z
Zeng Jinle 已提交
655

656
        Args:
657 658
            feed_list (list(Tensor)|tuple(Tensor)): feed Tensor list.
                The Tensors should be created by :code:`fluid.data()`.
Z
Zeng Jinle 已提交
659
            capacity (int): capacity of the queue maintained in DataLoader.
660 661
                The unit is batch number. Set larger capacity if your reader
                is fast.
662
            use_double_buffer (bool, optional): whether to use double_buffer_reader.
663 664
                If use_double_buffer=True, the DataLoader would prefetch next
                batch data asynchronously, so it would speed up data feeding
Z
Zeng Jinle 已提交
665
                and occupies a little more CPU or GPU memory, i.e., the memory
666
                of one batch input data.
667 668
            iterable (bool, optional): whether the created DataLoader is iterable.
            return_list (bool, optional): whether the return value on each device is
669 670 671 672
                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
                the name of each fed Tensors. If return_list=True, the
Z
Zeng Jinle 已提交
673 674
                return value on each device would be a list(LoDTensor). It is
                recommended to use return_list=False in static graph mode and
675
                use return_list=True in dygraph mode.
676 677 678
            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,
679 680
                whether this parameter is set or not has no effect.
                The Default value is False.
681 682 683
            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,
684
                because all CPU cores/GPU cards must read data from DataLoader.
685 686
                In inference phase, users can set drop_last=False, so that the
                last batches whose number is less than the CPU core/GPU card
687
                number can be tested.
Z
Zeng Jinle 已提交
688 689 690 691

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

692
        Examples 1:
693

Z
Zeng Jinle 已提交
694
            .. code-block:: python
S
sneaxiy 已提交
695

696 697 698
                '''
                Example in static graph mode
                '''
Z
Zeng Jinle 已提交
699
                import numpy as np
700

701 702 703 704 705
                import paddle
                import paddle.static as static
                import paddle.nn.functional as F


706
                BATCH_NUM = 10
Z
Zeng Jinle 已提交
707 708 709 710 711 712 713 714
                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

715
                DATA_FORMAT = 'batch_generator' # data format of data source user provides
Z
Zeng Jinle 已提交
716

717 718
                paddle.enable_static()

Z
Zeng Jinle 已提交
719
                def simple_net(image, label):
720 721 722 723
                    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 已提交
724 725 726 727 728 729 730 731 732 733
                    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.
734
                def sample_generator_creator():
Z
Zeng Jinle 已提交
735 736 737 738 739 740 741 742 743 744 745
                    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__():
746
                        for _ in range(BATCH_NUM):
Z
Zeng Jinle 已提交
747 748 749 750 751 752 753
                            sample_list = []
                            for _ in range(BATCH_SIZE):
                                image, label = get_random_images_and_labels([784], [1])
                                sample_list.append([image, label])

                            yield sample_list

754
                    return __reader__
Z
Zeng Jinle 已提交
755

756
                # If the data generator yields a batch each time,
Z
Zeng Jinle 已提交
757 758 759 760
                # use DataLoader.set_batch_generator to set the data source.
                def batch_generator_creator():
                    def __reader__():
                        for _ in range(BATCH_NUM):
761
                            batch_image, batch_label = get_random_images_and_labels([BATCH_SIZE, 784], [BATCH_SIZE, 1])
Z
Zeng Jinle 已提交
762
                            yield batch_image, batch_label
H
Huihuang Zheng 已提交
763

Z
Zeng Jinle 已提交
764
                    return __reader__
765

766
                # If DataLoader is iterable, use for loop to train the network
Z
Zeng Jinle 已提交
767 768 769 770
                def train_iterable(exe, prog, loss, loader):
                    for _ in range(EPOCH_NUM):
                        for data in loader():
                            exe.run(prog, feed=data, fetch_list=[loss])
771

772
                # If DataLoader is not iterable, use start() and reset() method to control the process
Z
Zeng Jinle 已提交
773 774 775 776 777 778
                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])
779
                        except paddle.core.EOFException:
780
                            loader.reset() # call DataLoader.reset() after catching EOFException
Z
Zeng Jinle 已提交
781 782 783 784 785 786 787 788 789 790

                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')
791

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

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

Z
Zeng Jinle 已提交
798 799
                # Define network
                loss = simple_net(image, label)
S
sneaxiy 已提交
800

801
                places = static.cuda_places() if USE_GPU else static.cpu_places()
Z
Zeng Jinle 已提交
802
                set_data_source(loader, places)
S
sneaxiy 已提交
803

804 805
                exe = static.Executor(places[0])
                exe.run(static.default_startup_program())
H
Huihuang Zheng 已提交
806

807
                prog = static.CompiledProgram(static.default_main_program())
Z
Zeng Jinle 已提交
808 809 810 811 812 813
                if loader.iterable:
                    train_iterable(exe, prog, loss, loader)
                else:
                    train_non_iterable(exe, prog, loss, loader)


814 815 816 817
        Examples 2:

            .. code-block:: python

Z
Zeng Jinle 已提交
818
                '''
819
                Example in dynamic graph mode.
Z
Zeng Jinle 已提交
820
                '''
821
                import numpy as np
822

823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
                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):
853
                        super().__init__()
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
                        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())))

Z
Zeng Jinle 已提交
885
        """
J
Jiabin Yang 已提交
886
        if _non_static_mode():
887 888 889 890 891 892 893 894
            return DygraphGeneratorLoader(
                feed_list,
                capacity,
                use_double_buffer,
                iterable,
                return_list,
                use_multiprocess,
            )
895
        else:
896 897 898 899 900 901 902 903
            return GeneratorLoader(
                feed_list,
                capacity,
                use_double_buffer,
                iterable,
                return_list,
                drop_last,
            )
Z
Zeng Jinle 已提交
904 905 906 907

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

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

Z
Zeng Jinle 已提交
915 916
        Args:
            dataset (InMemoryDataset|QueueDataset): the dataset object.
917 918 919
            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.
920 921 922
            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.
923

Z
Zeng Jinle 已提交
924
        Returns:
925 926
            loader (DataLoader): the created DataLoader object, which can be
                treated as a Python generator.
927

Z
Zeng Jinle 已提交
928 929 930
        Examples:

            .. code-block:: python
931

932 933 934 935
                import paddle
                import paddle.static as static

                paddle.enable_static()
936

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

940 941 942 943 944
                dataset = paddle.distributed.QueueDataset()
                dataset.init(
                    batch_size=32,
                    pipe_command='cat',
                    use_var=[image, label])
Z
Zeng Jinle 已提交
945
                dataset.set_filelist(['a.txt', 'b.txt', 'c.txt'])
946

947
                loader = paddle.io.DataLoader.from_dataset(dataset, static.cpu_places())
Z
Zeng Jinle 已提交
948 949
        """
        return DatasetLoader(dataset, places, drop_last)
S
sneaxiy 已提交
950

S
sneaxiy 已提交
951

952 953 954 955
class DygraphGeneratorLoader(DataLoaderBase):
    """
    The GeneratorLoader of dygraph

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

960 961 962 963 964 965 966 967 968
    def __init__(
        self,
        feed_list=None,
        capacity=None,
        use_double_buffer=True,
        iterable=True,
        return_list=True,
        use_multiprocess=False,
    ):
969 970 971 972 973 974 975 976 977 978
        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:
979 980
            warnings.warn(
                "Please NOTE: DygraphGeneratorLoader supports iterable mode only. Change to iterable mode."
981 982 983
            )
        self._iterable = True
        if not return_list:
984 985
            warnings.warn(
                "Please NOTE: DygraphGeneratorLoader supports returning as list only. Change to return as list."
986 987 988 989 990
            )
        self._return_list = True

        # NOTE: the multiprocessing in different platform is incompatible, we will solve it later
        self._use_multiprocess = use_multiprocess
991 992 993
        if self._use_multiprocess and (
            sys.platform == 'darwin' or sys.platform == 'win32'
        ):
994 995
            warnings.warn(
                "NOTE: DygraphGeneratorLoader with multiprocess mode is not currently supported on MacOs and Windows."
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
            )
            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
1009
        # mode, this thread is used to get next batch data from self._batch_reader, then
1010 1011
        # push it into self._blocking_queue
        self._thread = None
1012 1013 1014
        self._pin_memory = (
            True if use_pinned_memory() is None else use_pinned_memory()
        )
1015 1016 1017 1018 1019 1020 1021 1022 1023

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

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

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
    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)

1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    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
1045
            core._erase_process_pids(id(self))
1046

1047 1048 1049 1050 1051 1052 1053 1054 1055
    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(
1056 1057
            core.Variable(), self._capacity, False
        )
1058
        self._reader = None
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
        self._reader = core.create_py_reader(
            self.queue,
            self._var_names,
            self._shapes,
            self._dtypes,
            self._need_check_feed,
            self._places,
            self._use_double_buffer,
            True,
            self._pin_memory,
        )
1070 1071 1072

    def _start(self):
        if self._use_multiprocess:
1073 1074 1075
            # clear old _data_queue and remove it from multiprocess_queue_set
            self._clear_and_remove_data_queue()
            # set data_queue and process
1076
            self._data_queue = multiprocessing.Queue(self._capacity)
1077 1078 1079
            # add _data_queue into global queue set
            global multiprocess_queue_set
            multiprocess_queue_set.add(self._data_queue)
1080 1081 1082 1083
            self._process = multiprocessing.Process(
                target=_reader_process_loop,
                args=(self._batch_reader, self._data_queue),
            )
1084 1085 1086 1087 1088
            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
1089
            # or just hang, the main process will hang waiting for data, so here need to deal
1090
            # with SIGSEGV and SIGBUS of child process; 2. if the main process end before child
1091
            # process, it shuts the all its daemonic children down with a SIGTERM (instead of
1092
            # joining them without a timeout), so here nedd to deal with SIGTERM.
1093 1094
            core._set_process_pids(id(self), [self._process.pid])
            _set_SIGCHLD_handler()
1095 1096 1097 1098

            # Set reader_thread
            self._thread_done_event = threading.Event()
            self._thread = threading.Thread(
1099
                target=self._reader_thread_loop_for_multiprocess,
1100 1101
                args=(_current_expected_place(),),
            )
1102 1103 1104
            self._thread.daemon = True
            self._thread.start()
        else:
1105
            self._thread = threading.Thread(
1106
                target=self._reader_thread_loop_for_singleprocess,
1107 1108
                args=(_current_expected_place(),),
            )
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
            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"
1120 1121 1122
        assert (
            self._batch_reader is not None
        ), "Data source of DataLoader has not set yet"
1123 1124 1125 1126 1127 1128 1129

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

    def __next__(self):
        try:
J
Jiabin Yang 已提交
1130
            if _in_eager_without_dygraph_check():
1131
                return core.eager.read_next_tensor_list(
1132 1133
                    self._reader.read_next_list()[0]
                )
1134 1135
            else:
                return self._reader.read_next_var_list()
1136 1137
        except StopIteration:
            self._reset()
1138
            raise
1139

1140 1141 1142 1143 1144 1145 1146 1147 1148
    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!")

1149 1150
    def _reader_thread_loop_for_multiprocess(self, legacy_expected_place):
        # See _DataLoaderIterSingleProcess._thread_loop() for why set expected place here.
L
Leo Chen 已提交
1151
        core.set_current_thread_name("Dataloader_" + str(id(self)))
1152 1153
        _set_expected_place(legacy_expected_place)

1154 1155
        while not self._thread_done_event.is_set():
            try:
1156 1157 1158 1159
                # 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
1160
                # we try to get data from `data_queue`
1161 1162 1163 1164 1165 1166 1167
                # 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)
1168
            except Exception as e:
1169 1170 1171
                # 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.
1172
                self._exit_thread_unexpectedly()
1173 1174
                logging.error(
                    "DataLoader reader thread failed to read data from the multiprocessing.Queue."
1175
                )
1176
                raise e
1177 1178

            if not self._thread_done_event.is_set():
1179
                if tensor_list is not None:
1180 1181
                    try:
                        array = core.LoDTensorArray()
1182 1183
                        for tensor in tensor_list:
                            array.append(tensor)
1184 1185
                        if not self._blocking_queue.push(array):
                            self._blocking_queue.close()
1186
                    except Exception as e:
1187
                        self._exit_thread_unexpectedly()
1188
                        raise e
1189
                else:
1190
                    self._exit_thread_expectedly()
1191

1192
    def _reader_thread_loop_for_singleprocess(self, legacy_expected_place):
1193
        try:
1194
            # See _DataLoaderIterSingleProcess._thread_loop() for why set expected place here.
L
Leo Chen 已提交
1195
            core.set_current_thread_name("Dataloader_" + str(id(self)))
1196 1197
            _set_expected_place(legacy_expected_place)

1198 1199 1200 1201
            for sample in self._batch_reader():
                array = core.LoDTensorArray()
                for item in sample:
                    if not isinstance(item, core.LoDTensor):
1202
                        item = self._check_input_array(item)
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
                        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
1214
        except Exception as e:
1215 1216 1217
            self._blocking_queue.kill()
            self._thread = None
            logging.warning(
1218 1219
                "DygraphDataLoader reader thread raised an exception."
            )
1220
            raise e
1221

1222 1223 1224
    def set_sample_generator(
        self, reader, batch_size, drop_last=True, places=None
    ):
1225
        assert batch_size > 0, "batch_size must be larger than 0"
1226 1227 1228 1229
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
1230 1231 1232 1233
        self.set_sample_list_generator(
            paddle.batch(reader, batch_size=batch_size, drop_last=drop_last),
            places=places,
        )
1234 1235 1236
        return self

    def set_sample_list_generator(self, reader, places=None):
1237 1238 1239 1240 1241
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)

1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
        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):
1257 1258 1259 1260
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
1261
        self._batch_reader = reader
1262 1263
        if places is None:
            places = _current_expected_place()
1264
        self._places = _convert_places(places)
1265 1266 1267
        assert (
            len(self._places) == 1
        ), "Number of places must be 1 in imperative mode"
1268 1269 1270
        return self


Z
Zeng Jinle 已提交
1271
class GeneratorLoader(DataLoaderBase):
1272 1273 1274 1275 1276 1277 1278 1279 1280
    def __init__(
        self,
        feed_list=None,
        capacity=None,
        use_double_buffer=True,
        iterable=True,
        return_list=False,
        drop_last=True,
    ):
S
sneaxiy 已提交
1281
        self._tensor_reader = None
Z
Zeng Jinle 已提交
1282
        self._places = None
S
sneaxiy 已提交
1283
        self._thread = None
1284
        self._queue = None
1285
        self._feed_list = feed_list
1286 1287 1288
        self._exited = False
        self._drop_last = drop_last
        self._keep_order = keep_data_loader_order()
1289 1290
        if not capacity:
            raise ValueError("Please give value to capacity.")
1291 1292 1293
        self._iterable = iterable
        self._return_list = return_list
        if not self._feed_list:
1294
            raise Exception("Feed list must be given under static graph mode.")
S
sneaxiy 已提交
1295 1296 1297 1298
        self._use_double_buffer = use_double_buffer
        self._capacity = capacity
        if not self._iterable:
            self._init_non_iterable()
S
sneaxiy 已提交
1299

Z
Zeng Jinle 已提交
1300
    def _wait_thread_ends(self):
1301
        # Get self._thread first to prevent data race, because __thread_main__
Z
Zeng Jinle 已提交
1302 1303 1304 1305 1306 1307 1308 1309
        # 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()
1310 1311 1312 1313 1314 1315
        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
        ]
1316
        self._queue = core.init_lod_tensor_blocking_queue(
1317 1318
            core.Variable(), self._capacity, self._keep_order
        )
1319
        self._reader = None
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
        self._reader = core.create_py_reader(
            self.queue,
            self._var_names,
            self._shapes,
            self._dtypes,
            self._need_check_feed,
            self._places,
            self._use_double_buffer,
            self._drop_last,
            False,
        )
S
sneaxiy 已提交
1331 1332 1333 1334 1335 1336 1337

    def _init_non_iterable(self):
        lod_levels = []
        dtypes = []
        shape_concat = []
        ranks = []
        shapes = []
1338
        need_check_feed = []
S
sneaxiy 已提交
1339 1340 1341 1342 1343 1344 1345

        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)
1346
            need_check_feed.append(int(feed_data.desc.need_check_feed()))
S
sneaxiy 已提交
1347

Z
Zeng Jinle 已提交
1348
        queue_name = data_loader_unique_name_generator(
1349 1350
            'lod_tensor_blocking_queue'
        )
Z
Zeng Jinle 已提交
1351
        reader_name = data_loader_unique_name_generator('create_py_reader')
1352
        double_buffer_name = data_loader_unique_name_generator('double_buffer')
S
sneaxiy 已提交
1353

S
sneaxiy 已提交
1354
        var = global_scope().var(queue_name)
1355
        self._queue = core.init_lod_tensor_blocking_queue(
1356 1357
            var, self._capacity, self._keep_order
        )
1358 1359 1360 1361 1362

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

1364
        reader_var = block.create_var(name=reader_name)
S
sneaxiy 已提交
1365

1366
        dtype_int = [int(t) for t in dtypes]
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
        block.append_op(
            type='create_py_reader',
            inputs={'blocking_queue': [queue_name]},
            outputs={'Out': [reader_var]},
            attrs={
                'shape_concat': shape_concat,
                'lod_levels': lod_levels,
                'dtypes': dtype_int,
                'need_check_feed': need_check_feed,
                'ranks': ranks,
            },
        )
S
sneaxiy 已提交
1379

1380 1381 1382
        reader_var.desc.set_dtypes(dtypes)
        reader_var.persistable = True
        reader_var.stop_gradient = True
S
sneaxiy 已提交
1383

1384 1385 1386 1387 1388 1389
        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_(
1390 1391
                default_main_program().current_block(), reader_var
            )
1392 1393 1394

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

1396
            reader = monkey_patch_reader_methods(main_prog_var)
S
sneaxiy 已提交
1397

1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
        if self._use_double_buffer:
            double_buffer_reader = __create_unshared_decorated_reader__(
                'create_double_buffer_reader',
                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

S
sneaxiy 已提交
1410 1411 1412 1413 1414
        self._reader = reader

        default_main_program().current_block().append_op(
            type='read',
            inputs={'Reader': [self._reader]},
1415
            outputs={'Out': self._feed_list},
1416 1417
            attrs={'drop_last': self._drop_last},
        )
S
sneaxiy 已提交
1418 1419 1420 1421 1422 1423 1424 1425

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

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

Z
Zeng Jinle 已提交
1427 1428
    def __iter__(self):
        assert self.iterable, "DataLoader is not iterable"
1429 1430 1431
        assert (
            self._tensor_reader is not None
        ), "Data source of DataLoader has not set yet"
S
sneaxiy 已提交
1432

Z
Zeng Jinle 已提交
1433
        self._init_iterable()
S
sneaxiy 已提交
1434
        self._start()
Z
Zeng Jinle 已提交
1435 1436 1437 1438
        return self

    def __next__(self):
        try:
1439
            if self._return_list:
1440 1441 1442 1443
                data = self._reader.read_next_list()
                for i in range(len(data)):
                    data[i] = data[i]._move_to_list()
                return data
1444
            else:
1445
                return self._reader.read_next()
Z
Zeng Jinle 已提交
1446 1447 1448
        except StopIteration:
            self._queue.close()
            self._reset()
1449
            raise
Z
Zeng Jinle 已提交
1450 1451

    def start(self):
1452 1453 1454
        assert (
            not self._iterable
        ), "start() cannot be called when DataLoader is iterable"
1455
        self._start()
Z
Zeng Jinle 已提交
1456 1457

    def reset(self):
1458 1459 1460
        assert (
            not self._iterable
        ), "reset() cannot be called when DataLoader is iterable"
1461
        self._reset()
Z
Zeng Jinle 已提交
1462 1463

    def _start(self):
1464
        def __thread_main__(legacy_expected_place):
Z
Zeng Jinle 已提交
1465
            try:
1466
                # See _DataLoaderIterSingleProcess._thread_loop() for why set expected place here.
L
Leo Chen 已提交
1467
                core.set_current_thread_name("Dataloader_" + str(id(self)))
1468 1469
                _set_expected_place(legacy_expected_place)

1470 1471 1472 1473
                while not self._queue.wait_for_inited(1):
                    if self._exited:
                        return

Z
Zeng Jinle 已提交
1474 1475 1476 1477
                for tensors in self._tensor_reader():
                    array = core.LoDTensorArray()
                    for item in tensors:
                        if not isinstance(item, core.LoDTensor):
1478
                            item = self._check_input_array(item)
Z
Zeng Jinle 已提交
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
                            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
1490
            except Exception as e:
Z
Zeng Jinle 已提交
1491
                self._queue.kill()
Z
Zeng Jinle 已提交
1492
                self._thread = None
1493
                logging.warning('Your reader has raised an exception!')
1494
                raise e
Z
Zeng Jinle 已提交
1495

1496 1497 1498
        self._thread = threading.Thread(
            target=__thread_main__, args=(_current_expected_place(),)
        )
Z
Zeng Jinle 已提交
1499 1500
        self._thread.daemon = True
        self._thread.start()
S
sneaxiy 已提交
1501

S
sneaxiy 已提交
1502
    def _reset(self):
1503
        self._queue.close()
1504
        self._exited = True
Z
Zeng Jinle 已提交
1505 1506 1507 1508
        thread = self._thread
        if thread is not None:
            thread.join()

1509
        self._exited = False
1510 1511
        self._reader.reset()

1512 1513 1514
    def set_sample_generator(
        self, reader, batch_size, drop_last=True, places=None
    ):
Z
Zeng Jinle 已提交
1515
        assert batch_size > 0, "batch_size must be larger than 0"
1516 1517 1518 1519
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
1520 1521 1522 1523 1524 1525 1526
        has_lod = False
        for f in self._feed_list:
            if f.lod_level != 0:
                has_lod = True
                break

        if has_lod:
1527 1528 1529 1530 1531 1532
            self.set_sample_list_generator(
                paddle.batch(
                    reader, batch_size=batch_size, drop_last=drop_last
                ),
                places=places,
            )
1533
        else:
1534 1535 1536 1537 1538 1539 1540
            reader = BatchedTensorProvider(
                feed_list=self._feed_list,
                place=core.CPUPlace(),
                batch_size=batch_size,
                generator=reader,
                drop_last=drop_last,
            )
1541
            self.set_batch_generator(reader, places=places)
Z
Zeng Jinle 已提交
1542 1543 1544
        return self

    def set_sample_list_generator(self, reader, places=None):
1545 1546 1547 1548
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
1549
        with program_guard(Program(), Program()):
1550 1551 1552
            feeder = DataFeeder(
                feed_list=self._feed_list, place=core.CPUPlace()
            )
1553
            paddle_reader = feeder.decorate_reader(reader, multi_devices=False)
Z
Zeng Jinle 已提交
1554

1555 1556 1557
        def __tensor_reader_impl__():
            for slots in paddle_reader():
                yield [slots[var.name] for var in self._feed_list]
Z
Zeng Jinle 已提交
1558 1559 1560 1561 1562

        self.set_batch_generator(__tensor_reader_impl__, places)
        return self

    def set_batch_generator(self, reader, places=None):
1563 1564 1565 1566
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
Z
Zeng Jinle 已提交
1567 1568
        self._tensor_reader = reader
        if self._iterable:
1569 1570 1571
            assert (
                places is not None
            ), "Places cannot be None when DataLoader is iterable"
Z
Zeng Jinle 已提交
1572 1573 1574 1575
            self._places = _convert_places(places)
        else:
            if places is not None:
                logging.info(
1576 1577
                    'places would be ommited when DataLoader is not iterable'
                )
Z
Zeng Jinle 已提交
1578 1579 1580 1581
        return self


class PyReader(DataLoaderBase):
1582
    r"""
1583
    Create a reader object for data feeding in Python.
Z
Zeng Jinle 已提交
1584
    Data would be prefetched using Python thread and be pushed
1585
    into a queue asynchronously. Data in the queue would be extracted
Z
Zeng Jinle 已提交
1586 1587
    automatically when `Executor.run(...)` is called.

1588
    Args:
Z
Zeng Jinle 已提交
1589
        feed_list (list(Variable)|tuple(Variable)): feed variable list.
G
GGBond8488 已提交
1590
            The variables should be created by :code:`paddle.static.data()`.
Z
Zeng Jinle 已提交
1591
        capacity (int): capacity of the queue maintained in PyReader.
1592 1593 1594 1595 1596
            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
Z
Zeng Jinle 已提交
1597
            and occupies a little more CPU or GPU memory, i.e., the memory
1598 1599 1600 1601 1602 1603 1604
            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
            the name of each fed variables. If return_list=True, the
Z
Zeng Jinle 已提交
1605 1606
            return value on each device would be a list(LoDTensor). It is
            recommended to use return_list=False in static graph mode and
1607
            use return_list=True in dygraph mode.
Z
Zeng Jinle 已提交
1608 1609

    Returns:
G
guofei 已提交
1610 1611 1612 1613
        the created reader object.

    Return type:
        reader(Reader)
Z
Zeng Jinle 已提交
1614 1615 1616

    Examples:
        1. If iterable = False, the created PyReader object is almost the
1617 1618
           same as :code:`fluid.layers.py_reader()`. Operators would be
           inserted into the program. User should call :code:`start()`
Z
Zeng Jinle 已提交
1619
           before each epoch and catch :code:`fluid.core.EOFException`
1620 1621
           thrown by :code:`Executor.run()` when epoch ends. Once the
           exception is caught, user should call :code:`reset()` to reset
Z
Zeng Jinle 已提交
1622 1623 1624 1625 1626 1627 1628 1629
           the reader manually.

        .. code-block:: python

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

1630 1631
           paddle.enable_static()

Z
Zeng Jinle 已提交
1632 1633 1634
           EPOCH_NUM = 3
           ITER_NUM = 5
           BATCH_SIZE = 3
1635

G
guofei 已提交
1636 1637
           def network(image, label):
               # User-defined network, here is an example of softmax regression.
C
Charles-hit 已提交
1638
               predict = paddle.static.nn.fc(x=image, size=10, activation='softmax')
1639 1640 1641 1642
               return paddle.nn.functional.cross_entropy(
                    input=predict, label=label,
                    reduction='none', use_softmax=False
               )
Z
Zeng Jinle 已提交
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653

           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 已提交
1654 1655
           image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
           label = fluid.data(name='label', shape=[None, 1], dtype='int64')
Z
Zeng Jinle 已提交
1656 1657 1658 1659 1660 1661 1662 1663

           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 已提交
1664 1665
           loss = network(image, label)
           executor = fluid.Executor(fluid.CPUPlace())
Z
Zeng Jinle 已提交
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
           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

1676

Z
Zeng Jinle 已提交
1677
        2. If iterable=True, the created PyReader object is decoupled with
1678 1679 1680 1681
           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=...)`.
Z
Zeng Jinle 已提交
1682 1683 1684 1685 1686 1687 1688

        .. code-block:: python

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

1689 1690
           paddle.enable_static()

Z
Zeng Jinle 已提交
1691 1692 1693 1694
           EPOCH_NUM = 3
           ITER_NUM = 5
           BATCH_SIZE = 10

G
guofei 已提交
1695 1696
           def network(image, label):
               # User-defined network, here is an example of softmax regression.
C
Charles-hit 已提交
1697
               predict = paddle.static.nn.fc(x=image, size=10, activation='softmax')
1698 1699 1700 1701
               return paddle.nn.functional.cross_entropy(
                   input=predict, label=label,
                   reduction='none', use_softmax=False
               )
G
guofei 已提交
1702

Z
Zeng Jinle 已提交
1703 1704 1705
           def reader_creator_random_image(height, width):
               def reader():
                   for i in range(ITER_NUM):
G
guofei 已提交
1706 1707
                       fake_image = np.random.uniform(low=0, high=255, size=[height, width])
                       fake_label = np.ones([1])
1708
                       yield fake_image, fake_label
Z
Zeng Jinle 已提交
1709 1710
               return reader

G
guofei 已提交
1711 1712 1713
           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 已提交
1714 1715 1716 1717

           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 已提交
1718
                   fluid.core.CPUPlace())
1719

G
guofei 已提交
1720 1721 1722
           loss = network(image, label)
           executor = fluid.Executor(fluid.CPUPlace())
           executor.run(fluid.default_startup_program())
1723

Z
Zeng Jinle 已提交
1724 1725
           for _ in range(EPOCH_NUM):
               for data in reader():
G
guofei 已提交
1726
                   executor.run(feed=data, fetch_list=[loss])
Z
Zeng Jinle 已提交
1727 1728


1729
        3. If return_list=True, the return values would be presented as list instead of dict.
Z
Zeng Jinle 已提交
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
           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():
1756
                   relu = paddle.nn.functional.relu(image)
Z
Zeng Jinle 已提交
1757 1758
    """

1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
    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
        )
Z
Zeng Jinle 已提交
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783

    @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 已提交
1784 1785

    def start(self):
S
add doc  
sneaxiy 已提交
1786
        '''
1787 1788 1789
        Start the data feeding thread.
        Can only call when the reader object is not iterable.

1790 1791
        Example:
            .. code-block:: python
1792

H
Huihuang Zheng 已提交
1793 1794 1795 1796
                import paddle
                import paddle.fluid as fluid
                import numpy as np

1797 1798 1799 1800 1801 1802
                BATCH_SIZE = 10

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

G
guofei 已提交
1803
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
1804 1805 1806 1807
                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 已提交
1808
                executor = fluid.Executor(fluid.CPUPlace())
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
                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

1819
        '''
Z
Zeng Jinle 已提交
1820
        self._loader.start()
S
sneaxiy 已提交
1821

S
sneaxiy 已提交
1822
    def reset(self):
S
add doc  
sneaxiy 已提交
1823
        '''
1824
        Reset the reader object when :code:`fluid.core.EOFException` raises.
S
add doc  
sneaxiy 已提交
1825
        Can only call when the reader object is not iterable.
1826

1827 1828 1829
        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
1830 1831 1832 1833
                import paddle
                import paddle.fluid as fluid
                import numpy as np

1834 1835 1836 1837 1838 1839
                BATCH_SIZE = 10

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

G
guofei 已提交
1840
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
1841 1842 1843 1844
                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 已提交
1845
                executor = fluid.Executor(fluid.CPUPlace())
1846 1847 1848 1849 1850 1851 1852 1853
                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()
1854
                            break
1855

S
add doc  
sneaxiy 已提交
1856
        '''
Z
Zeng Jinle 已提交
1857
        self._loader.reset()
S
sneaxiy 已提交
1858

1859 1860 1861
    def decorate_sample_generator(
        self, sample_generator, batch_size, drop_last=True, places=None
    ):
S
sneaxiy 已提交
1862 1863
        '''
        Set the data source of the PyReader object.
1864

S
sneaxiy 已提交
1865
        The provided :code:`sample_generator` should be a Python generator,
1866
        which yields list(numpy.ndarray)-typed data of each sample.
S
sneaxiy 已提交
1867 1868 1869

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

1870
        If all inputs have no lods, this method is faster than
S
sneaxiy 已提交
1871
        :code:`decorate_sample_list_generator(paddle.batch(sample_generator, ...))` .
S
sneaxiy 已提交
1872 1873 1874

        Args:
            sample_generator (generator): Python generator that yields
1875
                list(numpy.ndarray)-typed sample data.
S
sneaxiy 已提交
1876 1877
            batch_size (int): batch size. Must be larger than 0.
            drop_last (bool): Whether to drop the last batch when sample number
1878
                is less than batch_size.
S
sneaxiy 已提交
1879 1880
            places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
                be provided when PyReader is iterable.
1881 1882 1883 1884

        Example:
            .. code-block:: python

C
Charles-hit 已提交
1885
                import paddle
H
Huihuang Zheng 已提交
1886 1887 1888
                import paddle.fluid as fluid
                import numpy as np

1889 1890 1891
                EPOCH_NUM = 3
                ITER_NUM = 15
                BATCH_SIZE = 3
1892

G
guofei 已提交
1893 1894
                def network(image, label):
                    # User-defined network, here is an example of softmax regression.
C
Charles-hit 已提交
1895
                    predict = paddle.static.nn.fc(x=image, size=10, activation='softmax')
1896 1897 1898 1899
                    return paddle.nn.functional.cross_entropy(
                        input=predict, label=label,
                        reduction='none', use_softmax=False
                    )
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910

                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 已提交
1911 1912
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
                label = fluid.data(name='label', shape=[None, 1], dtype='int64')
1913 1914 1915 1916 1917
                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 已提交
1918 1919 1920 1921
                                                 places=[fluid.CPUPlace()])
                loss = network(image, label)
                executor = fluid.Executor(fluid.CPUPlace())
                executor.run(fluid.default_startup_program())
1922 1923 1924

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

S
sneaxiy 已提交
1927
        '''
1928 1929 1930
        self._loader.set_sample_generator(
            sample_generator, batch_size, drop_last, places
        )
S
sneaxiy 已提交
1931

S
sneaxiy 已提交
1932
    def decorate_sample_list_generator(self, reader, places=None):
S
add doc  
sneaxiy 已提交
1933
        '''
1934
        Set the data source of the PyReader object.
S
add doc  
sneaxiy 已提交
1935 1936

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

S
add doc  
sneaxiy 已提交
1939 1940 1941
        :code:`places` must be set when the PyReader object is iterable.

        Args:
1942 1943
            reader (generator): Python generator that yields
                list(numpy.ndarray)-typed batched data.
S
sneaxiy 已提交
1944 1945
            places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
                be provided when PyReader is iterable.
1946

1947 1948 1949
        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
1950 1951 1952 1953
                import paddle
                import paddle.fluid as fluid
                import numpy as np

1954 1955
                paddle.enable_static()

1956 1957 1958 1959
                EPOCH_NUM = 3
                ITER_NUM = 15
                BATCH_SIZE = 3

G
guofei 已提交
1960 1961
                def network(image, label):
                    # User-defined network, here is an example of softmax regression.
C
Charles-hit 已提交
1962
                    predict = paddle.static.nn.fc(x=image, size=10, activation='softmax')
1963 1964 1965 1966
                    return paddle.nn.functional.cross_entropy(
                        input=predict, label=label,
                        reduction='none', use_softmax=False
                    )
G
guofei 已提交
1967

1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
                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 已提交
1978 1979
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
                label = fluid.data(name='label', shape=[None, 1], dtype='int64')
1980 1981 1982 1983 1984
                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 已提交
1985
                    fluid.core.CPUPlace())
1986

G
guofei 已提交
1987 1988 1989
                loss = network(image, label)
                executor = fluid.Executor(fluid.core.CPUPlace())
                executor.run(fluid.default_startup_program())
1990 1991 1992

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

S
add doc  
sneaxiy 已提交
1995
        '''
Z
Zeng Jinle 已提交
1996
        self._loader.set_sample_list_generator(reader, places)
S
sneaxiy 已提交
1997

S
sneaxiy 已提交
1998
    def decorate_batch_generator(self, reader, places=None):
S
add doc  
sneaxiy 已提交
1999 2000 2001 2002
        '''
        Set the data source of the PyReader object.

        The provided :code:`reader` should be a Python generator,
S
sneaxiy 已提交
2003
        which yields numpy.ndarray-typed or LoDTensor-typed batched data.
S
add doc  
sneaxiy 已提交
2004 2005 2006 2007 2008 2009

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

        Args:
            reader (generator): Python generator that yields LoDTensor-typed
                batched data.
S
sneaxiy 已提交
2010
            places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
S
sneaxiy 已提交
2011
                be provided when PyReader is iterable.
2012 2013 2014 2015

        Example:
            .. code-block:: python

2016
                import paddle
H
Huihuang Zheng 已提交
2017 2018 2019
                import paddle.fluid as fluid
                import numpy as np

2020 2021
                paddle.enable_static()

2022 2023 2024
                EPOCH_NUM = 3
                ITER_NUM = 15
                BATCH_SIZE = 3
2025

G
guofei 已提交
2026 2027
                def network(image, label):
                    # User-defined network, here is an example of softmax regression.
C
Charles-hit 已提交
2028
                    predict = paddle.static.nn.fc(x=image, size=10, activation='softmax')
2029 2030 2031 2032
                    return paddle.nn.functional.cross_entropy(
                        input=predict, label=label,
                        reduction='none', use_softmax=False
                    )
2033 2034 2035 2036 2037 2038 2039 2040

                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 已提交
2041 2042
                            batch_image = batch_image.astype('float32')
                            batch_label = batch_label.astype('int64')
2043 2044 2045
                            yield batch_image, batch_label
                    return generator

G
guofei 已提交
2046 2047
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
                label = fluid.data(name='label', shape=[None, 1], dtype='int64')
2048 2049 2050
                reader = fluid.io.PyReader(feed_list=[image, label], capacity=4, iterable=True)

                user_defined_generator = random_image_and_label_generator(784, 784)
G
guofei 已提交
2051
                reader.decorate_batch_generator(user_defined_generator, fluid.CPUPlace())
2052

G
guofei 已提交
2053 2054 2055
                loss = network(image, label)
                executor = fluid.Executor(fluid.CPUPlace())
                executor.run(fluid.default_startup_program())
2056 2057 2058

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

S
add doc  
sneaxiy 已提交
2061
        '''
Z
Zeng Jinle 已提交
2062 2063 2064 2065 2066
        self._loader.set_batch_generator(reader, places)


class DatasetLoader(DataLoaderBase):
    def __init__(self, dataset, places, drop_last):
2067 2068 2069 2070 2071
        assert isinstance(
            dataset, paddle.distributed.fleet.dataset.DatasetBase
        ), "dataset must be type of DatasetBase"
        assert (
            not _non_static_mode()
Z
Zeng Jinle 已提交
2072
        ), "DatasetLoader is not supported in dygraph mode yet"
2073 2074 2075 2076
        if isinstance(places, (list, tuple)):
            places = _get_paddle_place_list(places)
        else:
            places = _get_paddle_place(places)
Z
Zeng Jinle 已提交
2077 2078 2079

        thread_num = len(places)

2080 2081 2082 2083 2084
        assert (
            len(dataset.filelist) >= thread_num
        ), "Filelist number of dataset {} must be not less than place number {}".format(
            len(dataset.filelist), thread_num
        )
Z
Zeng Jinle 已提交
2085 2086

        if dataset.thread_num != 0 and dataset.thread_num != thread_num:
2087 2088
            logging.warn(
                'thread_num {} which is set in Dataset is ignored'.format(
2089 2090 2091
                    dataset.thread_num
                )
            )
Z
Zeng Jinle 已提交
2092

2093
        dataset._set_thread(thread_num)
Z
Zeng Jinle 已提交
2094

2095 2096 2097 2098 2099 2100
        if (
            isinstance(
                dataset, paddle.distributed.fleet.dataset.InMemoryDataset
            )
            and dataset.queue_num > thread_num
        ):
2101 2102
            logging.warn(
                "queue_num {} which is set in Dataset is ignored".format(
2103 2104 2105
                    dataset.queue_num
                )
            )
2106
            dataset._set_queue_num(thread_num)
Z
Zeng Jinle 已提交
2107 2108 2109

        self._dataset = dataset
        use_slots = [
2110 2111
            slot.name
            for slot in dataset.proto_desc.multi_slot_desc.slots
Z
Zeng Jinle 已提交
2112 2113 2114 2115
            if slot.is_used
        ]

        self._iterable_dataset = core.IterableDatasetWrapper(
2116 2117 2118 2119 2120 2121
            dataset.dataset,
            use_slots,
            _convert_places(places),
            dataset.proto_desc.batch_size,
            drop_last,
        )
Z
Zeng Jinle 已提交
2122 2123 2124 2125 2126 2127 2128 2129 2130

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