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

15
from . import core
16
import sys
S
sneaxiy 已提交
17
import six
18
import numpy as np
S
sneaxiy 已提交
19
import threading
20
import paddle
Z
Zeng Jinle 已提交
21
from .framework import Program, Variable, program_guard, default_main_program, default_startup_program, in_dygraph_mode, cpu_places
S
sneaxiy 已提交
22
from .executor import global_scope
23
from .data_feeder import DataFeeder, BatchedTensorProvider
S
sneaxiy 已提交
24
from .layers.io import monkey_patch_reader_methods, _copy_reader_var_, double_buffer
S
sneaxiy 已提交
25
from .unique_name import UniqueNameGenerator
26
import logging
Z
Zeng Jinle 已提交
27
from .dataset import DatasetBase, InMemoryDataset
S
sneaxiy 已提交
28

29 30 31 32 33 34 35 36 37 38 39
### Dygraph DataLoader configs ###
import multiprocessing
import signal
# NOTE: queue has a different name in python2 and python3
if sys.version_info[0] == 2:
    import Queue as queue
else:
    import queue
# NOTE: [ avoid hanging ] This value is used in getting data from another process
MP_CHECK_TIMEOUT = 10

Z
Zeng Jinle 已提交
40 41 42
__all__ = ['PyReader', 'DataLoader']

data_loader_unique_name_generator = UniqueNameGenerator()
S
sneaxiy 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59


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


Z
Zeng Jinle 已提交
60 61 62
class DataLoaderBase(object):
    def __init__(self):
        self._places = None
S
sneaxiy 已提交
63

Z
Zeng Jinle 已提交
64 65
    def __call__(self):
        return self
S
sneaxiy 已提交
66

Z
Zeng Jinle 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    def next(self):
        '''
        Get the next item in the DataLoader object. This method    
        should not be called by users directly. It is used for
        implementing iterator protocol of Python 2.x inside
        PaddlePaddle framework.
        '''
        return self.__next__()

    def __iter__(self):
        raise NotImplementedError()

    def __next__(self):
        raise NotImplementedError()


class DataLoader(object):
    @staticmethod
    def from_generator(feed_list=None,
                       capacity=None,
                       use_double_buffer=True,
                       iterable=True,
89
                       return_list=False,
90
                       use_multiprocess=False,
91
                       drop_last=True,
S
sneaxiy 已提交
92
                       keep_order=False):
