decorator.py 7.9 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.

H
Helin Wang 已提交
15 16
__all__ = [
    'map_readers', 'buffered', 'compose', 'chain', 'shuffle',
17
    'ComposeNotAligned', 'firstn', 'xmap'
H
Helin Wang 已提交
18
]
19

20 21
import itertools
import random
Y
Yu Yang 已提交
22 23
from Queue import Queue
from threading import Thread
24 25
from multiprocessing import Queue as MQueue
from multiprocessing import Process
26 27


H
Helin Wang 已提交
28 29 30 31 32
def map_readers(func, *readers):
    """
    Creates a data reader that outputs return value of function using
    output of each data readers as arguments.

Y
Yu Yang 已提交
33 34 35 36 37
    :param func: function to use. The type of func should be (Sample) => Sample
    :type: callable
    :param readers: readers whose outputs will be used as arguments of func.
    :return: the created data reader.
    :rtype: callable
H
Helin Wang 已提交
38 39 40 41 42 43 44 45 46 47 48 49
    """

    def reader():
        rs = []
        for r in readers:
            rs.append(r())
        for e in itertools.imap(func, *rs):
            yield e

    return reader


H
Helin Wang 已提交
50
def shuffle(reader, buf_size):
51
    """
Y
Yu Yang 已提交
52
    Creates a data reader whose data output is shuffled.
53

H
Helin Wang 已提交
54
    Output from the iterator that created by original reader will be
55 56 57
    buffered into shuffle buffer, and then shuffled. The size of shuffle buffer
    is determined by argument buf_size.

58
    :param reader: the original reader whose output will be shuffled.
Y
Yu Yang 已提交
59
    :type reader: callable
60
    :param buf_size: shuffle buffer size.
Y
Yu Yang 已提交
61
    :type buf_size: int
62

Y
Yu Yang 已提交
63 64
    :return: the new reader whose output is shuffled.
    :rtype: callable
65 66
    """

H
Helin Wang 已提交
67
    def data_reader():
68
        buf = []
H
Helin Wang 已提交
69
        for e in reader():
70 71 72 73 74 75 76 77 78 79 80 81
            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 已提交
82
    return data_reader
83 84


H
Helin Wang 已提交
85
def chain(*readers):
86 87 88
    """
    Creates a data reader whose output is the outputs of input data
    readers chained together.
89

H
Helin Wang 已提交
90
    If input readers output following data entries:
91 92 93
    [0, 0, 0]
    [1, 1, 1]
    [2, 2, 2]
H
Helin Wang 已提交
94
    The chained reader will output:
95 96
    [0, 0, 0, 1, 1, 1, 2, 2, 2]

97
    :param readers: input readers.
Y
Yu Yang 已提交
98 99
    :return: the new data reader.
    :rtype: callable
100 101
    """

H
Helin Wang 已提交
102
    def reader():
103
        rs = []
H
Helin Wang 已提交
104
        for r in readers:
105 106 107 108 109
            rs.append(r())

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

H
Helin Wang 已提交
110
    return reader
111 112


H
Helin Wang 已提交
113
class ComposeNotAligned(ValueError):
114 115 116
    pass


H
Helin Wang 已提交
117
def compose(*readers, **kwargs):
118 119
    """
    Creates a data reader whose output is the combination of input readers.
120

H
Helin Wang 已提交
121
    If input readers output following data entries:
122
    (1, 2)    3    (4, 5)
H
Helin Wang 已提交
123
    The composed reader will output:
124 125
    (1, 2, 3, 4, 5)

Y
Yu Yang 已提交
126 127
    :param readers: readers that will be composed together.
    :param check_alignment: if True, will check if input readers are aligned
128 129
        correctly. If False, will not check alignment and trailing outputs
        will be discarded. Defaults to True.
Y
Yu Yang 已提交
130
    :type check_alignment: bool
131

Y
Yu Yang 已提交
132
    :return: the new data reader.
133

134 135
    :raises ComposeNotAligned: outputs of readers are not aligned.
        Will not raise when check_alignment is set to False.
136 137 138 139 140 141 142 143 144
    """
    check_alignment = kwargs.pop('check_alignment', True)

    def make_tuple(x):
        if isinstance(x, tuple):
            return x
        else:
            return (x, )

