"""Serve DeepEdu-Decision over ``POST /v1/systemone`` (the Jev Decision Index wire format):: python -m deepedu_decision.serve --model --port 9100 Request: ``{"state", "questions"}``; other fields are ignored. Response: ``{"model", "answers": {key: {"type": "choice", "choice", "probabilities"} | {"type": "noul", "noul"}}, "scores": {key: {option: raw head score}}, "usage": {"wall_ms", "queue_ms", "batch_rows", ...}}``. ``GET /health`` returns the model, the limits and the current queue depth. Dynamic batching: request threads enqueue their request; one GPU worker takes the queue in arrival order. It waits up to ``--batch_wait_ms`` after the first request for more, up to ``--max_batch_rows`` requests / ``--max_batch_questions`` questions, and scores them together in forwards of at most ``--token_budget`` tokens. A batch-wide failure (CUDA out-of-memory) re-runs its requests one at a time, so only the request that cannot fit fails. One GPU, no scaling, so every limit is enforced up front: - **Admission:** at most ``--max_pending`` requests are in flight (running plus queued); the next one gets HTTP 503 with ``Retry-After`` straight away. A request still queued after ``--queue_timeout`` seconds also gets 503. - **Context:** every prefill (state + one question) must fit ``--max_length`` tokens; a request carries at most ``--max_questions`` questions and ``--max_body_bytes`` bytes. Each breach, and a CUDA out-of-memory on the request alone, is HTTP 422 (413 for the body) whose body contains ``maximum context length``. A question type other than choice/noul, or too many options, is also 422. - A malformed body is 400. """ from __future__ import annotations import argparse import collections import json import threading import time import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Any import torch from .model import DecisionModel, format_answers CAPACITY = "maximum context length" # clients read this marker as "request does not fit" LIMITS = ("max_length", "token_budget", "max_questions", "max_body_bytes", "max_pending", "queue_timeout", "max_batch_rows", "max_batch_questions", "batch_wait_ms") def parse_args(argv=None): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--model", required=True, help="checkpoint: Hub id or local package directory") p.add_argument("--revision", default=None) p.add_argument("--name", default="BunGPT-DeepEdu-Decision-4B-Open", help="model name returned in responses") p.add_argument("--host", default="0.0.0.0") p.add_argument("--port", type=int, required=True) p.add_argument("--token_budget", type=int, default=16384, help="real tokens per forward") p.add_argument("--max_length", type=int, default=None, help="longest prefill (default: --token_budget)") p.add_argument("--max_questions", type=int, default=16, help="questions per request") p.add_argument("--max_body_bytes", type=int, default=1 << 20, help="request body size") p.add_argument("--max_pending", type=int, default=64, help="requests in flight, running plus queued") p.add_argument("--queue_timeout", type=float, default=30.0, help="seconds a request may stay queued") p.add_argument("--max_batch_rows", type=int, default=8, help="requests per GPU batch") p.add_argument("--max_batch_questions", type=int, default=16, help="questions per GPU batch") p.add_argument("--batch_wait_ms", type=float, default=5.0, help="wait after a batch's first request") p.add_argument("--attention", choices=("auto", "flash", "sdpa"), default="auto", help="auto: flash-attn when installed, else sdpa") p.add_argument("--device", default="cuda", help="CUDA device, e.g. cuda:0") p.add_argument("--no_fork", action="store_true", help="score each question with its own copy of the state instead of the fork tree") p.add_argument("--cache_mb", type=int, default=0, help="cross-request prefix cache cap in MB of GPU memory (fork path; 0 = off)") p.add_argument("--cache_every", type=int, default=1024, help="prefix cache checkpoint spacing in tokens") a = p.parse_args(argv) a.max_length = a.max_length or a.token_budget if a.max_length > a.token_budget: p.error("--max_length must not exceed --token_budget") if a.max_questions > a.max_batch_questions: p.error("--max_questions must not exceed --max_batch_questions") return a class Job: def __init__(self, row: dict[str, Any]): self.row = row self.arrived = time.perf_counter() self.started = self.arrived self.batch_rows = 0 self.code = 0 self.body: dict[str, Any] = {} self.done = threading.Event() def finish(self, code: int, body: dict[str, Any]) -> None: self.code, self.body = code, body self.done.set() class Batcher: """FIFO queue of jobs and the one thread that runs them on the GPU.""" def __init__(self, model: DecisionModel, a): self.model, self.a, self.name = model, a, model.name self.queue: collections.deque[Job] = collections.deque() self.cv = threading.Condition() self.in_flight = 0 threading.Thread(target=self.loop, daemon=True).start() def submit(self, row: dict[str, Any]) -> Job | None: """The queued job, or None when ``--max_pending`` requests are already in flight.""" with self.cv: if self.in_flight >= self.a.max_pending: return None self.in_flight += 1 job = Job(row) self.queue.append(job) self.cv.notify() return job def take(self) -> list[Job]: a = self.a with self.cv: while not self.queue: self.cv.wait() deadline = time.perf_counter() + a.batch_wait_ms / 1000 jobs, questions = [], 0 while True: while self.queue and len(jobs) < a.max_batch_rows: nq = len(self.queue[0].row["questions"]) if jobs and questions + nq > a.max_batch_questions: return jobs jobs.append(self.queue.popleft()) questions += nq left = deadline - time.perf_counter() if len(jobs) >= a.max_batch_rows or left <= 0: return jobs self.cv.wait(left) def loop(self): while True: jobs = self.take() now = time.perf_counter() live = [] for job in jobs: if now - job.arrived > self.a.queue_timeout: self.done(job, 503, {"error": f"server busy: queued over {self.a.queue_timeout}s"}) else: job.started, job.batch_rows = now, len(jobs) live.append(job) if live: self.run(live) def run(self, jobs: list[Job]) -> None: cache = self.model.engine.cache hit0 = cache.stats["hit_tokens"] if cache is not None else 0 try: results = self.model.run([j.row for j in jobs]) except Exception as e: # one bad row must not fail its batch-mates: re-run each alone if isinstance(e, torch.cuda.OutOfMemoryError): torch.cuda.empty_cache() if len(jobs) > 1: for job in jobs: job.batch_rows = 1 self.run([job]) return if isinstance(e, torch.cuda.OutOfMemoryError): return self.done(jobs[0], 422, {"error": f"{CAPACITY}: CUDA out of memory"}) return self.done(jobs[0], 400, {"error": f"bad request: {type(e).__name__}: {e}"}) end = time.perf_counter() hit = (cache.stats["hit_tokens"] - hit0) if cache is not None else 0 for job, result in zip(jobs, results): if not result.ok: reason = result.error or f"questions over the token budget: {result.skipped}" self.done(job, 422, {"error": f"{CAPACITY} (max_length {self.a.max_length}) or unsupported " f"request: {reason}"}) else: self.done(job, 200, {"model": self.name, "answers": format_answers(job.row["questions"], result), "scores": result.scores, "usage": {"wall_ms": round((end - job.started) * 1000, 1), "queue_ms": round((job.started - job.arrived) * 1000, 1), "batch_rows": job.batch_rows, "input_tokens": result.input_tokens, "prefills": result.prefills, "cache_hit_tokens": hit}}) def done(self, job: Job, code: int, body: dict[str, Any]) -> None: with self.cv: self.in_flight -= 1 job.finish(code, body) def main(argv=None): a = parse_args(argv) model = DecisionModel.from_pretrained( a.model, a.device, revision=a.revision, name=a.name, fork=not a.no_fork, cache_mb=a.cache_mb, cache_every=a.cache_every, token_budget=a.token_budget, max_length=a.max_length, attention=a.attention) runner, name, forked = model.engine, a.name, model.engine.fork limits = {k: getattr(a, k) for k in LIMITS} batcher = Batcher(model, a) class Handler(BaseHTTPRequestHandler): def reply(self, code: int, body: dict, headers: dict | None = None) -> None: data = json.dumps(body, ensure_ascii=False).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) for k, v in (headers or {}).items(): self.send_header(k, v) self.end_headers() self.wfile.write(data) def do_GET(self): if self.path.rstrip("/") == "/health": self.reply(200, {"status": "ok", "model": name, "limits": limits, "fork": forked, "readout": model.readout, "cache": getattr(getattr(runner, "cache", None), "stats", None), "in_flight": batcher.in_flight}) else: self.reply(404, {"error": "not found"}) def do_POST(self): if self.path.rstrip("/") != "/v1/systemone": return self.reply(404, {"error": "not found"}) size = int(self.headers.get("Content-Length", 0)) if size > a.max_body_bytes: self.close_connection = True # the unread body would corrupt a kept-alive connection return self.reply(413, {"error": f"{CAPACITY}: body {size} bytes > {a.max_body_bytes}"}) try: body = json.loads(self.rfile.read(size)) state, questions = body["state"], body["questions"] if not isinstance(questions, dict) or not questions: raise ValueError("questions must be a non-empty object") except (ValueError, KeyError, TypeError) as e: return self.reply(400, {"error": f"bad request: {e}"}) if len(questions) > a.max_questions: return self.reply(422, {"error": f"{CAPACITY}: {len(questions)} questions > {a.max_questions}"}) run_id = uuid.uuid4().hex job = batcher.submit({"id": run_id, "state": state, "questions": questions}) if job is None: return self.reply(503, {"error": f"server busy: {a.max_pending} requests in flight"}, {"Retry-After": "1"}) job.done.wait() self.reply(job.code, job.body, {"Retry-After": "1"} if job.code == 503 else None) def log_message(self, fmt, *args): print(json.dumps({"event": "request", "client": self.client_address[0], "line": fmt % args}), flush=True) class Server(ThreadingHTTPServer): daemon_threads = True request_queue_size = 1024 # listen backlog; the stdlib's 5 resets connections under bursts server = Server((a.host, a.port), Handler) print(json.dumps({"event": "ready", "model": name, "source": model.source, "temperature": model.temperature, "readout": model.readout, "attention": runner.attention, "port": a.port, "fork": forked, "cache_mb": a.cache_mb if forked else 0, "limits": limits}), flush=True) server.serve_forever() if __name__ == "__main__": main()