decorator.py 20.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2016 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.

T
tangwei12 已提交
15 16
from threading import Thread
import subprocess
Q
Qiao Longfei 已提交
17
import multiprocessing
18
import six
Q
Qiao Longfei 已提交
19
import sys
20
import warnings
21
import logging
T
tangwei12 已提交
22

23
from six.moves.queue import Queue
24
from six.moves import zip_longest
25 26
from six.moves import map
from six.moves import zip
27 28
import itertools
import random
T
tangwei12 已提交
29
import zlib
30

M
minqiyang 已提交
31
import paddle.compat as cpt
32
from paddle.fluid.reader import QUEUE_GET_TIMEOUT
33

34 35
__all__ = []

36
# On macOS, the 'spawn' start method is now the default in Python3.8 multiprocessing,
37
# Paddle is currently unable to solve this, so forces the process to start using
38 39
# the 'fork' start method.
#
40
# TODO: This solution is not good, because the fork start method could lead to
41 42 43 44 45
# crashes of the subprocess. Figure out how to make 'spawn' work.
#
# For more details, please refer to
# https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods
# https://bugs.python.org/issue33725
46
if sys.version_info >= (3, 8) and sys.platform == 'darwin':
47 48 49 50
    fork_context = multiprocessing.get_context('fork')
else:
    fork_context = multiprocessing

51

S
sneaxiy 已提交
52 53
def cache(reader):
    """
L
Ligoml 已提交
54
    Cache the reader data into memory.
S
sneaxiy 已提交
55

L
Ligoml 已提交
56 57 58
    Be careful that this method may take long time to process,
    and consume lots of memory. :code:`reader()` would only
    call once.
S
sneaxiy 已提交
59 60

    Args:
L
Ligoml 已提交
61
        reader (generator): a reader object which yields
S
sneaxiy 已提交
62 63 64
            data each time.

    Returns:
S
sneaxiy 已提交
65
        generator: a decorated reader object which yields data from cached memory.
L
Ligoml 已提交
66

67 68 69 70
    Examples:
        .. code-block:: python

            import paddle
L
Ligoml 已提交
71

72 73 74
            def reader():
                for i in range(3):
                    yield i
L
Ligoml 已提交
75

76 77
            # All data is cached into memory
            cached_reader = paddle.io.cache(reader)
L
Ligoml 已提交
78

79 80 81
            # Output: 0 1 2
            for i in cached_reader():
                print(i)
S
sneaxiy 已提交
82 83 84 85 86 87 88 89 90 91
    """
    all_data = tuple(reader())

    def __impl__():
        for item in all_data:
            yield item

    return __impl__


H
Helin Wang 已提交
92 93 94
def map_readers(func, *readers):
    """
    Creates a data reader that outputs return value of function using
95
    output of each data reader as arguments.
H
Helin Wang 已提交
96

97 98 99 100 101 102
    If input readers output the following data entries: 2 3,
    and the input func is mul(x, y),
    the output of the resulted reader will be 6.


    Args:
L
Ligoml 已提交
103
        func: a function to read data and compute result, the output of this function
104 105
              will be set as the output of the resulted data reader.
        readers (Reader|list of Reader): list of readers whose outputs will be used as arguments of func.
L
Ligoml 已提交
106

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    Returns:
        the resulted data reader (Reader)

    Examples:

        .. code-block:: python

         import paddle.reader
         d = {"h": 0, "i": 1}
         def func(x):
             return d[x]
         def reader():
             yield "h"
             yield "i"
         map_reader_result = paddle.reader.map_readers(func, reader)
H
Helin Wang 已提交
122 123 124 125 126 127
    """

    def reader():
        rs = []
        for r in readers:
            rs.append(r())
128
        for e in map(func, *rs):
H
Helin Wang 已提交
129 130 131 132 133
            yield e

    return reader


