"""Batched GPU inference server for Rust `selfplay`/`archbench` (`net=tcp://127.0.0.1:PORT`). Zero-Python-loop flat protocol + Cross-Thread Dynamic Micro-Batching: Rust's `BatchClient` sends per-thread flat batches (`vloss` waves). A dedicated GPU worker thread coalesces concurrent client batches arriving within `--wait-ms` (up to `--max-batch` items) into a single super-batch, runs one bf16 (optionally `torch.compile`d) forward pass on CUDA, and scatters results back to waiting threads. python infer_server.py --dir runs/phase3-final-5m-v3-soup --port 18400 [--max-batch 512 --wait-ms 0.5 --compile] """ import argparse import queue import socket import struct import sys import threading import time import numpy as np import torch from model import ACT_F, BUCKETS, ENT_F, GLOB_F, NO_ENT, Tx, hl_gauss_to_logit, load_dir from train import device as pick_device def recv_exact(conn, n): buf = bytearray(n) view = memoryview(buf) got = 0 while got < n: r = conn.recv_into(view[got:]) if r == 0: raise EOFError("client closed") got += r return buf def pack_handshake(net): if isinstance(net, Tx): emb = net.emb.table().detach().float().cpu().contiguous() dim = emb.shape[1] trunk = net.trunk1.out_features bw = net.belief.weight.detach().float().cpu().contiguous() bb = net.belief.bias.detach().float().cpu().contiguous() has_bel = 1 else: emb = net.emb.weight.detach().float().cpu().contiguous() dim = emb.shape[1] trunk = net.trunk2.out_features has_bel = 1 if net.belief is not None else 0 bw = net.belief.weight.detach().float().cpu().contiguous() if has_bel else torch.zeros(0) bb = net.belief.bias.detach().float().cpu().contiguous() if has_bel else torch.zeros(0) hdr = struct.pack(" 0.0 and tot_B < self.max_batch: deadline = time.perf_counter() + self.wait_s while tot_B < self.max_batch: rem = deadline - time.perf_counter() if rem <= 0.0: break try: nxt = self.q.get(timeout=rem) except queue.Empty: break if nxt is None: self.stop_ev.set() break group.append(nxt) tot_B += nxt.B else: while tot_B < self.max_batch: try: nxt = self.q.get_nowait() except queue.Empty: break if nxt is None: self.stop_ev.set() break group.append(nxt) tot_B += nxt.B try: self._run_superbatch(group) except Exception as e: for r in group: r.err = e r.ev.set() def handle_client(conn, engine, handshake): try: conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) conn.sendall(handshake) while True: hdr = recv_exact(conn, 12) B, w_e, w_a = struct.unpack(" 0: print( f"INFER_SERVER client done: {engine.items} evals in {engine.gpu_batches} gpu_batches " f"({engine.reqs} reqs, avg_gpu_B={engine.items / engine.gpu_batches:.1f}, " f"coalesce={engine.reqs / engine.gpu_batches:.2f}x)", flush=True, ) conn.close() def main(): ap = argparse.ArgumentParser() ap.add_argument("--dir", required=True, help="run folder with net.pt and arch.json") ap.add_argument("--host", default="127.0.0.1") ap.add_argument("--port", type=int, default=18400) ap.add_argument("--amp", type=int, default=1) ap.add_argument("--max-batch", type=int, default=512, help="max super-batch items across concurrent threads") ap.add_argument("--wait-ms", type=float, default=0.5, help="micro-batch coalescing window in ms") ap.add_argument("--compile", action="store_true") args = ap.parse_args() dev = pick_device() if dev.type == "cuda": torch.set_float32_matmul_precision("high") net = load_dir(args.dir, dev).eval() handshake = pack_handshake(net) if args.compile and dev.type == "cuda": net = torch.compile(net, dynamic=True) engine = InferEngine(net, dev, bool(args.amp), max_batch=args.max_batch, wait_ms=args.wait_ms) srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind((args.host, args.port)) port = srv.getsockname()[1] srv.listen(128) print( f"INFER_SERVER ready tcp://{args.host}:{port} device={dev} amp={engine.amp} " f"max_batch={args.max_batch} wait_ms={args.wait_ms} compile={args.compile}", flush=True, ) t0 = time.time() try: while True: conn, _ = srv.accept() threading.Thread(target=handle_client, args=(conn, engine, handshake), daemon=True).start() except KeyboardInterrupt: pass finally: engine.stop() dt = max(time.time() - t0, 1e-6) gb = max(engine.gpu_batches, 1) print( f"INFER_SERVER stopped: {engine.items} evals in {engine.gpu_batches} gpu_batches " f"(avg_gpu_B={engine.items / gb:.1f}, {engine.items / dt:.0f} eval/s)", flush=True, ) srv.close() if __name__ == "__main__": main()