#!/usr/bin/env python3 """Run private baseline/KAR-PLE Chat quality arms sequentially on one GPU. The original server config is read but never changed. Per-arm config files live in tmpfs and are removed after each arm. This is an offline experiment helper; the production control plane remains independent of Python. """ import argparse import hashlib import json import os from pathlib import Path import signal import subprocess import sys import tempfile import time import urllib.error import urllib.request def sha256(path): digest = hashlib.sha256() with path.open("rb") as file: for chunk in iter(lambda: file.read(8 * 1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def safe_engine_args(values): allowed = {"--pack", "--native", "--ple-gguf", "--max-context", "--kv", "--kv-resident", "--spec", "--spec-min-p", "--expert-cache", "--prefill", "--vram-reserve-mib"} return {flag: values[index + 1] for index, flag in enumerate(values[:-1]) if flag in allowed} def ready(port, process, timeout): deadline = time.monotonic() + timeout url = f"http://127.0.0.1:{port}/health" while time.monotonic() < deadline: if process.poll() is not None: raise RuntimeError(f"server exited during load with code {process.returncode}") try: with urllib.request.urlopen(url, timeout=3) as response: state = json.load(response) if state.get("loaded") and state.get("max_context", 0) > 0: return except (OSError, ValueError): pass time.sleep(2) raise TimeoutError("model did not become ready") def unload(port, key): request = urllib.request.Request( f"http://127.0.0.1:{port}/unload", data=b"{}", headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"}, method="POST") with urllib.request.urlopen(request, timeout=180) as response: if response.status != 200: raise RuntimeError("model unload failed") def arm(name, exe, config, args): cfg = dict(config) cfg["exe"] = str(exe) cfg["args"] = list(config["args"]) if name == "candidate": cfg["args"] += ["--ple-kar", str(args.kar), "--ple-kar-level", "2"] cfg["log"] = str(args.output_dir / f"{name}-engine.log") fd, config_name = tempfile.mkstemp(prefix="strata-next-ab-", suffix=".json", dir=args.tmpfs) temp_config = Path(config_name) process = None model_loaded = False server_log = args.output_dir / f"{name}-server.log" try: with os.fdopen(fd, "w") as file: json.dump(cfg, file) with server_log.open("x") as log: process = subprocess.Popen([ str(args.server_python), str(args.server_script), "--engine", "strata", "--config", str(temp_config), "--host", "127.0.0.1", "--port", str(args.port), ], stdout=log, stderr=subprocess.STDOUT, cwd=config["cwd"], start_new_session=True) ready(args.port, process, args.load_timeout_seconds) model_loaded = True metadata = { "arm": name, "engine_exe_sha256": sha256(exe), "kar_sha256": args.kar_sha256 if name == "candidate" else None, "project_commit": args.project_commit, "engine_settings": safe_engine_args(config["args"]), "experiment": "PLE-only KAR L2 CPU quality arm; all other weights native", "load_order": "baseline then candidate", "shared": args.shared_metadata, } metadata_file = args.output_dir / f"{name}-metadata.json" with metadata_file.open("x") as file: json.dump(metadata, file, indent=2) command = [ sys.executable, str(args.benchmark_script), "--suite", str(args.suite), "--baseline-url", f"http://127.0.0.1:{args.port}/v1/chat/completions", "--baseline-ready-url", f"http://127.0.0.1:{args.port}/health", "--baseline-auth-config", str(temp_config), "--model", config["model_name"], "--repeats", str(args.repeats), "--max-tokens", str(args.max_tokens), "--metadata", str(metadata_file), "--output", str(args.output_dir / f"{name}-chat.json"), ] subprocess.run(command, check=True) unload(args.port, cfg["api_key"]) model_loaded = False finally: if process is not None: if model_loaded and process.poll() is None: try: unload(args.port, cfg["api_key"]) except (OSError, RuntimeError): pass try: os.killpg(process.pid, signal.SIGTERM) except ProcessLookupError: pass try: process.wait(timeout=15) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait(timeout=15) temp_config.unlink(missing_ok=True) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source-config", type=Path, required=True) parser.add_argument("--server-script", type=Path, required=True) parser.add_argument("--server-python", type=Path, required=True) parser.add_argument("--baseline-exe", type=Path, required=True) parser.add_argument("--candidate-exe", type=Path, required=True) parser.add_argument("--kar", type=Path, required=True) parser.add_argument("--kar-sha256", required=True) parser.add_argument("--project-commit", required=True) parser.add_argument("--shared-metadata", type=Path) parser.add_argument("--benchmark-script", type=Path, required=True) parser.add_argument("--compare-script", type=Path, required=True) parser.add_argument("--suite", type=Path, required=True) parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--port", type=int, default=18081) parser.add_argument("--repeats", type=int, default=5) parser.add_argument("--max-tokens", type=int, default=128) parser.add_argument("--load-timeout-seconds", type=float, default=1800) parser.add_argument("--tmpfs", type=Path, default=Path("/dev/shm")) args = parser.parse_args() if args.port < 1024 or args.repeats < 1 or args.max_tokens < 1: parser.error("invalid port, repeats, or max tokens") repository = Path(__file__).resolve().parent.parent args.output_dir = args.output_dir.resolve() if args.output_dir == repository or repository in args.output_dir.parents: parser.error("output directory must be outside the repository") original = json.loads(args.source_config.read_text()) if not original.get("api_key") or not original.get("model_name") or not original.get("cwd"): parser.error("source config lacks required private server fields") if sha256(args.kar) != args.kar_sha256.lower(): raise ValueError("KAR archive SHA-256 does not match the expected digest") args.output_dir.mkdir(parents=True, exist_ok=True) if any(args.output_dir.iterdir()): parser.error("output directory must be empty") raw_metadata = (json.loads(args.shared_metadata.read_text()) if args.shared_metadata else {}) allowed_metadata = {"engine_commit", "gpu", "model_quant", "model_shard_sha256", "profile", "storage", "config_sha256"} args.shared_metadata = {key: raw_metadata[key] for key in allowed_metadata if key in raw_metadata} old_mask = os.umask(0o077) try: for name, exe in (("baseline", args.baseline_exe), ("candidate", args.candidate_exe)): arm(name, exe, original, args) subprocess.run([ sys.executable, str(args.compare_script), str(args.output_dir / "baseline-chat.json"), str(args.output_dir / "candidate-chat.json"), "--output", str(args.output_dir / "paired-comparison.json"), ], check=True) finally: os.umask(old_mask) if __name__ == "__main__": main()