Z
Zeng Jinle 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
        """
        Create a DataLoader object for loading data from Python generator. 
        Data would be prefetched using Python thread and be pushed
        into a queue asynchronously.

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

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

        If iterable = False, the created DataLoader object provides 
        :code:`start()` and :code:`reset()` method to control the data reading
        process. This mode is designed to be compatible with the 
        :code:`fluid.layers.py_reader` interface. Users can migrate the codes   
        from :code:`fluid.layers.py_reader` to :code:`fluid.io.DataLoader` 
        easily when using iterable=False. 

        Args:  
            feed_list (list(Variable)|tuple(Variable)): feed variable list.
115
                The variables should be created by :code:`fluid.data()`.
Z
Zeng Jinle 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
            capacity (int): capacity of the queue maintained in DataLoader.
                The unit is batch number. Set larger capacity if your reader 
                is fast. 
            use_double_buffer (bool): whether to use double_buffer_reader. 
                If use_double_buffer=True, the DataLoader would prefetch next 
                batch data asynchronously, so it would speed up data feeding 
                and occupies a little more CPU or GPU memory, i.e., the memory
                of one batch input data. 
            iterable (bool): whether the created DataLoader is iterable. 
            return_list (bool): whether the return value on each device is 
                presented as a list. It is only valid when iterable=True. 
                If return_list=False, the return value on each device would 
                be a dict of str -> LoDTensor, where the key of the dict is 
                the name of each feeded variables. If return_list=True, the 
                return value on each device would be a list(LoDTensor). It is
                recommended to use return_list=False in static graph mode and
132 133 134 135 136 137
                use return_list=True in dygraph mode.  
            use_multiprocess (bool): whether to use multi-process to speed up
                the data loading process in dygraph. Note: this parameter only
                can be used in the dygraph mode. In the static graph mode,
                whether this parameter is set or not has no effect.
                The Default value is False.
138 139 140
            drop_last (bool): whether to drop the last batches whose number is
                less than the CPU core/GPU card number. The default value is 
                True.
141 142 143 144 145 146 147 148 149
            keep_order (bool): whether to assign the data to CPU cores or GPU 
                cards in order. Supposing that there are 2 batches and we use 
                2 GPU cards to run the network. If keep_order=True, GPU 0 would 
                get batch 0 and GPU 1 would get batch 1 exactly. If 
                keep_order=False, GPU 0 may get batch 0 or may get batch 1, and 
                GPU 1 may get the rest of the data, which is uncertain. If 
                keep_order=True, the framework may do some synchronization to 
                keep the reading order, which may be slower. The default value 
                is False.
Z
Zeng Jinle 已提交
150 151 152 153 154 155 156

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

        Examples:
            
            .. code-block:: python
S
sneaxiy 已提交
157

Z
Zeng Jinle 已提交
158 159
                import paddle.fluid as fluid
                import numpy as np
160

Z
Zeng Jinle 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
                BATCH_NUM = 10 
                BATCH_SIZE = 16
                EPOCH_NUM = 4

                CLASS_NUM = 10

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

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

                def simple_net(image, label):
                    fc_tmp = fluid.layers.fc(image, size=CLASS_NUM)
                    cross_entropy = fluid.layers.softmax_with_cross_entropy(image, label)
                    loss = fluid.layers.reduce_mean(cross_entropy)
                    sgd = fluid.optimizer.SGD(learning_rate=1e-3)
                    sgd.minimize(loss)
                    return loss

                def get_random_images_and_labels(image_shape, label_shape):
                    image = np.random.random(size=image_shape).astype('float32')
                    label = np.random.random(size=label_shape).astype('int64')
                    return image, label

                # If the data generator yields one sample each time,
                # use DataLoader.set_sample_generator to set the data source.
                def sample_generator_creator(): 
                    def __reader__():
                        for _ in range(BATCH_NUM * BATCH_SIZE):
                            image, label = get_random_images_and_labels([784], [1])
                            yield image, label

                    return __reader__

                # If the data generator yield list of samples each time,
                # use DataLoader.set_sample_list_generator to set the data source.
                def sample_list_generator_creator():
                    def __reader__():
                        for _ in range(BATCH_NUM): 
                            sample_list = []
                            for _ in range(BATCH_SIZE):
                                image, label = get_random_images_and_labels([784], [1])
                                sample_list.append([image, label])

                            yield sample_list

                    return __reader__ 

                # If the data generator yields a batch each time, 
                # use DataLoader.set_batch_generator to set the data source.
                def batch_generator_creator():
                    def __reader__():
                        for _ in range(BATCH_NUM):
                            batch_image, batch_label = get_random_images_and_labels([BATCH_SIZE, 784], [BATCH_SIZE, 1]) 
                            yield batch_image, batch_label
H
Huihuang Zheng 已提交
216

Z
Zeng Jinle 已提交
217
                    return __reader__
218

Z
Zeng Jinle 已提交
219 220 221 222 223
                # If DataLoader is iterable, use for loop to train the network 
                def train_iterable(exe, prog, loss, loader):
                    for _ in range(EPOCH_NUM):
                        for data in loader():
                            exe.run(prog, feed=data, fetch_list=[loss])
224

Z
Zeng Jinle 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
                # If DataLoader is not iterable, use start() and reset() method to control the process 
                def train_non_iterable(exe, prog, loss, loader):
                    for _ in range(EPOCH_NUM):
                        loader.start() # call DataLoader.start() before each epoch starts
                        try:
                            while True:
                                exe.run(prog, fetch_list=[loss])
                        except fluid.core.EOFException:
                            loader.reset() # call DataLoader.reset() after catching EOFException 

                def set_data_source(loader, places):
                    if DATA_FORMAT == 'sample_generator':
                        loader.set_sample_generator(sample_generator_creator(), batch_size=BATCH_SIZE, drop_last=True, places=places)
                    elif DATA_FORMAT == 'sample_list_generator':
                        loader.set_sample_list_generator(sample_list_generator_creator(), places=places)
                    elif DATA_FORMAT == 'batch_generator':
                        loader.set_batch_generator(batch_generator_creator(), places=places)
                    else:
                        raise ValueError('Unsupported data format')
244

245 246
                image = fluid.data(name='image', shape=[None, 784], dtype='float32')
                label = fluid.data(name='label', shape=[None, 1], dtype='int64')
247

Z
Zeng Jinle 已提交
248 249
                # Define DataLoader 
                loader = fluid.io.DataLoader.from_generator(feed_list=[image, label], capacity=16, iterable=ITERABLE)
250

Z
Zeng Jinle 已提交
251 252
                # Define network
                loss = simple_net(image, label)
S
sneaxiy 已提交
253

Z
Zeng Jinle 已提交
254 255 256 257 258 259 260 261 262
                # Set data source of DataLoader
                #
                # If DataLoader is iterable, places must be given and the number of places must be the same with device number.  
                #  - If you are using GPU, call `fluid.cuda_places()` to get all GPU places. 
                #  - If you are using CPU, call `fluid.cpu_places()` to get all CPU places. 
                # 
                # If DataLoader is not iterable, places can be None.
                places = fluid.cuda_places() if USE_GPU else fluid.cpu_places()
                set_data_source(loader, places)
S
sneaxiy 已提交
263

Z
Zeng Jinle 已提交
264 265
                exe = fluid.Executor(places[0])
                exe.run(fluid.default_startup_program())
H
Huihuang Zheng 已提交
266

Z
Zeng Jinle 已提交
267
                prog = fluid.CompiledProgram(fluid.default_main_program()).with_data_parallel(loss_name=loss.name)
268

Z
Zeng Jinle 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
                if loader.iterable:
                    train_iterable(exe, prog, loss, loader)
                else:
                    train_non_iterable(exe, prog, loss, loader)


                '''
                Users can use return_list = True in dygraph mode. 
                '''
                with fluid.dygraph.guard(places[0]):
                    loader = fluid.io.DataLoader.from_generator(capacity=2, return_list=True)
                    set_data_source(loader, places[0]) 
                    for image, label in loader():
                        relu = fluid.layers.relu(image)
                        assert image.shape == [BATCH_SIZE, 784] 
                        assert label.shape == [BATCH_SIZE, 1]
                        assert relu.shape == [BATCH_SIZE, 784]
        """
