"""HTTP server: POST /v1/systemone, GET /v1/models (the TypeSafe wire format kev.serve speaks; the Decision Index http engine and JevBench's typesafe adapter work against it unchanged). python -m verdin.server --model ./Verdin-4B --port 8903 [--host 0.0.0.0] [--backend auto|cuda|cpu|mlx] Concurrency: HTTP handler threads validate + render + tokenize; one batcher thread owns the model and runs whatever requests are waiting as one batch (dynamic batching: while the GPU is busy, new requests queue up and go together in the next batch; --batch-wait-ms adds an optional collection window). --max-batch 1 gives strictly one request per forward (bitwise-reproducible numbers regardless of load). Errors: malformed / invalid requests -> 422 {"error", "detail"}; requests over a token cap or the device's memory -> 422 with the "too many tokens" capacity marker; internal errors -> 500. """ from __future__ import annotations import argparse import json import queue import sys import threading import time import traceback from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from .render import RequestError, Unsupported, parse_body class _Job: __slots__ = ("enc", "done", "result", "error", "t_in", "t_start", "t_end") def __init__(self, enc): self.enc, self.done, self.result, self.error = enc, threading.Event(), None, None self.t_in = time.perf_counter() class Batcher(threading.Thread): def __init__(self, verdin, max_batch=32, max_batch_tokens=32768, wait_ms=0.0): super().__init__(daemon=True, name="verdin-batcher") self.v, self.q = verdin, queue.Queue() self.max_batch, self.max_tokens, self.wait = max_batch, max_batch_tokens, wait_ms / 1000.0 self.stats = {"batches": 0, "requests": 0, "max_batch_seen": 0, "errors": 0} def submit(self, enc): job = _Job(enc) self.q.put(job) job.done.wait() return job def _collect(self): batch = [self.q.get()] tokens = batch[0].enc.n_tokens deadline = time.perf_counter() + self.wait while len(batch) < self.max_batch and tokens < self.max_tokens: try: left = deadline - time.perf_counter() job = self.q.get(timeout=left) if left > 0 else self.q.get_nowait() except queue.Empty: break batch.append(job); tokens += job.enc.n_tokens return batch def run(self): while True: batch = self._collect() t = time.perf_counter() for j in batch: j.t_start = t try: results = self.v.run([j.enc for j in batch]) for j, r in zip(batch, results): if r.error is not None: # this request alone does not fit the device's memory j.error = r.error else: j.result = r except Exception as e: # noqa: BLE001 - report, keep serving traceback.print_exc() self.stats["errors"] += 1 for j in batch: j.error = e try: self.v.engine.sync() except Exception: # noqa: BLE001 - never let the batcher thread die (callers would wait forever) traceback.print_exc() t_end = time.perf_counter() self.stats["batches"] += 1; self.stats["requests"] += len(batch) self.stats["max_batch_seen"] = max(self.stats["max_batch_seen"], len(batch)) for j in batch: j.t_end = t_end j.done.set() class _Server(ThreadingHTTPServer): daemon_threads = True request_queue_size = 256 # listen backlog (set before bind/listen): concurrency-32 clients must not be refused allow_reuse_address = True def make_handler(v, batcher, served_name): class H(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" server_version = "verdin" def log_message(self, *args): pass def send(self, code, obj): b = json.dumps(obj).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(b))) self.end_headers() self.wfile.write(b) def do_GET(self): path = self.path.split("?")[0].rstrip("/") if path == "/v1/models": info = v.info() eng = info["engine"] if eng.get("device", "").startswith("cuda"): import torch eng["memory_allocated_bytes"] = torch.cuda.memory_allocated() eng["max_memory_allocated_bytes"] = torch.cuda.max_memory_allocated() card = {**info, "id": served_name, "object": "model", "owned_by": "verdin", "aliases": ["kev-latest", "jev-latest"], "server": {**batcher.stats, "max_batch": batcher.max_batch, "max_batch_tokens": batcher.max_tokens, "batch_wait_ms": batcher.wait * 1000}} return self.send(200, {"object": "list", "data": [card], "models": [card]}) if path in ("/health", "/healthz"): return self.send(200, {"ok": True}) self.send(404, {"error": f"no route {self.path}"}) def do_POST(self): t0 = time.perf_counter() path = self.path.split("?")[0].rstrip("/") n = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(n) if n else b"" if path != "/v1/systemone": return self.send(404, {"error": f"no route {self.path}"}) try: body = parse_body(raw) enc = v.encode(body) except Unsupported as e: return self.send(422, {"error": str(e), "detail": str(e)}) except RequestError as e: return self.send(422, {"error": str(e), "detail": str(e)}) job = batcher.submit(enc) if job.error is not None: if isinstance(job.error, RequestError): return self.send(422, {"error": str(job.error), "detail": str(job.error)}) return self.send(500, {"error": f"internal error: {type(job.error).__name__}: {job.error}"}) ans = v.answers(enc, job.result) model = body.get("model") if isinstance(body.get("model"), str) else served_name self.send(200, {"model": model, "answers": ans, "usage": {"input_tokens": enc.n_tokens, "output_tokens": 0}, "latency_ms": round(1000 * (time.perf_counter() - t0), 2), "compute_ms": round(1000 * (job.t_end - job.t_start), 2)}) return H def main(argv=None): ap = argparse.ArgumentParser(description="Verdin /v1/systemone server") ap.add_argument("--model", required=True, help="converted Verdin checkpoint directory") ap.add_argument("--host", default="127.0.0.1", help="0.0.0.0 to serve the LAN") ap.add_argument("--port", type=int, default=8903) ap.add_argument("--backend", default="auto", help="auto | cuda | cpu | mlx (auto: cuda, else mlx on Apple silicon, else cpu)") ap.add_argument("--device", default=None, help="e.g. cuda:0 (default: the backend's)") ap.add_argument("--dtype", default="auto", help="bf16 | fp32 | auto (= the checkpoint's)") ap.add_argument("--name", default=None, help="model id reported by /v1/models (default: the checkpoint's model_name)") ap.add_argument("--max-batch", type=int, default=32, help="requests per batch (1 = no cross-request batching)") ap.add_argument("--max-batch-tokens", type=int, default=32768) ap.add_argument("--batch-wait-ms", type=float, default=0.0) ap.add_argument("--prefix-cache", type=int, default=4, help="states kept across requests (0 = off)") ap.add_argument("--prefix-cache-min-tokens", type=int, default=384) ap.add_argument("--prefill-chunk", type=int, default=0) ap.add_argument("--max-sweep-tokens", type=int, default=0) ap.add_argument("--max-sweep-rows", type=int, default=256) ap.add_argument("--attn-chunk-mb", type=int, default=0) ap.add_argument("--gdr", default="auto", choices=["auto", "fla", "torch"]) ap.add_argument("--branch-gdr", default="recurrent", choices=["chunk", "recurrent"]) # recurrent: same results as chunk on the validation suites, faster ap.add_argument("--conv", default="auto", choices=["auto", "kernel", "torch"]) ap.add_argument("--sdpa", default="auto", choices=["auto", "math"]) ap.add_argument("--threads", type=int, default=0, help="CPU threads (cpu backend)") ap.add_argument("--cuda-graphs", action="store_true", help="reserved (phase B)") ap.add_argument("--no-warmup", action="store_true") a = ap.parse_args(argv) from .core import Verdin t = time.time() v = Verdin.from_pretrained(a.model, backend=a.backend, device=a.device, dtype=a.dtype, prefix_cache=a.prefix_cache, prefix_cache_min_tokens=a.prefix_cache_min_tokens, prefill_chunk=a.prefill_chunk, max_sweep_tokens=a.max_sweep_tokens, max_sweep_rows=a.max_sweep_rows, attn_chunk_mb=a.attn_chunk_mb, gdr=a.gdr, branch_gdr=a.branch_gdr, conv=a.conv, sdpa=a.sdpa, threads=a.threads, cuda_graphs=a.cuda_graphs) if not a.no_warmup: v.engine.warmup() name = a.name or v.name batcher = Batcher(v, a.max_batch, a.max_batch_tokens, a.batch_wait_ms) batcher.start() srv = _Server((a.host, a.port), make_handler(v, batcher, name)) print(f"verdin: serving {name} from {a.model} on {a.host}:{a.port} ({json.dumps(v.engine.describe())}; " f"render {json.dumps(v.cfg.render)}; loaded in {time.time() - t:.1f} s)", flush=True) try: srv.serve_forever() except KeyboardInterrupt: pass return 0 if __name__ == "__main__": sys.exit(main())