H
Helin Wang 已提交
134
def shuffle(reader, buf_size):
135
    """
136 137
    paddle.fluid.io.shuffle ( :ref:`api_fluid_io_shuffle` ) is recommended to use,
    and paddle.reader.shuffle is an alias.
138

139
    This API creates a decorated reader that outputs the shuffled data.
140

L
Ligoml 已提交
141
    The output data from the origin reader will be saved into a buffer,
142
    and then shuffle the data. The size of buffer is determined by argument buf_size.
L
Ligoml 已提交
143

144 145 146
    Args:
        reader(callable): the original reader whose data will be shuffled.
        buf_size(int): the size of shuffled buffer.
147

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    Returns:
        callable: a decorated reader.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid

            def reader():
                for i in range(5):
                    yield i
            shuffled_reader = fluid.io.shuffle(reader, 3)
            for e in shuffled_reader():
                print(e)
            # outputs are 0~4 unordered arrangement
163 164
    """

H
Helin Wang 已提交
165
    def data_reader():
166
        buf = []
H
Helin Wang 已提交
167
        for e in reader():
168 169 170 171 172 173 174 175 176 177 178 179
            buf.append(e)
            if len(buf) >= buf_size:
                random.shuffle(buf)
                for b in buf:
                    yield b
                buf = []

        if len(buf) > 0:
            random.shuffle(buf)
            for b in buf:
                yield b

H
Helin Wang 已提交
180
    return data_reader
181 182


H
Helin Wang 已提交
183
def chain(*readers):
184
    """
185
    Use the input data readers to create a chained data reader. The new created reader
186 187
    chains the outputs of input readers together as its output, and it do not change
    the format of the outputs.
188

189 190 191 192 193 194 195 196
    **Note**:
        ``paddle.reader.chain`` is the alias of ``paddle.fluid.io.chain``, and
        ``paddle.fluid.io.chain`` is recommended to use.

    For example, if three input readers' outputs are as follows:
    [0, 0, 0],
    [10, 10, 10],
    [20, 20, 20].
H
Helin Wang 已提交
197
    The chained reader will output:
198
    [0, 0, 0], [10, 10, 10], [20, 20, 20].
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229

    Args:
        readers(list): input data readers.

    Returns:
        callable: the new chained data reader.

    Examples:
        ..  code-block:: python

            import paddle

            def reader_creator_3(start):
                def reader():
                    for i in range(start, start + 3):
                        yield [i, i, i]
                return reader

            c = paddle.reader.chain(reader_creator_3(0), reader_creator_3(10), reader_creator_3(20))
            for e in c():
                print(e)
            # Output:
            # [0, 0, 0]
            # [1, 1, 1]
            # [2, 2, 2]
            # [10, 10, 10]
            # [11, 11, 11]
            # [12, 12, 12]
            # [20, 20, 20]
            # [21, 21, 21]
            # [22, 22, 22]
230 231 232

    """

H
Helin Wang 已提交
233
    def reader():
234
        rs = []
H
Helin Wang 已提交
235
        for r in readers:
236 237 238 239 240
            rs.append(r())

        for e in itertools.chain(*rs):
            yield e

H
Helin Wang 已提交
241
    return reader
242 243


H
Helin Wang 已提交
244
class ComposeNotAligned(ValueError):
245 246 247
    pass


H
Helin Wang 已提交
248
def compose(*readers, **kwargs):
249 250
    """
    Creates a data reader whose output is the combination of input readers.
251

H
Helin Wang 已提交
252
    If input readers output following data entries:
253
    (1, 2)    3    (4, 5)
H
Helin Wang 已提交
254
    The composed reader will output:
255 256
    (1, 2, 3, 4, 5)

H
huzhiqiang 已提交
257
    Args:
L
Ligoml 已提交
258
        readers (Reader|list of Reader): readers that will be composed together.
H
huzhiqiang 已提交
259 260 261 262 263
        check_alignment(bool, optional): Indicates whether the input readers are checked for
                              alignment. If True, whether input readers are aligned
                              correctly will be checked, else alignment will not be checkout and trailing outputs
                              will be discarded. Defaults to True.

L
Ligoml 已提交
264
    Returns:
H
huzhiqiang 已提交
265 266 267 268
        the new data reader (Reader).

    Raises:
        ComposeNotAligned: outputs of readers are not aligned. This will not raise if check_alignment is set to False.
L
Ligoml 已提交
269

H
huzhiqiang 已提交
270 271
    Examples:
        .. code-block:: python
272

H
huzhiqiang 已提交
273 274 275 276 277 278 279
          import paddle.fluid as fluid
          def reader_creator_10(dur):
              def reader():
                 for i in range(10):
                     yield i
              return reader
          reader = fluid.io.compose(reader_creator_10(0), reader_creator_10(0))
280 281 282 283 284 285 286
    """
    check_alignment = kwargs.pop('check_alignment', True)

    def make_tuple(x):
        if isinstance(x, tuple):
            return x
        else:
L
Ligoml 已提交
287
            return (x,)
288

H
Helin Wang 已提交
289
    def reader():
290
        rs = []
H
Helin Wang 已提交
291
        for r in readers:
292 293
            rs.append(r())
        if not check_alignment:
294 295
            for outputs in zip(*rs):
                yield sum(list(map(make_tuple, outputs)), ())
296
        else:
297
            for outputs in zip_longest(*rs):
298 299 300
                for o in outputs:
                    if o is None:
                        # None will be not be present if compose is aligned
H
Helin Wang 已提交
301
                        raise ComposeNotAligned(
L
Ligoml 已提交
302 303
                            "outputs of readers are not aligned."
                        )
304
                yield sum(list(map(make_tuple, outputs)), ())
305

H
Helin Wang 已提交
306
    return reader
307 308


H
Helin Wang 已提交
309
def buffered(reader, size):
310 311
    """
    Creates a buffered data reader.
312

H
Helin Wang 已提交
313 314
    The buffered data reader will read and save data entries into a
    buffer. Reading from the buffered data reader will proceed as long
315
    as the buffer is not empty.
316

317 318 319 320 321 322
    Args:
        reader(generator): the data reader to read from.
        size(int): max buffer size.

    Returns:
        generator: the buffered data reader.
L
Ligoml 已提交
323

324 325
    Examples:
        .. code-block:: python
326

327
            import paddle
L
Ligoml 已提交
328

329 330 331
            def reader():
                for i in range(3):
                    yield i
L
Ligoml 已提交
332

333 334
            # Create a buffered reader, and the buffer size is 2.
            buffered_reader = paddle.io.buffered(reader, 2)
L
Ligoml 已提交
335

336 337 338
            # Output: 0 1 2
            for i in buffered_reader():
                print(i)
339 340
    """

L
Ligoml 已提交
341
    class EndSignal:
342 343 344 345 346 347 348 349 350
        pass

    end = EndSignal()

    def read_worker(r, q):
        for d in r:
            q.put(d)
        q.put(end)

H
Helin Wang 已提交
351 352
    def data_reader():
        r = reader()
353
        q = Queue(maxsize=size)
L
Ligoml 已提交
354 355 356 357 358 359 360
        t = Thread(
            target=read_worker,
            args=(
                r,
                q,
            ),
        )
361 362 363 364 365 366 367
        t.daemon = True
        t.start()
        e = q.get()
        while e != end:
            yield e
            e = q.get()

H
Helin Wang 已提交
368
    return data_reader
Y
Yu Yang 已提交
369 370


Y
Yu Yang 已提交
371
def firstn(reader, n):
Y
Yu Yang 已提交
372
    """
373 374
    paddle.fluid.io.firstn ( :ref:`api_fluid_io_firstn` ) is recommended to use,
    and paddle.reader.firstn is an alias.
L
Ligoml 已提交
375 376

    This API creates a decorated reader, and limits the max number of
377
    samples that reader could return.
Y
Yu Yang 已提交
378

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    Args:
        reader(callable): the input reader.
        n(int): the max number of samples in the reader.

    Returns:
        callable: the decorated reader.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid

            def reader():
                for i in range(100):
                    yield i
            firstn_reader = fluid.io.firstn(reader, 5)
            for e in firstn_reader():
                print(e)
L
Ligoml 已提交
397
            # the outputs are: 0 1 2 3 4
Y
Yu Yang 已提交
398 399
    """