287
        if in_dygraph_mode():
288 289 290
            # Dygraph only support multiprocess training when using multi GPUs. 
            # So in each process, we only use 1 GPU card to train the network, 
            # so `keep_order` would also be True.
291 292 293 294 295
            return DygraphGeneratorLoader(feed_list, capacity,
                                          use_double_buffer, iterable,
                                          return_list, use_multiprocess)
        else:
            return GeneratorLoader(feed_list, capacity, use_double_buffer,
296
                                   iterable, return_list, drop_last, keep_order)
Z
Zeng Jinle 已提交
297 298 299 300 301 302

    @staticmethod
    def from_dataset(dataset, places, drop_last=True):
        """
        Create an iterable DataLoader object for loading data from Dataset.    
        Dataset is only supported in Linux system currently.
303

Z
Zeng Jinle 已提交
304 305 306 307 308 309 310
        Args:
            dataset (InMemoryDataset|QueueDataset): the dataset object.
            places (list(CUDAPlace)|list(CPUPlace)): places where the result 
                data should be converted.   
            drop_last (bool): whether to drop the last batch whose sample 
                number is less than batch size. If drop_last = True, they
                would be dropped. If drop_last = False, they would be kept. 
311

Z
Zeng Jinle 已提交
312 313 314
        Returns:
            loader (DataLoader): the created DataLoader object, which can be 
                treated as a Python generator.   
315

Z
Zeng Jinle 已提交
316 317 318
        Examples:

            .. code-block:: python
319

Z
Zeng Jinle 已提交
320
                import paddle.fluid as fluid
321

322 323
                image = fluid.data(name='image', shape=[None, 784], dtype='float32')
                label = fluid.data(name='label', shape=[None, 1], dtype='int64')
324

Z
Zeng Jinle 已提交
325 326 327 328 329
                dataset = fluid.DatasetFactory().create_dataset("QueueDataset")
                dataset.set_batch_size(32)
                dataset.set_filelist(['a.txt', 'b.txt', 'c.txt'])
                dataset.set_use_var([image, label])
                dataset.set_pipe_command('cat') 
330

Z
Zeng Jinle 已提交
331 332 333
                loader = fluid.io.DataLoader.from_dataset(dataset, fluid.cpu_places())
        """
        return DatasetLoader(dataset, places, drop_last)
S
sneaxiy 已提交
334

