parallel_map.py 9.0 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 73 74 75 76
        if self._use_process and type(memsize) is str:
            assert memsize[-1].lower() == 'g', \
                "invalid param for memsize[%s], should be ended with 'G' or 'g'" % (memsize)
            gb = memsize[:-1]
            self._memsize = int(gb) * 1024**3
77 78
        self._started = False
        self._source = source
79
        self._worker = worker
80 81
        self._exit = False
        self._setup()
82 83 84 85 86 87 88
        self._souce_drained = False

    def __iter__(self):
        return self

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

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

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

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

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

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

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

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

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

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

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

        return abnormal_num == 0

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

        if self.drained():
            raise StopIteration()

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

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

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

246 247
        raise StopIteration()

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

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

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

            self._epoch += 1

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

        self._source.reset()
275
        self._souce_drained = False
276 277 278 279 280 281
        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
282
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())