parallel_map.py 9.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 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.

# function:
16
#   transform samples in 'source' using 'worker'
17 18 19 20 21 22 23

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import sys
import six
24 25 26 27 28
if six.PY3:
    from queue import Empty
else:
    from Queue import Empty

29 30 31 32
import uuid
import logging
import signal
import threading
33
import traceback
34 35 36 37 38

logger = logging.getLogger(__name__)


class EndSignal(object):
39 40
    """ signal used to notify worker to exit
    """
41

42 43
    def __init__(self, id, errno=0, errmsg=''):
        self.id = id
44 45 46 47
        self.errno = errno
        self.errmsg = errmsg


48
class ParallelMap(object):
49
    """
50 51 52
    Transform samples to mapped samples which is similar to 
    'basic.MappedDataset', but multiple workers (threads or processes) 
    will be used
53 54 55 56 57

    Notes:
        this class is not thread-safe
    """

58 59 60 61 62 63 64 65 66 67
    def __init__(self,
                 source,
                 worker,
                 worker_num,
                 bufsize=100,
                 use_process=False,
                 memsize='3G'):
        self._worker_num = worker_num
        self._bufsize = bufsize
        self._use_process = use_process
68 69 70 71
        if self._use_process and sys.platform == "win32":
            logger.info("Use multi-thread reader instead of "
                        "multi-process reader on Windows.")
            self._use_process = False
72
        if self._use_process and type(memsize) is str:
K
Kaipeng Deng 已提交
73 74 75 76 77
            assert memsize[-1].lower() in ['g', 'm'], \
                "invalid param for memsize[%s], should be " \
                "ended with 'G' or 'g' or 'M' or 'm'" % (memsize)
            power = 3 if memsize[-1].lower() == 'g' else 2
            self._memsize = int(memsize[:-1]) * (1024**power)
78 79
        self._started = False
        self._source = source
80
        self._worker = worker
81 82
        self._exit = False
        self._setup()
83 84 85 86 87 88 89
        self._souce_drained = False

    def __iter__(self):
        return self

    def __next__(self):
        return self.next()
90 91 92

    def _setup(self):
        """setup input/output queues and workers """
93
        use_process = self._use_process
94

95
        bufsize = self._bufsize
96 97 98 99
        if use_process:
            from .shared_queue import SharedQueue as Queue
            from multiprocessing import Process as Worker
            from multiprocessing import Event
100
            memsize = self._memsize
W
walloollaw 已提交
101 102
            self._inq = Queue(bufsize, memsize=memsize)
            self._outq = Queue(bufsize, memsize=memsize)
103 104 105 106 107 108 109
        else:
            if six.PY3:
                from queue import Queue
            else:
                from Queue import Queue
            from threading import Thread as Worker
            from threading import Event
W
walloollaw 已提交
110 111
            self._inq = Queue(bufsize)
            self._outq = Queue(bufsize)
112

113
        consumer_num = self._worker_num
114 115 116 117 118 119 120
        id = str(uuid.uuid4())[-3:]
        self._producer = threading.Thread(
            target=self._produce,
            args=('producer-' + id, self._source, self._inq))
        self._producer.daemon = True

        self._consumers = []
121
        self._consumer_endsig = {}
122
        for i in range(consumer_num):
123
            consumer_id = 'consumer-' + id + '-' + str(i)
124 125
            p = Worker(
                target=self._consume,
126
                args=(consumer_id, self._inq, self._outq, self._worker))
127 128
            self._consumers.append(p)
            p.daemon = True
129
            setattr(p, 'id', consumer_id)
130 131 132 133 134 135 136 137

        self._epoch = -1
        self._feeding_ev = Event()
        self._produced = 0  # produced sample in self._produce
        self._consumed = 0  # consumed sample in self.next

    def _produce(self, id, source, inq):
        """Fetch data from source and feed it to 'inq' queue"""
138
        endsig = EndSignal(id)
139 140 141 142 143
        while True:
            self._feeding_ev.wait()
            if self._exit:
                break
            try:
144 145
                s = source.next()
                inq.put(s)
146 147
                self._produced += 1
            except StopIteration:
148
                self._souce_drained = True
149
                self._feeding_ev.clear()
150
                self._feeding_ev.wait()
151
            except Exception as e:
152 153 154 155
                endsig.errno = -1
                endsig.errmsg = "producer[{}] failed with error: {}" \
                    .format(id, str(e))
                inq.put(endsig)
156 157
                break

158
    def _consume(self, id, inq, outq, worker):
159
        """Fetch data from 'inq', process it and put result to 'outq'"""
160
        if self._use_process:
161
            # handle SIGTERM signal to exit to prevent print stack frame
162
            signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
163 164

        endsig = EndSignal(id)
165 166 167
        while True:
            sample = inq.get()
            if isinstance(sample, EndSignal):
168 169 170 171
                endsig.errno = sample.errno
                endsig.errmsg = "consumer[{}] exits for reason[{}]" \
                    .format(id, sample.errmsg)
                outq.put(endsig)
172 173 174
                break

            try:
175
                result = worker(sample)
176 177
                outq.put(result)
            except Exception as e:
178 179 180 181
                endsig.errno = -2
                endsig.errmsg = "consumer[{}] failed to map with error:[{}]" \
                    .format(id, str(e))
                outq.put(endsig)
182 183 184 185 186 187 188 189 190 191 192 193 194 195
                break

    def drained(self):
        assert self._epoch >= 0, "first epoch has not started yet"
        return self._source.drained() and self._produced == self._consumed

    def stop(self):
        """ notify to exit
        """
        self._exit = True
        self._feeding_ev.set()
        for _ in range(len(self._consumers)):
            self._inq.put(EndSignal(0, "notify consumers to exit"))

196 197 198 199 200
    def _consumer_healthy(self):
        abnormal_num = 0
        for w in self._consumers:
            if not w.is_alive() and w.id not in self._consumer_endsig:
                abnormal_num += 1
201
                if self._use_process:
202 203 204 205
                    errmsg = "consumer[{}] exit abnormally with exitcode[{}]" \
                                .format(w.pid, w.exitcode)
                else:
                    errmsg = "consumer[{}] exit abnormally".format(w.ident)
206

207 208 209 210 211 212 213 214
                logger.warn(errmsg)

        if abnormal_num > 0:
            logger.warn("{} consumers have exited abnormally!!!" \
                .format(abnormal_num))

        return abnormal_num == 0

215 216 217 218 219 220 221 222 223
    def next(self):
        """ get next transformed sample
        """
        if self._epoch < 0:
            self.reset()

        if self.drained():
            raise StopIteration()

224 225 226 227 228 229 230 231 232
        while not self._exit:
            try:
                sample = self._outq.get(timeout=3)
            except Empty as e:
                if not self._consumer_healthy():
                    raise StopIteration()
                else:
                    continue

233
            if isinstance(sample, EndSignal):
234 235 236
                self._consumer_endsig[sample.id] = sample
                logger.warn("recv endsignal from outq with errmsg[{}]" \
                    .format(sample.errmsg))
237

238
                if len(self._consumer_endsig.keys()) < len(self._consumers):
239 240
                    self._inq.put(sample)
                else:
241 242
                    self._exit = True
                    raise StopIteration("all consumers exited, no more samples")
243 244 245 246
            else:
                self._consumed += 1
                return sample

247 248
        raise StopIteration()

249 250 251
    def reset(self):
        """ reset for a new epoch of samples
        """
252 253
        assert not self._exit, "cannot reset for already stopped dataset"

254 255
        if self._epoch < 0:
            self._epoch = 0
256 257
            for w in self._consumers:
                w.start()
258 259
            self._producer.start()
        else:
260 261 262
            assert self._consumer_healthy(), "cannot start another pass of data" \
                " for some consumers exited abnormally before!!!"

263
            if not self.drained():
264 265
                logger.warn("reset before epoch[{}] finishes".format(
                    self._epoch))
266 267 268 269 270 271
                self._produced = self._produced - self._consumed
            else:
                self._produced = 0

            self._epoch += 1

272
        assert len(self._consumer_endsig.keys()) == 0, "some consumers already exited," \
273 274 275
            + " cannot start another epoch"

        self._source.reset()
276
        self._souce_drained = False
277 278 279 280 281 282
        self._consumed = 0
        self._feeding_ev.set()


# FIXME(dengkaipeng): fix me if you have better impliment
# handle terminate reader process, do not print stack frame
283
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())