S
sneaxiy 已提交
335

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
class DygraphGeneratorLoader(DataLoaderBase):
    """
    The GeneratorLoader of dygraph

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

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

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

        if not iterable:
            logging.warning(
                "Please NOTE: dygraph can support iterable mode only. Change to iterable mode."
            )
        self._iterable = True
        if not return_list:
            logging.warning(
                "Please NOTE: dygraph can support return as list only. Change to return as list."
            )
        self._return_list = True

        # NOTE: the multiprocessing in different platform is incompatible, we will solve it later
        self._use_multiprocess = use_multiprocess
        if self._use_multiprocess and (sys.platform == 'darwin' or
                                       sys.platform == 'win32'):
            logging.warning(
                "NOTE: The multiprocess mode does not currently support MacOs and Windows."
            )
            self._use_multiprocess = False

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

        # NOTE: the C++ LoDTensorBlockingQueue instance
        self._blocking_queue = None
        # NOTE: 1. In multiprocess mode, this thread is used to get next batch data from
        # self._data_queue, then push it into self._blocking_queue; 2. In singleprocess
        # mode, this thread is used to get next batch data from self._batch_reader, then 
        # push it into self._blocking_queue
        self._thread = None

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

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

    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:
            self._data_queue.cancel_join_thread()
            self._data_queue.close()
            process.join()
            # erase process id
            core._erase_process_pid(id(self))

    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(
426
            core.Variable(), self._capacity, False)
427 428
        self._reader = core.create_py_reader(
            self.queue, self._var_names, self._shapes, self._dtypes,
429
            self._need_check_feed, self._places, self._use_double_buffer, True)
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627

    def _start(self):
        if self._use_multiprocess:
            # Set data_queue and process
            self._data_queue = multiprocessing.Queue(self._capacity)
            self._process = multiprocessing.Process(
                target=self._reader_process_loop)
            self._process.daemon = True
            self._process.start()

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

            # Set reader_thread
            self._thread_done_event = threading.Event()
            self._thread = threading.Thread(
                target=self._reader_thread_loop_with_process)
            self._thread.daemon = True
            self._thread.start()
        else:
            self._thread = threading.Thread(target=self._reader_thread_loop)
            self._thread.daemon = True
            self._thread.start()

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

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

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

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

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

    def _set_child_signal_handler(self):
        core._set_process_pid(id(self), self._process.pid)
        current_handler = signal.getsignal(signal.SIGCHLD)
        if not callable(current_handler):
            current_handler = None

        def __handler__(signum, frame):
            core._throw_error_if_process_failed()
            if current_handler is not None:
                current_handler(signum, frame)

        signal.signal(signal.SIGCHLD, __handler__)

    def _reader_process_loop(self):
        try:
            # set signal handler
            core._set_process_signal_handler()

            for sample in self._batch_reader():
                if sample is None:
                    raise ValueError(
                        "Sample in reader is None. Please check whether your dataset is valid."
                    )
                self._data_queue.put(sample)
            self._data_queue.put(None)
        except KeyboardInterrupt:
            # NOTE: Main process will raise KeyboardInterrupt anyways, ignore it in child process
            pass
        except:
            self._data_queue.cancel_join_thread()
            self._data_queue.close()
            six.reraise(*sys.exc_info())

    def _reader_thread_loop_with_process(self):
        while not self._thread_done_event.is_set():
            try:
                # NOTE: [ avoid hanging ] Even with carefully designed data dependencies 
                # (i.e., a put() always corresponding to a get()), hanging on get() can 
                # still happen when data in queue is corrupted (e.g., due to 
                # Queue.cancel_join_thread or unexpected exit). So we set a timeout whenever 
                # we try to get data from `data_queue`
                sample = self._data_queue.get(timeout=MP_CHECK_TIMEOUT)
            except queue.Empty:
                self._thread_done_event.set()
                logging.error("The reader has not read data for a long time.")

            if not self._thread_done_event.is_set():
                if sample is not None:
                    try:
                        array = core.LoDTensorArray()
                        for item in sample:
                            if not isinstance(item, core.LoDTensor):
                                self._check_input_array(item)
                                tmp = core.LoDTensor()
                                tmp.set(item, core.CPUPlace())
                                item = tmp
                            array.append(item)
                        if not self._blocking_queue.push(array):
                            self._blocking_queue.close()
                    except:
                        self._thread_done_event.set()
                        self._blocking_queue.kill()
                        self._data_queue.close()
                        logging.warning(
                            "DygraphDataLoader reader thread raised an exception."
                        )
                        six.reraise(*sys.exc_info())
                else:
                    self._thread_done_event.set()
                    self._blocking_queue.close()
                    self._data_queue.close()
            else:
                self._blocking_queue.kill()
                self._data_queue.close()

    def _reader_thread_loop(self):
        try:
            for sample in self._batch_reader():
                array = core.LoDTensorArray()
                for item in sample:
                    if not isinstance(item, core.LoDTensor):
                        self._check_input_array(item)
                        tmp = core.LoDTensor()
                        tmp.set(item, core.CPUPlace())
                        item = tmp

                    array.append(item)

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

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

    def set_sample_generator(self,
                             reader,
                             batch_size,
                             drop_last=True,
                             places=None):
        assert batch_size > 0, "batch_size must be larger than 0"
        self.set_sample_list_generator(
            paddle.batch(
                reader, batch_size=batch_size, drop_last=drop_last),
            places=places)
        return self

    def set_sample_list_generator(self, reader, places=None):
        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):
        self._batch_reader = reader
        assert places is not None, "Places cannot be None when DataLoader is iterable"
        self._places = _convert_places(places)
        assert len(self._places) == 1, \
            "Number of places must be 1 in dygraph mode"
        return self


Z
Zeng Jinle 已提交
628
class GeneratorLoader(DataLoaderBase):
S
sneaxiy 已提交
629
    def __init__(self,
630 631
                 feed_list=None,
                 capacity=None,
S
sneaxiy 已提交
632
                 use_double_buffer=True,
633
                 iterable=True,
634
                 return_list=False,
635
                 drop_last=True,
S
sneaxiy 已提交
636
                 keep_order=False):
S
sneaxiy 已提交
637
        self._tensor_reader = None
Z
Zeng Jinle 已提交
638
        self._places = None
S
sneaxiy 已提交
639
        self._thread = None
640
        self._queue = None
641
        self._feed_list = feed_list
642
        self._exited = False
643 644
        self._drop_last = drop_last
        self._keep_order = keep_order
645 646
        if not capacity:
            raise ValueError("Please give value to capacity.")
647 648 649 650
        self._iterable = iterable
        self._return_list = return_list
        if not self._feed_list:
            raise Exception("Feed list must be given under static mode.")
S
sneaxiy 已提交
651 652 653 654
        self._use_double_buffer = use_double_buffer
        self._capacity = capacity
        if not self._iterable:
            self._init_non_iterable()
S
sneaxiy 已提交
655

Z
Zeng Jinle 已提交
656
    def _wait_thread_ends(self):
657
        # Get self._thread first to prevent data race, because __thread_main__
Z
Zeng Jinle 已提交
658 659 660 661 662 663 664 665
        # 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()
666 667 668 669 670 671
        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
        ]
672 673
        self._queue = core.init_lod_tensor_blocking_queue(
            core.Variable(), self._capacity, self._keep_order)
S
sneaxiy 已提交
674
        self._reader = core.create_py_reader(
675
            self.queue, self._var_names, self._shapes, self._dtypes,
676 677
            self._need_check_feed, self._places, self._use_double_buffer,
            self._drop_last)
S
sneaxiy 已提交
678 679 680 681 682 683 684

    def _init_non_iterable(self):
        lod_levels = []
        dtypes = []
        shape_concat = []
        ranks = []
        shapes = []
685
        need_check_feed = []
S
sneaxiy 已提交
686 687 688 689 690 691 692

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

Z
Zeng Jinle 已提交
695 696 697 698
        queue_name = data_loader_unique_name_generator(
            'lod_tensor_blocking_queue')
        reader_name = data_loader_unique_name_generator('create_py_reader')
        double_buffer_name = data_loader_unique_name_generator('double_buffer')
S
sneaxiy 已提交
699

S
sneaxiy 已提交
700
        var = global_scope().var(queue_name)
701 702
        self._queue = core.init_lod_tensor_blocking_queue(var, self._capacity,
                                                          self._keep_order)
S
sneaxiy 已提交
703

704 705 706 707 708 709
        if self._keep_order:
            block = default_main_program().current_block()
        else:
            block = default_startup_program().current_block()

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

711
        dtype_int = [int(t) for t in dtypes]
712
        block.append_op(
S
sneaxiy 已提交
713 714
            type='create_py_reader',
            inputs={'blocking_queue': [queue_name]},
715
            outputs={'Out': [reader_var]},
S
sneaxiy 已提交
716 717 718
            attrs={
                'shape_concat': shape_concat,
                'lod_levels': lod_levels,
719 720
                'dtypes': dtype_int,
                'need_check_feed': need_check_feed,
S
sneaxiy 已提交
721 722 723
                'ranks': ranks
            })

724 725 726 727 728 729 730 731 732 733 734
        reader_var.desc.set_dtypes(dtypes)
        reader_var.persistable = True
        reader_var.stop_gradient = True

        if self._keep_order:
            main_prog_var = reader_var
            reader = main_prog_var
            reader.reset = self._queue.reset
        else:
            main_prog_var = _copy_reader_var_(
                default_main_program().current_block(), reader_var)
S
sneaxiy 已提交
735

736 737
            main_prog_var.stop_gradient = True
            main_prog_var.persistable = True
S
sneaxiy 已提交
738

739
            reader = monkey_patch_reader_methods(main_prog_var)
S
sneaxiy 已提交
740 741 742 743 744 745 746 747 748 749 750 751 752 753

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

        self._reader = reader

        default_main_program().current_block().append_op(
            type='read',
            inputs={'Reader': [self._reader]},
754 755
            outputs={'Out': self._feed_list},
            attrs={'drop_last': self._drop_last})
S
sneaxiy 已提交
756 757 758 759 760 761 762 763

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

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

Z
Zeng Jinle 已提交
765 766
    def __iter__(self):
        assert self.iterable, "DataLoader is not iterable"
S
sneaxiy 已提交
767
        assert self._tensor_reader is not None, \
Z
Zeng Jinle 已提交
768
            "Data source of DataLoader has not set yet"
S
sneaxiy 已提交
769

Z
Zeng Jinle 已提交
770
        self._init_iterable()
S
sneaxiy 已提交
771
        self._start()
Z
Zeng Jinle 已提交
772 773 774 775
        return self

    def __next__(self):
        try:
776 777
            if self._return_list:
                return self._reader.read_next_list()
778
            else:
779
                return self._reader.read_next()
Z
Zeng Jinle 已提交
780 781 782 783 784 785
        except StopIteration:
            self._queue.close()
            self._reset()
            six.reraise(*sys.exc_info())

    def start(self):
786 787
        assert not self._iterable, "start() cannot be called when DataLoader is iterable"
        self._start()
Z
Zeng Jinle 已提交
788 789

    def reset(self):
790 791
        assert not self._iterable, "reset() cannot be called when DataLoader is iterable"
        self._reset()
Z
Zeng Jinle 已提交
792

793 794 795 796 797 798 799 800 801 802 803
    @classmethod
    def _check_input_array(cls, item):
        arr = np.array(item)
        if arr.dtype == np.object:
            raise TypeError((
                "\n\tFaild to convert input data to a regular ndarray :\n\t* Usually "
                "this means the input data contains nested lists with different lengths. "
                "\n\t* Check the reader function passed to 'decorate_batch_generator'"
                " to locate the data causes this issue.\n\t* Please consider using "
                "'fluid.create_lod_tensor' to convert it to a LoD-Tensor."))

804 805
        return arr

Z
Zeng Jinle 已提交
806 807 808
    def _start(self):
        def __thread_main__():
            try:
809 810 811
                while not self._queue.wait_for_inited(1):
                    if self._exited:
                        return
812

Z
Zeng Jinle 已提交
813 814 815 816
                for tensors in self._tensor_reader():
                    array = core.LoDTensorArray()
                    for item in tensors:
                        if not isinstance(item, core.LoDTensor):
817
                            item = self._check_input_array(item)
Z
Zeng Jinle 已提交
818 819 820 821 822 823 824 825 826 827 828 829
                            tmp = core.LoDTensor()
                            tmp.set(item, core.CPUPlace())
                            item = tmp

                        array.append(item)

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

                self._queue.close()
                self._thread = None
            except Exception as ex:
Z
Zeng Jinle 已提交
830
                self._queue.kill()
Z
Zeng Jinle 已提交
831 832 833 834 835 836 837
                self._thread = None
                logging.warn('Your reader has raised an exception!')
                six.reraise(*sys.exc_info())

        self._thread = threading.Thread(target=__thread_main__)
        self._thread.daemon = True
        self._thread.start()
S
sneaxiy 已提交
838

S
sneaxiy 已提交
839
    def _reset(self):
840
        self._queue.close()
841
        self._exited = True
Z
Zeng Jinle 已提交
842 843 844 845
        thread = self._thread
        if thread is not None:
            thread.join()

846
        self._exited = False
847 848
        self._reader.reset()

Z
Zeng Jinle 已提交
849 850 851 852 853 854
    def set_sample_generator(self,
                             reader,
                             batch_size,
                             drop_last=True,
                             places=None):
        assert batch_size > 0, "batch_size must be larger than 0"
855 856 857 858 859 860 861
        has_lod = False
        for f in self._feed_list:
            if f.lod_level != 0:
                has_lod = True
                break

        if has_lod:
862 863 864 865 866
            self.set_sample_list_generator(
                paddle.batch(
                    reader, batch_size=batch_size, drop_last=drop_last),
                places=places)
        else:
867 868 869 870 871 872 873
            reader = BatchedTensorProvider(
                feed_list=self._feed_list,
                place=core.CPUPlace(),
                batch_size=batch_size,
                generator=reader,
                drop_last=drop_last)
            self.set_batch_generator(reader, places=places)
Z
Zeng Jinle 已提交
874 875 876
        return self

    def set_sample_list_generator(self, reader, places=None):
877 878 879 880
        with program_guard(Program(), Program()):
            feeder = DataFeeder(
                feed_list=self._feed_list, place=core.CPUPlace())
            paddle_reader = feeder.decorate_reader(reader, multi_devices=False)
Z
Zeng Jinle 已提交
881

882 883 884
        def __tensor_reader_impl__():
            for slots in paddle_reader():
                yield [slots[var.name] for var in self._feed_list]
Z
Zeng Jinle 已提交
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929

        self.set_batch_generator(__tensor_reader_impl__, places)
        return self

    def set_batch_generator(self, reader, places=None):
        self._tensor_reader = reader
        if self._iterable:
            assert places is not None, "Places cannot be None when DataLoader is iterable"
            self._places = _convert_places(places)
        else:
            if places is not None:
                logging.info(
                    'places would be ommited when DataLoader is not iterable')
        return self


class PyReader(DataLoaderBase):
    """
    Create a reader object for data feeding in Python. 
    Data would be prefetched using Python thread and be pushed
    into a queue asynchronously. Data in the queue would be extracted 
    automatically when `Executor.run(...)` is called.

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

    Returns:
G
guofei 已提交
930 931 932 933
        the created reader object.

    Return type:
        reader(Reader)
Z
Zeng Jinle 已提交
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952

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

        .. code-block:: python

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

           EPOCH_NUM = 3
           ITER_NUM = 5
           BATCH_SIZE = 3
G
guofei 已提交
953 954 955 956 957
           
           def network(image, label):
               # User-defined network, here is an example of softmax regression.
               predict = fluid.layers.fc(input=image, size=10, act='softmax')           
               return fluid.layers.cross_entropy(input=predict, label=label)
Z
Zeng Jinle 已提交
958 959 960 961 962 963 964 965 966 967 968

           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 已提交
969 970
           image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
           label = fluid.data(name='label', shape=[None, 1], dtype='int64')
Z
Zeng Jinle 已提交
971 972 973 974 975 976 977 978

           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 已提交
979 980
           loss = network(image, label)
           executor = fluid.Executor(fluid.CPUPlace())
Z
Zeng Jinle 已提交
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
           executor.run(fluid.default_startup_program())
           for i in range(EPOCH_NUM):
               reader.start()
               while True:
                   try:
                       executor.run(feed=None)
                   except fluid.core.EOFException:
                       reader.reset()
                       break

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

        .. code-block:: python

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

           EPOCH_NUM = 3
           ITER_NUM = 5
           BATCH_SIZE = 10