Y
Yu Yang 已提交
400 401 402 403
    # TODO(yuyang18): Check if just drop the reader, could clean the opened
    # resource or not?

    def firstn_reader():
Y
Yu Yang 已提交
404
        for i, item in enumerate(reader()):
Y
Yu Yang 已提交
405
            if i == n:
Y
Yu Yang 已提交
406 407 408
                break
            yield item

Y
Yu Yang 已提交
409
    return firstn_reader
410 411


L
Ligoml 已提交
412
class XmapEndSignal:
413 414 415
    pass


416
def xmap_readers(mapper, reader, process_num, buffer_size, order=False):
417
    """
Z
Zeng Jinle 已提交
418 419 420 421
    Use multi-threads to map samples from reader by a mapper defined by user.

    Args:
        mapper (callable): a function to map the data from reader.
L
Ligoml 已提交
422
        reader (callable): a data reader which yields the data.
Z
Zeng Jinle 已提交
423
        process_num (int): thread number to handle original sample.
L
Ligoml 已提交
424 425
        buffer_size (int): size of the queue to read data in.
        order (bool): whether to keep the data order from original reader.
Z
Zeng Jinle 已提交
426 427 428
            Default False.

    Returns:
L
Ligoml 已提交
429
        callable: a decorated reader with data mapping.
430 431
    """
    end = XmapEndSignal()
W
wanghaoshuang 已提交
432

433 434 435 436 437
    # define a worker to read samples from reader to in_queue
    def read_worker(reader, in_queue):
        for i in reader():
            in_queue.put(i)
        in_queue.put(end)
W
wanghaoshuang 已提交
438

439 440 441 442
    # define a worker to read samples from reader to in_queue with order flag
    def order_read_worker(reader, in_queue):
        in_order = 0
        for i in reader():
W
wanghaoshuang 已提交
443 444
            in_queue.put((in_order, i))
            in_order += 1
445
        in_queue.put(end)
446 447 448 449 450 451 452 453 454 455 456

    # define a worker to handle samples from in_queue by mapper
    # and put mapped samples into out_queue
    def handle_worker(in_queue, out_queue, mapper):
        sample = in_queue.get()
        while not isinstance(sample, XmapEndSignal):
            r = mapper(sample)
            out_queue.put(r)
            sample = in_queue.get()
        in_queue.put(end)
        out_queue.put(end)
W
wanghaoshuang 已提交
457

458 459 460 461 462 463 464 465 466 467
    # define a worker to handle samples from in_queue by mapper
    # and put mapped samples into out_queue by order
    def order_handle_worker(in_queue, out_queue, mapper, out_order):
        ins = in_queue.get()
        while not isinstance(ins, XmapEndSignal):
            order, sample = ins
            r = mapper(sample)
            while order != out_order[0]:
                pass
            out_queue.put(r)
W
wanghaoshuang 已提交
468
            out_order[0] += 1
469 470 471
            ins = in_queue.get()
        in_queue.put(end)
        out_queue.put(end)
472 473

    def xreader():
474 475
        in_queue = Queue(buffer_size)
        out_queue = Queue(buffer_size)
476 477 478 479 480 481 482 483
        out_order = [0]
        # start a read worker in a thread
        target = order_read_worker if order else read_worker
        t = Thread(target=target, args=(reader, in_queue))
        t.daemon = True
        t.start()
        # start several handle_workers
        target = order_handle_worker if order else handle_worker
L
Ligoml 已提交
484 485 486 487 488
        args = (
            (in_queue, out_queue, mapper, out_order)
            if order
            else (in_queue, out_queue, mapper)
        )
489
        workers = []
490
        for i in range(process_num):
491 492 493 494 495 496
            worker = Thread(target=target, args=args)
            worker.daemon = True
            workers.append(worker)
        for w in workers:
            w.start()

