File size: 7,576 Bytes
5c33f00 | 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 183 184 185 186 187 188 189 190 191 192 | # SPDX-License-Identifier: Apache-2.0
"""Request batching for the HTTP server: ONE device thread owns the model; HTTP handlers submit prepared work items
(a list of host-preprocessed inputs + whether token embeddings are needed) and await a future.
The thread takes the oldest item, waits up to ``window_ms`` for more, merges queued items into one device batch of
<= ``max_batch`` texts (requests larger than ``max_batch`` were split by the submitter), runs
``run(inputs, want_tokens)`` once and hands every item its rows. More than ``depth`` waiting items -> :class:`QueueFull`
(HTTP 429); an item older than ``timeout_s`` when reached -> :class:`QueueTimeout` (HTTP 503). Standard library +
the model 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_embgemma.server.batcher")
class QueueFull(RuntimeError):
pass
class QueueTimeout(RuntimeError):
pass
class ShuttingDown(RuntimeError):
pass
class _Item:
__slots__ = ("ids", "want_tokens", "future", "t0")
def __init__(self, ids, want_tokens):
self.ids = ids
self.want_tokens = want_tokens
self.future: "concurrent.futures.Future" = concurrent.futures.Future()
self.t0 = time.monotonic()
class Batcher:
def __init__(self, run: Callable[[Sequence[Sequence[int]], bool], Any], max_batch: int, window_ms: float,
depth: int, timeout_s: float, name: str = "embgemma-device"):
self._run = run
self.max_batch = int(max_batch)
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.texts = 0
self.busy_s = 0.0
self._thread = threading.Thread(target=self._loop, name=name, daemon=True)
self._thread.start()
# ------------------------------------------------------------------ API
@property
def alive(self) -> bool:
return self._thread.is_alive()
def submit(self, ids: Sequence[Sequence[int]], want_tokens: bool) -> List["concurrent.futures.Future"]:
"""One future per device-sized part of ``ids``; each resolves to ``(sums [n, 768], n_tokens, tokens or None,
device seconds, merged batch size)``."""
parts = [ids[i:i + self.max_batch] for i in range(0, len(ids), self.max_batch)]
items = [_Item(p, want_tokens) for p in parts]
with self._cv:
if self._closing:
raise ShuttingDown("the server is shutting down")
if len(self._q) + len(items) > self.depth and self._q:
raise QueueFull(f"{len(self._q)} device batches are waiting (EMBGEMMA_QUEUE_DEPTH={self.depth}); "
"retry later")
self._q.extend(items)
self._cv.notify()
return [it.future for it in items]
def call(self, fn: Callable[[], Any], timeout: Optional[float] = None) -> Any:
"""Run ``fn()`` on the device thread (start-up, info, 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, "texts": self.texts,
"busy_s": round(self.busy_s, 3), "max_batch": self.max_batch,
"window_ms": self.window_s * 1e3}
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)
# ------------------------------------------------------------------ loop
def _take(self) -> List[_Item]:
"""Under the lock: the oldest item plus the queued items that fit in max_batch texts, waiting at most
window_ms after the oldest item arrived (0: no wait; requests queued during a run merge anyway)."""
first = self._q.popleft()
batch = [first]
n = len(first.ids)
deadline = first.t0 + self.window_s
while n < self.max_batch and not self._closing:
if self._q:
if n + len(self._q[0].ids) > self.max_batch:
break
it = self._q.popleft()
batch.append(it)
n += len(it.ids)
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"(EMBGEMMA_QUEUE_TIMEOUT_S={self.timeout_s:g})"))
continue
live.append(it)
if not live:
continue
ids = [x for it in live for x in it.ids]
want = any(it.want_tokens for it in live)
t0 = time.perf_counter()
try:
pooled, ntok, toks = self._run(ids, want)
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.texts += len(ids)
self.busy_s += dt
o = 0
for it in live:
n = len(it.ids)
res = (pooled[o:o + n], ntok[o:o + n], toks[o:o + n] if toks is not None else None, dt, len(ids))
o += n
if not it.future.done():
it.future.set_result(res)
|