File size: 6,735 Bytes
f882f26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# SPDX-License-Identifier: Apache-2.0
"""Request batching for the HTTP server: ONE device thread owns the model; HTTP handlers submit prepared work (the
model rows of one request) and await a future.

The thread takes the oldest item, waits up to ``window_ms`` for more, merges queued items into one engine call of
<= ``max_states`` states (a request larger than that is one item on its own), runs ``run(rows)`` once (the engine
packs the rows into device launches of <= 20 row tiles) and hands every item its slice. More than ``depth`` waiting
items -> :class:`QueueFull` (HTTP 429); an item older than ``timeout_s`` when reached -> :class:`QueueTimeout`
(HTTP 503). Standard library only."""
from __future__ import annotations

import concurrent.futures
import logging
import threading
import time
from collections import deque
from typing import Any, Callable, Deque, List, Optional, Sequence

__all__ = ["Batcher", "QueueFull", "QueueTimeout", "ShuttingDown"]

LOG = logging.getLogger("tt_laya.server.batcher")


class QueueFull(RuntimeError):
    pass


class QueueTimeout(RuntimeError):
    pass


class ShuttingDown(RuntimeError):
    pass


class _Item:
    __slots__ = ("rows", "states", "future", "t0")

    def __init__(self, rows, states):
        self.rows = rows
        self.states = states
        self.future: "concurrent.futures.Future" = concurrent.futures.Future()
        self.t0 = time.monotonic()


class Batcher:
    def __init__(self, run: Callable[[List[Any]], Any], max_states: int, window_ms: float, depth: int,
                 timeout_s: float, name: str = "laya-device"):
        self._run = run
        self.max_states = int(max_states)
        self.window_s = float(window_ms) / 1e3
        self.depth = int(depth)
        self.timeout_s = float(timeout_s)
        self._q: Deque[_Item] = deque()
        self._cv = threading.Condition()
        self._closing = False
        self._calls: Deque = deque()
        self.batches = 0
        self.items = 0
        self.rows = 0
        self.busy_s = 0.0
        self._thread = threading.Thread(target=self._loop, name=name, daemon=True)
        self._thread.start()

    def submit(self, rows: List[Any], states: int) -> "concurrent.futures.Future":
        """One future for the rows of one request; resolves to ``(logits, acts, device_s, merged_rows)``."""
        it = _Item(rows, states)
        with self._cv:
            if self._closing:
                raise ShuttingDown("the server is shutting down")
            if len(self._q) >= self.depth:
                raise QueueFull(f"{len(self._q)} requests are waiting (LAYA_QUEUE_DEPTH={self.depth}); retry later")
            self._q.append(it)
            self._cv.notify()
        return it.future

    def call(self, fn: Callable[[], Any], timeout: Optional[float] = None) -> Any:
        """Run ``fn()`` on the device thread (start-up, shutdown) and return its result."""
        fut: "concurrent.futures.Future" = concurrent.futures.Future()
        with self._cv:
            self._calls.append((fn, fut))
            self._cv.notify()
        return fut.result(timeout)

    def status(self):
        with self._cv:
            return {"waiting": len(self._q), "batches": self.batches, "items": self.items, "rows": self.rows,
                    "busy_s": round(self.busy_s, 3), "max_states": self.max_states,
                    "window_ms": self.window_s * 1e3}

    @property
    def alive(self) -> bool:
        return self._thread.is_alive()

    def close(self, fn: Optional[Callable[[], Any]] = None, timeout: float = 60.0) -> None:
        with self._cv:
            self._closing = True
            while self._q:
                it = self._q.popleft()
                if not it.future.done():
                    it.future.set_exception(ShuttingDown("the server is shutting down"))
            self._cv.notify()
        if fn is not None:
            try:
                self.call(fn, timeout)
            except Exception:  # noqa: BLE001
                LOG.exception("close function failed")
        with self._cv:
            self._calls.append((None, None))
            self._cv.notify()
        self._thread.join(timeout)

    def _take(self) -> List[_Item]:
        first = self._q.popleft()
        batch = [first]
        n = first.states
        deadline = first.t0 + self.window_s
        while n < self.max_states and not self._closing:
            if self._q:
                if n + self._q[0].states > self.max_states:
                    break
                it = self._q.popleft()
                batch.append(it)
                n += it.states
                continue
            left = deadline - time.monotonic()
            if left <= 0:
                break
            self._cv.wait(left)
        return batch

    def _loop(self) -> None:
        while True:
            with self._cv:
                while not self._q and not self._calls:
                    self._cv.wait()
                if self._calls:
                    fn, fut = self._calls.popleft()
                    if fn is None:
                        return
                    batch = None
                else:
                    batch = self._take()
            if batch is None:
                try:
                    fut.set_result(fn())
                except BaseException as e:  # noqa: BLE001
                    fut.set_exception(e)
                continue
            now = time.monotonic()
            live = []
            for it in batch:
                if it.future.cancelled():
                    continue
                if now - it.t0 > self.timeout_s:
                    it.future.set_exception(QueueTimeout(f"waited {now - it.t0:.1f} s in the queue "
                                                         f"(LAYA_QUEUE_TIMEOUT_S={self.timeout_s:g})"))
                    continue
                live.append(it)
            if not live:
                continue
            rows = [r for it in live for r in it.rows]
            t0 = time.perf_counter()
            try:
                logits, acts = self._run(rows) if rows else ([], [])
            except BaseException as e:  # noqa: BLE001
                for it in live:
                    if not it.future.done():
                        it.future.set_exception(e)
                continue
            dt = time.perf_counter() - t0
            self.batches += 1
            self.items += len(live)
            self.rows += len(rows)
            self.busy_s += dt
            o = 0
            for it in live:
                n = len(it.rows)
                if not it.future.done():
                    it.future.set_result((logits[o:o + n], acts[o:o + n], dt, len(rows)))
                o += n