497 498 499 500 501 502 503 504 505 506 507 508 509
        sample = out_queue.get()
        while not isinstance(sample, XmapEndSignal):
            yield sample
            sample = out_queue.get()
        finish = 1
        while finish < process_num:
            sample = out_queue.get()
            if isinstance(sample, XmapEndSignal):
                finish += 1
            else:
                yield sample

    return xreader
510 511


Q
Qiao Longfei 已提交
512 513
def multiprocess_reader(readers, use_pipe=True, queue_size=1000):
    """
514
    This API use python ``multiprocessing`` to read data from ``readers`` parallelly,
L
Ligoml 已提交
515 516 517
    and then ``multiprocess.Queue`` or ``multiprocess.Pipe`` is used to merge
    these data. A separate process will be created for each reader in the
    ``readers`` list, please guarantee every reader can work independently
518 519
    to avoid conflicts in parallel environment.

L
Ligoml 已提交
520 521

    ``Multiprocess.Queue`` require the rw access right to /dev/shm, and it's not supported
522
    in some platforms.
Q
Qiao Longfei 已提交
523

524
    Parameters:
L
Ligoml 已提交
525
       readers (list( ``generator`` ) | tuple( ``generator`` )): a python ``generator`` list
526 527 528 529 530 531
           used to read input data
       use_pipe (bool, optional): control the inner API used to implement the multi-processing,
           default True - use ``multiprocess.Pipe`` which is recommended
       queue_size (int, optional): only useful when ``use_pipe`` is False - ``multiprocess.Queue``
           is used, default 1000. Increase this value can speed up the data reading, and more memory
           will be consumed.
Q
Qiao Longfei 已提交
532

533 534
    Returns:
        ``generator``: a new reader which can be run parallelly
Q
Qiao Longfei 已提交
535

536 537

    Example:
Q
Qiao Longfei 已提交
538 539 540

    .. code-block:: python

541 542 543
        import paddle.fluid as fluid
        from paddle.fluid.io import multiprocess_reader
        import numpy as np
L
Ligoml 已提交
544

545
        sample_files = ['sample_file_1', 'sample_file_2']
L
Ligoml 已提交
546

547 548 549 550 551
        def fake_input_files():
            with open(sample_files[0], 'w') as f:
               np.savez(f, a=np.array([1, 2]), b=np.array([3, 4]), c=np.array([5, 6]), d=np.array([7, 8]))
            with open(sample_files[1], 'w') as f:
               np.savez(f, a=np.array([9, 10]), b=np.array([11, 12]), c=np.array([13, 14]))
L
Ligoml 已提交
552 553


554 555 556 557 558 559 560
        def generate_reader(file_name):
            # load data file
            def _impl():
                data = np.load(file_name)
                for item in sorted(data.files):
                    yield data[item],
            return _impl
L
Ligoml 已提交
561

562 563 564
        if __name__ == '__main__':
            # generate sample input files
            fake_input_files()
L
Ligoml 已提交
565

566 567 568
            with fluid.program_guard(fluid.Program(), fluid.Program()):
                place = fluid.CPUPlace()
                # the 1st 2 is batch size
L
Ligoml 已提交
569
                image = fluid.data(name='image', dtype='int64', shape=[2, 1, 2])
570 571
                fluid.layers.Print(image)
                # print detailed tensor info of image variable
L
Ligoml 已提交
572

573
                reader = fluid.io.PyReader(feed_list=[image], capacity=2)
L
Ligoml 已提交
574

575 576
                decorated_reader = multiprocess_reader(
                    [generate_reader(sample_files[0]), generate_reader(sample_files[1])], False)
L
Ligoml 已提交
577

578
                reader.decorate_sample_generator(decorated_reader, batch_size=2, places=[place])
L
Ligoml 已提交
579

580 581
                exe = fluid.Executor(place)
                exe.run(fluid.default_startup_program())
L
Ligoml 已提交
582

583 584 585 586 587 588 589 590 591
                for data in reader():
                    res = exe.run(feed=data, fetch_list=[image])
                    print(res[0])
                    # print below content in this case
                    # [[[1 2]], [[3 4]]]
                    # [[[5 6]], [[7 8]]]
                    # [[[9 10]], [[11 12]]]
                    # [13,14] will be dropped

Q
Qiao Longfei 已提交
592 593
    """

