# 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)