H
Helin Wang 已提交
145
    def reader():
146
        rs = []
H
Helin Wang 已提交
147
        for r in readers:
148 149 150 151 152 153 154 155 156
            rs.append(r())
        if not check_alignment:
            for outputs in itertools.izip(*rs):
                yield sum(map(make_tuple, outputs), ())
        else:
            for outputs in itertools.izip_longest(*rs):
                for o in outputs:
                    if o is None:
                        # None will be not be present if compose is aligned
H
Helin Wang 已提交
157 158
                        raise ComposeNotAligned(
                            "outputs of readers are not aligned.")
159 160
                yield sum(map(make_tuple, outputs), ())

H
Helin Wang 已提交
161
    return reader
162 163


H
Helin Wang 已提交
164
def buffered(reader, size):
165 166
    """
    Creates a buffered data reader.
167

H
Helin Wang 已提交
168 169
    The buffered data reader will read and save data entries into a
    buffer. Reading from the buffered data reader will proceed as long
170
    as the buffer is not empty.
171
    
172
    :param reader: the data reader to read from.
Y
Yu Yang 已提交
173
    :type reader: callable
174
    :param size: max buffer size.
Y
Yu Yang 已提交
175
    :type size: int
176
    
177
    :returns: the buffered data reader.
178 179 180 181 182 183 184 185 186 187 188 189
    """

    class EndSignal():
        pass

    end = EndSignal()

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

H
Helin Wang 已提交
190 191
    def data_reader():
        r = reader()
192 193 194 195 196 197 198 199 200 201 202 203
        q = Queue(maxsize=size)
        t = Thread(
            target=read_worker, args=(
                r,
                q, ))
        t.daemon = True
        t.start()
        e = q.get()
        while e != end:
            yield e
            e = q.get()

H
Helin Wang 已提交
204
    return data_reader
Y
Yu Yang 已提交
205 206


Y
Yu Yang 已提交
207
def firstn(reader, n):
Y
Yu Yang 已提交
208 209
    """
    Limit the max number of samples that reader could return.
Y
Yu Yang 已提交
210 211 212 213 214 215 216

    :param reader: the data reader to read from.
    :type reader: callable
    :param n: the max number of samples that return.
    :type n: int
    :return: the decorated reader.
    :rtype: callable
Y
Yu Yang 已提交
217 218
    """

Y
Yu Yang 已提交
219 220 221 222
    # TODO(yuyang18): Check if just drop the reader, could clean the opened
    # resource or not?

    def firstn_reader():
Y
Yu Yang 已提交
223
        for i, item in enumerate(reader()):
Y
Yu Yang 已提交
224
            if i == n:
Y
Yu Yang 已提交
225 226 227
                break
            yield item

Y
Yu Yang 已提交
228
    return firstn_reader
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299


class XmapEndSignal():
    pass


def xmap(mapper, reader, process_num, buffer_size):
    """
    Use multiprocess to map samples from reader by a mapper defined by user.
    And this function contains a buffered decorator.
    :param mapper:  a function to map sample.
    :type mapper: callable
    :param reader: the data reader to read from
    :type reader: callable
    :param process_num: process number to handle original sample 
    :type process_num: int
    :param buffer_size: max buffer size
    :type buffer_size: int
    :return: the decarated reader
    :rtype: callable
    """
    end = XmapEndSignal()
    in_queue = MQueue(buffer_size)
    out_queue = MQueue(buffer_size)

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

    # start a read worker in a thread
    t = Thread(target=read_worker, args=(reader, in_queue))
    t.daemon = True
    t.start()

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

    # start several handle_workers
    workers = []
    for i in xrange(process_num):
        worker = Process(
            target=handle_worker, args=(in_queue, out_queue, mapper))
        worker.daemon = True
        workers.append(worker)
    for w in workers:
        w.start()

    def xreader():
        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