G
guofei 已提交
1008 1009 1010 1011 1012
           def network(image, label):
               # User-defined network, here is an example of softmax regression.
               predict = fluid.layers.fc(input=image, size=10, act='softmax')           
               return fluid.layers.cross_entropy(input=predict, label=label)

Z
Zeng Jinle 已提交
1013 1014 1015
           def reader_creator_random_image(height, width):
               def reader():
                   for i in range(ITER_NUM):
G
guofei 已提交
1016 1017 1018
                       fake_image = np.random.uniform(low=0, high=255, size=[height, width])
                       fake_label = np.ones([1])
                       yield fake_image, fake_label 
Z
Zeng Jinle 已提交
1019 1020
               return reader

G
guofei 已提交
1021 1022 1023
           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 已提交
1024 1025 1026 1027

           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 已提交
1028 1029 1030 1031 1032 1033
                   fluid.core.CPUPlace())
           
           loss = network(image, label)
           executor = fluid.Executor(fluid.CPUPlace())
           executor.run(fluid.default_startup_program())
           
Z
Zeng Jinle 已提交
1034 1035
           for _ in range(EPOCH_NUM):
               for data in reader():
G
guofei 已提交
1036
                   executor.run(feed=data, fetch_list=[loss])
Z
Zeng Jinle 已提交
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090


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

        .. code-block:: python

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

           ITER_NUM = 5
           BATCH_SIZE = 10

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

           place = fluid.CPUPlace()
           with fluid.dygraph.guard(place):
               py_reader = fluid.io.PyReader(capacity=2, return_list=True)
               user_defined_reader = reader_creator_random_image(784, 784)
               py_reader.decorate_sample_list_generator(
                   paddle.batch(user_defined_reader, batch_size=BATCH_SIZE),
                   place)
               for image, label in py_reader():
                   relu = fluid.layers.relu(image)
    """

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

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

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

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

    def __next__(self):
        return self._loader.__next__()
S
sneaxiy 已提交
1091 1092

    def start(self):
S
add doc  
sneaxiy 已提交
1093 1094 1095
        '''
        Start the data feeding thread. 
        Can only call when the reader object is not iterable.  
1096
        
G
guofei 已提交
1097 1098
	Example:
	    .. code-block:: python
Z
Zeng Jinle 已提交
1099
    
H
Huihuang Zheng 已提交
1100 1101 1102 1103
                import paddle
                import paddle.fluid as fluid
                import numpy as np

1104 1105 1106 1107 1108 1109
                BATCH_SIZE = 10

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

G
guofei 已提交
1110
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
1111 1112 1113 1114
                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 已提交
1115
                executor = fluid.Executor(fluid.CPUPlace())
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
                executor.run(fluid.default_startup_program())
                for i in range(3):
                    reader.start()
                    while True:
                        try:
                            executor.run(feed=None)
                        except fluid.core.EOFException:
                            reader.reset()
                            break

Z
Zeng Jinle 已提交
1126 1127
	    '''
        self._loader.start()
S
sneaxiy 已提交
1128

S
sneaxiy 已提交
1129
    def reset(self):
S
add doc  
sneaxiy 已提交
1130 1131 1132
        '''
        Reset the reader object when :code:`fluid.core.EOFException` raises. 
        Can only call when the reader object is not iterable.
1133 1134 1135 1136
        
        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
1137 1138 1139 1140
                import paddle
                import paddle.fluid as fluid
                import numpy as np

1141 1142 1143 1144 1145 1146
                BATCH_SIZE = 10

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

G
guofei 已提交
1147
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
1148 1149 1150 1151
                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 已提交
1152
                executor = fluid.Executor(fluid.CPUPlace())
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
                executor.run(fluid.default_startup_program())
                for i in range(3):
                    reader.start()
                    while True:
                        try:
                            executor.run(feed=None)
                        except fluid.core.EOFException:
                            reader.reset()
                            break        

S
add doc  
sneaxiy 已提交
1163
        '''
Z
Zeng Jinle 已提交
1164
        self._loader.reset()
S
sneaxiy 已提交
1165

S
sneaxiy 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174
    def decorate_sample_generator(self,
                                  sample_generator,
                                  batch_size,
                                  drop_last=True,
                                  places=None):
        '''
        Set the data source of the PyReader object.
        
        The provided :code:`sample_generator` should be a Python generator,
1175
        which yields list(numpy.ndarray)-typed data of each sample.
S
sneaxiy 已提交
1176 1177 1178 1179

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

        If all inputs have no lods, this method is faster than 
S
sneaxiy 已提交
1180
        :code:`decorate_sample_list_generator(paddle.batch(sample_generator, ...))` .
S
sneaxiy 已提交
1181 1182 1183

        Args:
            sample_generator (generator): Python generator that yields
1184
                list(numpy.ndarray)-typed sample data.
S
sneaxiy 已提交
1185 1186 1187 1188 1189
            batch_size (int): batch size. Must be larger than 0.
            drop_last (bool): Whether to drop the last batch when sample number
                is less than batch_size. 
            places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
                be provided when PyReader is iterable.
1190 1191 1192 1193

        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
1194 1195 1196
                import paddle.fluid as fluid
                import numpy as np

1197 1198 1199
                EPOCH_NUM = 3
                ITER_NUM = 15
                BATCH_SIZE = 3
G
guofei 已提交
1200 1201 1202 1203 1204
        
                def network(image, label):
                    # User-defined network, here is an example of softmax regression.
                    predict = fluid.layers.fc(input=image, size=10, act='softmax')           
                    return fluid.layers.cross_entropy(input=predict, label=label)
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215

                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 已提交
1216 1217
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
                label = fluid.data(name='label', shape=[None, 1], dtype='int64')
1218 1219 1220 1221 1222
                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 已提交
1223 1224 1225 1226
                                                 places=[fluid.CPUPlace()])
                loss = network(image, label)
                executor = fluid.Executor(fluid.CPUPlace())
                executor.run(fluid.default_startup_program())
1227 1228 1229

                for _ in range(EPOCH_NUM):
                    for data in reader():
G
guofei 已提交
1230
                        executor.run(feed=data, fetch_list=[loss])
1231
    
S
sneaxiy 已提交
1232
        '''
Z
Zeng Jinle 已提交
1233 1234
        self._loader.set_sample_generator(sample_generator, batch_size,
                                          drop_last, places)
S
sneaxiy 已提交
1235

S
sneaxiy 已提交
1236
    def decorate_sample_list_generator(self, reader, places=None):
S
add doc  
sneaxiy 已提交
1237 1238 1239 1240
        '''
        Set the data source of the PyReader object. 

        The provided :code:`reader` should be a Python generator,
S
sneaxiy 已提交
1241
        which yields list(numpy.ndarray) typed batched data. 
S
add doc  
sneaxiy 已提交
1242 1243 1244 1245
        
        :code:`places` must be set when the PyReader object is iterable.

        Args:
S
sneaxiy 已提交
1246 1247 1248 1249
            reader (generator): Python generator that yields 
                list(numpy.ndarray)-typed batched data. 
            places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
                be provided when PyReader is iterable.
1250 1251 1252 1253
        
        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
1254 1255 1256 1257
                import paddle
                import paddle.fluid as fluid
                import numpy as np

1258 1259 1260 1261
                EPOCH_NUM = 3
                ITER_NUM = 15
                BATCH_SIZE = 3

G
guofei 已提交
1262 1263 1264 1265 1266
                def network(image, label):
                    # User-defined network, here is an example of softmax regression.
                    predict = fluid.layers.fc(input=image, size=10, act='softmax')           
                    return fluid.layers.cross_entropy(input=predict, label=label)

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
                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 已提交
1277 1278
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
                label = fluid.data(name='label', shape=[None, 1], dtype='int64')
1279 1280 1281 1282 1283
                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 已提交
1284 1285 1286 1287 1288
                    fluid.core.CPUPlace())
                
                loss = network(image, label)
                executor = fluid.Executor(fluid.core.CPUPlace())
                executor.run(fluid.default_startup_program())
1289 1290 1291

                for _ in range(EPOCH_NUM):
                    for data in reader():
G
guofei 已提交
1292
                        executor.run(feed=data, fetch_list=[loss])
1293
                 
S
add doc  
sneaxiy 已提交
1294
        '''
Z
Zeng Jinle 已提交
1295
        self._loader.set_sample_list_generator(reader, places)
S
sneaxiy 已提交
1296

S
sneaxiy 已提交
1297
    def decorate_batch_generator(self, reader, places=None):
S
add doc  
sneaxiy 已提交
1298 1299 1300 1301
        '''
        Set the data source of the PyReader object.

        The provided :code:`reader` should be a Python generator,
S
sneaxiy 已提交
1302
        which yields numpy.ndarray-typed or LoDTensor-typed batched data.
S
add doc  
sneaxiy 已提交
1303 1304 1305 1306 1307 1308

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

        Args:
            reader (generator): Python generator that yields LoDTensor-typed
                batched data.
S
sneaxiy 已提交
1309
            places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
S
sneaxiy 已提交
1310
                be provided when PyReader is iterable.
1311 1312 1313 1314

        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
1315 1316 1317
                import paddle.fluid as fluid
                import numpy as np

1318 1319 1320
                EPOCH_NUM = 3
                ITER_NUM = 15
                BATCH_SIZE = 3
G
guofei 已提交
1321 1322 1323 1324 1325
               
                def network(image, label):
                    # User-defined network, here is an example of softmax regression.
                    predict = fluid.layers.fc(input=image, size=10, act='softmax')           
                    return fluid.layers.cross_entropy(input=predict, label=label)
1326 1327 1328 1329 1330 1331 1332 1333

                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 已提交
1334 1335
                            batch_image = batch_image.astype('float32')
                            batch_label = batch_label.astype('int64')
1336 1337 1338
                            yield batch_image, batch_label
                    return generator

G
guofei 已提交
1339 1340
                image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32')
                label = fluid.data(name='label', shape=[None, 1], dtype='int64')
1341 1342 1343
                reader = fluid.io.PyReader(feed_list=[image, label], capacity=4, iterable=True)

                user_defined_generator = random_image_and_label_generator(784, 784)
G
guofei 已提交
1344 1345 1346 1347 1348
                reader.decorate_batch_generator(user_defined_generator, fluid.CPUPlace())
                
                loss = network(image, label)
                executor = fluid.Executor(fluid.CPUPlace())
                executor.run(fluid.default_startup_program())
1349 1350 1351

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

S
add doc  
sneaxiy 已提交
1354
        '''
Z
Zeng Jinle 已提交
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
        self._loader.set_batch_generator(reader, places)


class DatasetLoader(DataLoaderBase):
    def __init__(self, dataset, places, drop_last):
        assert isinstance(dataset,
                          DatasetBase), "dataset must be type of DatasetBase"
        assert not in_dygraph_mode(
        ), "DatasetLoader is not supported in dygraph mode yet"

        thread_num = len(places)

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

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

        dataset.set_thread(thread_num)

        if isinstance(dataset,
                      InMemoryDataset) and dataset.queue_num > thread_num:
            logging.warn("queue_num {} which is set in Dataset is ignored".
                         format(dataset.queue_num))
            dataset.set_queue_num(thread_num)

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

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

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

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