parallel_map.py 9.4 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

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

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

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

logger = logging.getLogger(__name__)

K
Kaipeng Deng 已提交
38 39
worker_set = set()

40 41

class EndSignal(object):
42 43
    """ signal used to notify worker to exit
    """
44

45 46
    def __init__(self, id, errno=0, errmsg=''):
        self.id = id
47 48 49 50
        self.errno = errno
        self.errmsg = errmsg


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

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

61 62 63 64 65 66 67 68 69 70
    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
71 72 73 74
        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
75
        if self._use_process and type(memsize) is str:
K
Kaipeng Deng 已提交
76 77 78 79 80
            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)
81 82
        self._started = False
        self._source = source
83
        self._worker = worker
84 85
        self._exit = False
        self._setup()
86 87 88 89 90 91 92
        self._souce_drained = False

    def __iter__(self):
        return self

    def __next__(self):
        return self.next()
93 94 95

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

98
        bufsize = self._bufsize
99 100 101 102
        if use_process:
            from .shared_queue import SharedQueue as Queue
            from multiprocessing import Process as Worker
            from multiprocessing import Event
103
            memsize = self._memsize
W
walloollaw 已提交
104 105
            self._inq = Queue(bufsize, memsize=memsize)
            self._outq = Queue(bufsize, memsize=memsize)
106 107 108 109 110 111 112
        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 已提交
113 114
            self._inq = Queue(bufsize)
            self._outq = Queue(bufsize)
115

116
        consumer_num = self._worker_num
117 118 119 120 121 122 123
        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 = []
124
        self._consumer_endsig = {}
K
Kaipeng Deng 已提交
125
        global worker_set
126
        for i in range(consumer_num):
127
            consumer_id = 'consumer-' + id + '-' + str(i)
128 129
            p = Worker(
                target=self._consume,
130
                args=(consumer_id, self._inq, self._outq, self._worker))
131 132
            self._consumers.append(p)
            p.daemon = True
133
            setattr(p, 'id', consumer_id)
K
Kaipeng Deng 已提交
134
            worker_set.add(p)
135 136 137 138 139 140 141 142

        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"""
143
        endsig = EndSignal(id)
144 145 146 147 148
        while True:
            self._feeding_ev.wait()
            if self._exit:
                break
            try:
149 150
                s = source.next()
                inq.put(s)
151 152
                self._produced += 1
            except StopIteration:
153
                self._souce_drained = True
154
                self._feeding_ev.clear()
155
                self._feeding_ev.wait()
156
            except Exception as e:
157 158 159 160
                endsig.errno = -1
                endsig.errmsg = "producer[{}] failed with error: {}" \
                    .format(id, str(e))
                inq.put(endsig)
161 162
                break

163
    def _consume(self, id, inq, outq, worker):
164
        """Fetch data from 'inq', process it and put result to 'outq'"""
165
        if self._use_process:
166
            # handle SIGTERM signal to exit to prevent print stack frame
167
            signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
168 169

        endsig = EndSignal(id)
170 171 172
        while True:
            sample = inq.get()
            if isinstance(sample, EndSignal):
173 174 175 176
                endsig.errno = sample.errno
                endsig.errmsg = "consumer[{}] exits for reason[{}]" \
                    .format(id, sample.errmsg)
                outq.put(endsig)
177 178 179
                break

            try:
180
                result = worker(sample)
181 182
                outq.put(result)
            except Exception as e:
183 184 185 186
                endsig.errno = -2
                endsig.errmsg = "consumer[{}] failed to map with error:[{}]" \
                    .format(id, str(e))
                outq.put(endsig)
187 188 189 190 191 192 193 194 195 196 197 198 199 200
                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"))

201 202 203 204 205
    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
206
                if self._use_process:
207 208 209 210
                    errmsg = "consumer[{}] exit abnormally with exitcode[{}]" \
                                .format(w.pid, w.exitcode)
                else:
                    errmsg = "consumer[{}] exit abnormally".format(w.ident)
211

212 213 214 215 216 217 218 219
                logger.warn(errmsg)

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

        return abnormal_num == 0

220 221 222 223 224 225 226 227 228
    def next(self):
        """ get next transformed sample
        """
        if self._epoch < 0:
            self.reset()

        if self.drained():
            raise StopIteration()

229 230 231 232 233 234 235 236 237
        while not self._exit:
            try:
                sample = self._outq.get(timeout=3)
            except Empty as e:
                if not self._consumer_healthy():
                    raise StopIteration()
                else:
                    continue

238
            if isinstance(sample, EndSignal):
239 240 241
                self._consumer_endsig[sample.id] = sample
                logger.warn("recv endsignal from outq with errmsg[{}]" \
                    .format(sample.errmsg))
242

243
                if len(self._consumer_endsig.keys()) < len(self._consumers):
244 245
                    self._inq.put(sample)
                else:
246 247
                    self._exit = True
                    raise StopIteration("all consumers exited, no more samples")
248 249 250 251
            else:
                self._consumed += 1
                return sample

252 253
        raise StopIteration()

254 255 256
    def reset(self):
        """ reset for a new epoch of samples
        """
257 258
        assert not self._exit, "cannot reset for already stopped dataset"

259 260
        if self._epoch < 0:
            self._epoch = 0
261 262
            for w in self._consumers:
                w.start()
263 264
            self._producer.start()
        else:
265 266 267
            assert self._consumer_healthy(), "cannot start another pass of data" \
                " for some consumers exited abnormally before!!!"

268
            if not self.drained():
269 270
                logger.warn("reset before epoch[{}] finishes".format(
                    self._epoch))
271 272 273 274 275 276
                self._produced = self._produced - self._consumed
            else:
                self._produced = 0

            self._epoch += 1

277
        assert len(self._consumer_endsig.keys()) == 0, "some consumers already exited," \
278 279 280
            + " cannot start another epoch"

        self._source.reset()
281
        self._souce_drained = False
282 283 284 285
        self._consumed = 0
        self._feeding_ev.set()


K
Kaipeng Deng 已提交
286
# FIXME: fix me if you have better impliment
287
# handle terminate reader process, do not print stack frame
288
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
289 290


K
Kaipeng Deng 已提交
291 292 293 294 295 296
def _term_workers(sig_num, frame):
    global worker_set
    logger.info("main proc {} exit, kill subprocess {}".format(
        pid, [w.pid for w in worker_set]))
    for w in worker_set:
        os.kill(w, signal.SIGKILL)
297 298


K
Kaipeng Deng 已提交
299
signal.signal(signal.SIGINT, _term_workers)