Download code/tt_laya/server/batcher.py from changh95/laya: direct link, hf CLI and curl.
- Browser
- Download file 6.74 kB
-
https://huggingface.co/changh95/laya/resolve/main/code/tt_laya/server/batcher.py
- Command line
-
hf download hf://changh95/laya/code/tt_laya/server/batcher.py
-
curl -L -o batcher.py https://huggingface.co/changh95/laya/resolve/main/code/tt_laya/server/batcher.py
6.74 kB
| # 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} | |
| 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 | |