data_utils.py 5.2 KB
Newer Older
D
dengkaipeng 已提交
1 2 3 4
"""
This code is based on https://github.com/fchollet/keras/blob/master/keras/utils/data_utils.py
"""

5
import os
6 7
import sys
import signal
D
dengkaipeng 已提交
8 9 10 11 12 13 14 15 16 17
import time
import numpy as np
import threading
import multiprocessing
try:
    import queue
except ImportError:
    import Queue as queue


18 19 20 21 22
# handle terminate reader process, do not print stack frame
def _reader_quit(signum, frame):
    print("Reader process exit.")
    sys.exit()

23 24 25 26 27
def _term_group(sig_num, frame):
    print('pid {} terminated, terminate group '
          '{}...'.format(os.getpid(), os.getpgrp()))
    os.killpg(os.getpgid(os.getpid()), signal.SIGKILL)

28
signal.signal(signal.SIGTERM, _reader_quit)
29
signal.signal(signal.SIGINT, _term_group)
30 31


D
dengkaipeng 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
class GeneratorEnqueuer(object):
    """
    Builds a queue out of a data generator.

    Args:
        generator: a generator function which endlessly yields data
        use_multiprocessing (bool): use multiprocessing if True,
            otherwise use threading.
        wait_time (float): time to sleep in-between calls to `put()`.
        random_seed (int): Initial seed for workers,
            will be incremented by one for each workers.
    """

    def __init__(self,
                 generator,
                 use_multiprocessing=False,
                 wait_time=0.05,
                 random_seed=None):
        self.wait_time = wait_time
        self._generator = generator
        self._use_multiprocessing = use_multiprocessing
        self._threads = []
        self._stop_event = None
D
dengkaipeng 已提交
55
        self.queue = None
D
dengkaipeng 已提交
56 57 58
        self._manager = None
        self.seed = random_seed

D
dengkaipeng 已提交
59
    def start(self, workers=1, max_queue_size=10):
D
dengkaipeng 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
        """
        Start worker threads which add data from the generator into the queue.

        Args:
            workers (int): number of worker threads
            max_queue_size (int): queue size
                (when full, threads could block on `put()`)
        """

        def data_generator_task():
            """
            Data generator task.
            """

            def task():
D
dengkaipeng 已提交
75 76
                if (self.queue is not None and
                        self.queue.qsize() < max_queue_size):
D
dengkaipeng 已提交
77
                    generator_output = next(self._generator)
D
dengkaipeng 已提交
78
                    self.queue.put((generator_output))
D
dengkaipeng 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
                else:
                    time.sleep(self.wait_time)

            if not self._use_multiprocessing:
                while not self._stop_event.is_set():
                    with self.genlock:
                        try:
                            task()
                        except Exception:
                            self._stop_event.set()
                            break
            else:
                while not self._stop_event.is_set():
                    try:
                        task()
                    except Exception:
                        self._stop_event.set()
                        break

        try:
            if self._use_multiprocessing:
                self._manager = multiprocessing.Manager()
D
dengkaipeng 已提交
101
                self.queue = self._manager.Queue(maxsize=max_queue_size)
D
dengkaipeng 已提交
102 103 104
                self._stop_event = multiprocessing.Event()
            else:
                self.genlock = threading.Lock()
D
dengkaipeng 已提交
105
                self.queue = queue.Queue()
D
dengkaipeng 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
                self._stop_event = threading.Event()
            for _ in range(workers):
                if self._use_multiprocessing:
                    # Reset random seed else all children processes
                    # share the same seed
                    np.random.seed(self.seed)
                    thread = multiprocessing.Process(target=data_generator_task)
                    thread.daemon = True
                    if self.seed is not None:
                        self.seed += 1
                else:
                    thread = threading.Thread(target=data_generator_task)
                self._threads.append(thread)
                thread.start()
        except:
            self.stop()
            raise

    def is_running(self):
        """
        Returns:
            bool: Whether the worker theads are running.
        """
        return self._stop_event is not None and not self._stop_event.is_set()

    def stop(self, timeout=None):
        """
        Stops running threads and wait for them to exit, if necessary.
        Should be called by the same thread which called `start()`.

        Args:
            timeout(int|None): maximum time to wait on `thread.join()`.
        """
        if self.is_running():
            self._stop_event.set()
        for thread in self._threads:
            if self._use_multiprocessing:
                if thread.is_alive():
144
                    thread.join(timeout)
D
dengkaipeng 已提交
145 146 147 148 149 150 151 152 153
            else:
                thread.join(timeout)
        if self._manager:
            self._manager.shutdown()

        self._threads = []
        self._stop_event = None
        self.queue = None

D
dengkaipeng 已提交
154
    def get(self):
D
dengkaipeng 已提交
155 156 157 158 159 160 161 162
        """
        Creates a generator to extract data from the queue.
        Skip the data if it is `None`.

        # Yields
            tuple of data in the queue.
        """
        while self.is_running():
D
dengkaipeng 已提交
163 164
            if not self.queue.empty():
                inputs = self.queue.get()
D
dengkaipeng 已提交
165 166 167 168
                if inputs is not None:
                    yield inputs
            else:
                time.sleep(self.wait_time)