594 595
    if sys.platform == 'win32':
        raise NotImplementedError(
L
Ligoml 已提交
596 597
            "The multiprocess_reader method is not supported on windows."
        )
598

599
    # ujson is ultra fast json encoder and decoder written in pure C with bindings for Python 3.6+.
Q
Qiao Longfei 已提交
600 601 602
    try:
        import ujson as json
    except Exception as e:
603 604
        warnings.warn(
            "The `ujson` module is not found, use the `json` module, `ujson` encodes and decodes faster, "
L
Ligoml 已提交
605 606
            "you can install `ujson` through `pip install ujson`."
        )
Q
Qiao Longfei 已提交
607 608
        import json

L
Ligoml 已提交
609 610 611
    assert (
        isinstance(readers, (list, tuple)) and len(readers) > 0
    ), "`readers` must be list or tuple."
Q
Qiao Longfei 已提交
612 613

    def _read_into_queue(reader, queue):
614 615 616 617 618 619 620 621 622
        try:
            for sample in reader():
                if sample is None:
                    raise ValueError("sample has None")
                queue.put(sample)
            queue.put(None)
        except:
            queue.put("")
            six.reraise(*sys.exc_info())
Q
Qiao Longfei 已提交
623 624

    def queue_reader():
625
        queue = fork_context.Queue(queue_size)
Q
Qiao Longfei 已提交
626
        for reader in readers:
L
Ligoml 已提交
627 628 629
            p = fork_context.Process(
                target=_read_into_queue, args=(reader, queue)
            )
Q
Qiao Longfei 已提交
630 631 632 633 634
            p.start()

        reader_num = len(readers)
        finish_num = 0
        while finish_num < reader_num:
635 636 637 638 639 640 641 642
            try:
                sample = queue.get(timeout=QUEUE_GET_TIMEOUT)
            except:
                logging.error(
                    "multiprocess_reader failed to get data from the multiprocessing.Queue."
                )
                six.reraise(*sys.exc_info())

Q
Qiao Longfei 已提交
643 644
            if sample is None:
                finish_num += 1
645
            elif sample == "":
646 647 648
                raise ValueError(
                    "multiprocess_reader failed to put data into the multiprocessing.Queue."
                )
Q
Qiao Longfei 已提交
649 650 651 652
            else:
                yield sample

    def _read_into_pipe(reader, conn):
653 654 655 656 657 658 659 660 661 662 663
        try:
            for sample in reader():
                if sample is None:
                    raise ValueError("sample has None!")
                conn.send(json.dumps(sample))
            conn.send(json.dumps(None))
            conn.close()
        except:
            conn.send(json.dumps(""))
            conn.close()
            six.reraise(*sys.exc_info())
Q
Qiao Longfei 已提交
664 665 666 667

    def pipe_reader():
        conns = []
        for reader in readers:
668
            parent_conn, child_conn = fork_context.Pipe()
Q
Qiao Longfei 已提交
669
            conns.append(parent_conn)
L
Ligoml 已提交
670 671 672
            p = fork_context.Process(
                target=_read_into_pipe, args=(reader, child_conn)
            )
Q
Qiao Longfei 已提交
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
            p.start()

        reader_num = len(readers)
        finish_num = 0
        conn_to_remove = []
        while finish_num < reader_num:
            for conn in conn_to_remove:
                conns.remove(conn)
            conn_to_remove = []
            for conn in conns:
                sample = json.loads(conn.recv())
                if sample is None:
                    finish_num += 1
                    conn.close()
                    conn_to_remove.append(conn)
688 689 690
                elif sample == "":
                    conn.close()
                    conn_to_remove.append(conn)
691 692 693
                    raise ValueError(
                        "multiprocess_reader failed to send data into the multiprocessing.Pipe."
                    )
Q
Qiao Longfei 已提交
694 695 696 697 698 699 700
                else:
                    yield sample

    if use_pipe:
        return pipe_reader
    else:
        return queue_reader