parallel_map.py 9.3 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 38 39

logger = logging.getLogger(__name__)


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

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


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

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

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

    def __iter__(self):
        return self

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

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

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

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

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

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

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

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

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

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

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

        return abnormal_num == 0

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

        if self.drained():
            raise StopIteration()

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

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

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

248 249
        raise StopIteration()

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

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

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

            self._epoch += 1

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

        self._source.reset()
277
        self._souce_drained = False
278 279 280 281 282 283
        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
284
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
285 286 287 288 289 290 291 292 293 294


def _term_group(sig_num, frame):
    pid = os.getpid()
    pg = os.getpgid(os.getpid())
    logger.info("main proc {} exit, kill process group " "{}".format(pid, pg))
    os.killpg(pg, signal.SIGKILL)


signal.signal(signal.SIGINT, _term_group)