"""/v1/systemone server for the SearchJev Qwen3.8-27B decision model (Decision Index submission path). The code our full public run used through the kit's `http` engine (Decision Index 0.3, 2026-11-09/10). Board rules it follows (decision-index README): * No truncation: every request is read whole. The prompt budget is the model's context (262,144 tokens); a request that still does not fit gets HTTP 422 with the kit's capacity marker "maximum context length", which the kit records as unsupported (counted wrong). Nothing is ever cut to fit. * One request at a time (single-threaded server), the way the maintainers measure latency. * Every question is answered. A question the model cannot read (more options than the 173-label space) gets the first option with uniform probabilities, exactly as in our local scoring (di_jev.py results); the response's evaluation_trace (stripped by the kit) lists such questions. The request -> prompt path is the one our local tests used: a request is turned into a JEV row exactly as publicbench_build/di_eval/di_jev.py to-jev does (instructions given as an object -> JSON text with indent 1; an empty state -> the same placeholder sentence), then jev_snapshot's PromptBuilder renders it. SharedPrefixPredictor reads the common prefix of a request's questions once. Inference settings (all optional; the defaults are the trained model as tested on 2026-11-08): --layout plain|header header = every question of the request listed before the state --read-twice-max-tokens N write the user turn twice when the single-read prompt has at most N tokens (0 = off) --lora-scale S multiply every LoRA scaling factor before merging the adapter (1 = trained adapter) --temperature-multipliers F per-type multipliers of the run's calibrated temperatures: a JSON object {"choice": m, "noul": m, "score": m} or a refit_calibration.py settings file --noul-floor move P(yes) out of (0.2, 0.8) to 0.801 / 0.199 on the side it leans (JevBench rule) python -m searchjev.server --model . --port 8000 [options] # from the downloaded repo root curl -s localhost:8000/health """ from __future__ import annotations import argparse import json import logging import sys import time from http.server import BaseHTTPRequestHandler, HTTPServer from pathlib import Path from typing import Any, Mapping _PKG = str(Path(__file__).resolve().parent) # searchjev/: holds training/ and shared_prefix.py if _PKG not in sys.path: sys.path.insert(0, _PKG) from training.prompting import PromptTooLong # noqa: E402 from training.schema import jev_row_to_examples # noqa: E402 logger = logging.getLogger("systemone") EMPTY_STATE = "No additional context; the question is in the instructions." # di_jev.py to_jev CAPACITY_MARKER = "maximum context length" # decision_index/engines/http.py MAX_CONTEXT = 262144 # Qwen3.8-27B max_position_embeddings NOUL_FLOOR = 0.801 TYPES = ("choice", "noul", "score") class Capacity(Exception): """The request cannot be read whole (HTTP 422 with the kit's capacity marker).""" class BadRequest(Exception): """Malformed request (HTTP 400).""" # --------------------------------------------------------------------------- request <-> JEV row (as di_jev.py) def _instr(q: Mapping[str, Any]) -> str: i = q.get("instructions") return i if isinstance(i, str) else json.dumps(i, ensure_ascii=False, indent=1) def _placeholder_answer(q: Mapping[str, Any]) -> dict[str, Any]: keys = list(q.get("criteria") or {}) if q["type"] == "noul": return {"type": "noul", "noul": 0.5} return {"type": "choice", "choice": str(keys[0]) if keys else ""} def request_to_row(state: Any, questions: Mapping[str, Any], sample_id: str = "request") -> dict[str, Any]: """One /v1/systemone request -> the JEV row our local tests read (di_jev.py to_jev, without the gold answers).""" if not isinstance(questions, Mapping) or not questions: raise BadRequest("questions must be a non-empty object") qs, ans = {}, {} for k, q in questions.items(): if not isinstance(q, Mapping) or q.get("type") not in ("choice", "noul"): raise BadRequest(f"question {k!r}: type must be 'choice' or 'noul'") q2 = {"type": q["type"], "instructions": _instr(q)} if q.get("criteria") is not None: q2["criteria"] = q["criteria"] qs[str(k)] = q2 ans[str(k)] = _placeholder_answer(q) if state in (None, "", {}, []): state = EMPTY_STATE return {"sample_id": sample_id, "dataset": "systemone", "task": "decision_index/request", "split": "test", "state": state, "questions": qs, "answers": ans, "meta": {}} def commit_noul(p_yes: float) -> float: if 0.2 < p_yes < 0.8: return NOUL_FLOOR if p_yes >= 0.5 else 1.0 - NOUL_FLOOR return p_yes def load_multipliers(spec: str | None) -> dict[str, float]: """JSON object {"choice": m, ...}, or a path to such a file or to a refit_calibration.py settings file.""" if not spec: return {} p = Path(spec) d = json.loads(p.read_text()) if p.is_file() else json.loads(spec) if "per_type" in d: d = {k: v["multiplier"] for k, v in d["per_type"].items()} out = {k: float(v) for k, v in d.items()} bad = [k for k in out if k not in TYPES or not out[k] > 0] if bad: raise ValueError(f"bad temperature multipliers {bad}") return out # --------------------------------------------------------------------------- engine class SystemOneEngine: """Answers one request at a time with a SharedPrefixPredictor (``predictor`` may be injected for tests).""" def __init__(self, model: str | None = None, *, layout: str = "plain", read_twice_max_tokens: int = 0, lora_scale: float = 1.0, temperature_multipliers: Mapping[str, float] | None = None, noul_floor: bool = False, max_context: int = MAX_CONTEXT, device: str = "cuda:0", batch_size: int = 64, max_batch_tokens: int = 131072, served_name: str = "searchjev-27b", predictor: Any = None) -> None: if layout not in ("plain", "header"): raise ValueError(f"layout {layout!r}") self.served_name = served_name self.noul_floor = bool(noul_floor) self.settings = {"model": model, "layout": layout, "read_twice_max_tokens": int(read_twice_max_tokens), "lora_scale": float(lora_scale), "temperature_multipliers": dict(temperature_multipliers or {}), "noul_floor": self.noul_floor, "max_context": int(max_context), "truncation": "never", "batch_size": batch_size, "max_batch_tokens": max_batch_tokens} if predictor is None: import torch from shared_prefix import SharedPrefixPredictor torch.backends.cuda.enable_cudnn_sdp(False) # cuDNN builds a plan per new prompt length (~0.7 s each) predictor = SharedPrefixPredictor(model, device=device, batch_size=batch_size, max_length=max_context, calibration=True, max_batch_tokens=max_batch_tokens, merge_lora=False) n = scale_lora(predictor.model, lora_scale) if hasattr(predictor.model, "merge_and_unload"): # merge (after scaling): no adapter cost per call predictor.model = predictor.model.merge_and_unload() predictor.model.eval() self.settings["lora_layers_scaled"] = n self.pred = predictor pb = predictor.prompt_builder pb.layout = layout pb.read_twice_max_tokens = int(read_twice_max_tokens) if temperature_multipliers: from training.calibration import temperature_for cal = dict(predictor.calibration or {}) base = {qt: temperature_for(cal, qt) for qt in TYPES} for qt, m in temperature_multipliers.items(): cal[qt] = base[qt] * float(m) predictor.calibration = cal self.settings["temperatures"] = {qt: _temperature(predictor.calibration, qt) for qt in TYPES} self.layout = layout self.max_options = predictor.label_space.max_options def decide(self, state: Any, questions: Mapping[str, Any]) -> dict[str, Any]: from training.inference import _qid_of row = request_to_row(state, questions) examples, drops = jev_row_to_examples(row, family="", label_space=self.pred.label_space, require_answer=False) if self.layout == "header": hq = [e.question for e in examples] for e in examples: e.meta = {**(e.meta or {}), "header_questions": hq} n_tokens = [0] enc = self.pred.prompt_builder.encode def counting_encode(ex, perm=None): out = enc(ex, perm) if out.get("truncated"): # PromptBuilder cuts the state (or question) to fit: never allowed here raise PromptTooLong(f"example {ex.id} does not fit whole") n_tokens[0] += len(out["input_ids"]) return out self.pred.prompt_builder.encode = counting_encode try: results = self.pred.decide_batch(examples) if examples else [] except PromptTooLong as exc: raise Capacity(f"request longer than the {CAPACITY_MARKER} ({self.settings['max_context']} tokens): {exc}") finally: self.pred.prompt_builder.encode = enc got = {_qid_of(ex.id, row["sample_id"]): res for ex, res in zip(examples, results)} answers, filled = {}, [] for k, q in row["questions"].items(): res = got.get(k) keys = [str(o) for o in (q.get("criteria") or {})] if q["type"] == "noul": if res is None: filled.append(k) p = 0.5 else: pr = res.probabilities p = float(pr.get("true", pr.get("yes", 0.0))) if self.noul_floor: p = commit_noul(p) answers[k] = {"type": "noul", "noul": p} continue if res is None or not keys: filled.append(k) pr = {o: 1.0 / max(1, len(keys)) for o in keys} else: pr = {o: float(res.probabilities.get(o, 0.0)) for o in keys} z = sum(pr.values()) or 1.0 pr = {o: v / z for o, v in pr.items()} answers[k] = {"type": "choice", "choice": max(pr, key=pr.get) if pr else "", "probabilities": pr} trace = {"dropped": {r: int(n) for r, n in dict(drops).items() if n}, "filled_questions": filled, "read_twice_prompts_total": int(getattr(self.pred.prompt_builder, "n_read_twice", 0))} return {"model": self.served_name, "answers": answers, "usage": {"input_tokens": n_tokens[0]}, "evaluation_trace": trace} def _temperature(cal: Mapping[str, Any] | None, qt: str) -> float: from training.calibration import temperature_for return float(temperature_for(cal, qt)) def scale_lora(model: Any, scale: float) -> int: """Multiply every unmerged LoRA scaling factor by ``scale``; returns the number of LoRA layers seen.""" n = 0 for mod in model.modules(): sc = getattr(mod, "scaling", None) if isinstance(sc, dict) and sc: if float(scale) != 1.0: for k in list(sc): sc[k] = sc[k] * float(scale) n += 1 if float(scale) != 1.0 and n == 0: raise ValueError("--lora-scale given but the model has no unmerged LoRA layers") return n # --------------------------------------------------------------------------- HTTP def make_handler(engine: SystemOneEngine): class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def _send(self, code: int, obj: Any) -> None: body = json.dumps(obj, ensure_ascii=False).encode("utf-8") self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def do_GET(self): # noqa: N802 if self.path.rstrip("/") == "/health": self._send(200, {"status": "ok", "model": engine.served_name, "settings": engine.settings}) else: self._send(404, {"error": "not found"}) def do_POST(self): # noqa: N802 if self.path.rstrip("/") != "/v1/systemone": self._send(404, {"error": "not found"}) return t0 = time.perf_counter() try: n = int(self.headers.get("Content-Length") or 0) req = json.loads(self.rfile.read(n) or b"{}") if not isinstance(req, dict): raise BadRequest("request body must be a JSON object") out = engine.decide(req.get("state"), req.get("questions")) out["evaluation_trace"]["server_ms"] = round(1000 * (time.perf_counter() - t0), 2) self._send(200, out) except Capacity as exc: self._send(422, {"error": str(exc)}) except (BadRequest, json.JSONDecodeError, ValueError) as exc: self._send(400, {"error": f"bad request: {exc}"}) except Exception as exc: # noqa: BLE001 logger.exception("request failed") self._send(500, {"error": f"{type(exc).__name__}: {exc}"}) def log_message(self, fmt, *args): # quiet access log logger.debug("%s - %s", self.address_string(), fmt % args) return Handler def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--model", required=True, help="run dir (adapter + calibration.json) or merged model dir") ap.add_argument("--host", default="127.0.0.1") ap.add_argument("--port", type=int, default=8000) ap.add_argument("--served-name", default="searchjev-27b") ap.add_argument("--layout", default="plain", choices=["plain", "header"]) ap.add_argument("--read-twice-max-tokens", type=int, default=0) ap.add_argument("--lora-scale", type=float, default=1.0) ap.add_argument("--temperature-multipliers", default=None) ap.add_argument("--noul-floor", action="store_true") ap.add_argument("--max-context", type=int, default=MAX_CONTEXT) ap.add_argument("--batch-size", type=int, default=64) ap.add_argument("--max-batch-tokens", type=int, default=131072) ap.add_argument("--settings-out", default=None, help="write the effective settings here (for the submission record)") ap.add_argument("--log-level", default="INFO") a = ap.parse_args(argv) logging.basicConfig(level=a.log_level, format="%(asctime)s %(levelname)s %(name)s: %(message)s") engine = SystemOneEngine(a.model, layout=a.layout, read_twice_max_tokens=a.read_twice_max_tokens, lora_scale=a.lora_scale, temperature_multipliers=load_multipliers(a.temperature_multipliers), noul_floor=a.noul_floor, max_context=a.max_context, batch_size=a.batch_size, max_batch_tokens=a.max_batch_tokens, served_name=a.served_name) logger.info("settings: %s", json.dumps(engine.settings)) if a.settings_out: Path(a.settings_out).write_text(json.dumps(engine.settings, indent=1)) srv = HTTPServer((a.host, a.port), make_handler(engine)) # single-threaded: one request at a time logger.info("serving POST /v1/systemone on %s:%d", a.host, a.port) try: srv.serve_forever() except KeyboardInterrupt: pass return 0 if __name__ == "__main__": raise SystemExit(main())