"""Step 2 (Lightweight Build): Parity Gate + Disjoint VAL_24 Sweep & Speed Verification.""" from __future__ import annotations import json import re import sys import time from pathlib import Path from typing import Any, Dict, List ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\inkling2-mini-wsp") sys.path.insert(0, str(ROOT)) sys.path.insert(0, r"C:\Users\jhjwi\.gemini\antigravity\scratch\wsp-5model-pipeline") sys.path.insert(0, r"C:\Users\jhjwi\.gemini\antigravity\scratch\qwen35-deepthought-stem-wsp") import disjoint_inkling2_data as dd # noqa: E402 import wsp_tasks_9subspaces as tasks # noqa: E402 from evaluate_deepthought import _extract_math_answer, _extract_mcq_letter, _sympy_equiv # noqa: E402 from inkling2_lite_router import ( # noqa: E402 LITE_ADAPTER_DIR, LITE_ADAPTER_NAMES, Inkling2LiteRouter, LitePreset, ) from validate_inkling2_sites import BASE_URL, ManagedWspServer, openai_chat_check, vram_mb # noqa: E402 sys.stdout.reconfigure(encoding="utf-8", line_buffering=True) OUT_PATH = ROOT / "val24_lite_results.json" def run_lite_parity_gate(router: Inkling2LiteRouter, val24: Dict[str, Any]) -> Dict[str, Any]: """Compare native /v1/chat/completions vs single-call pass-through splitter on vnl_0, vmath_0, vre_0.""" router.reset_kv_cache() checks = [] # 1. vnl_0 it_nl = val24["val_nl2bash_6"][0] m_nl = [{"role": "user", "content": f"Execute a single Linux shell command via `exec` to accomplish this task: {it_nl['query']}"}] a_nl = openai_chat_check(m_nl, tools=tasks.WORKER_TOOLS, eff=0.2, max_tokens=512) b_nl = router.chat_completion(m_nl, tools=tasks.WORKER_TOOLS, max_tokens=512, reasoning_effort=0.2, mode="base") ok_nl = (a_nl["content"] == b_nl["content"]) and (a_nl["parsed_tcs"] == b_nl["parsed_tool_calls"]) checks.append({ "id": it_nl["id"], "ok": ok_nl, "openai_content": a_nl["content"][:120], "router_content": b_nl["content"][:120], "openai_tcs": a_nl["parsed_tcs"], "router_tcs": b_nl["parsed_tool_calls"], }) # 2. vmath_0 it_math = val24["val_math_7"][0] m_math = [{"role": "user", "content": f"Solve the following mathematics problem carefully. Put your final simplified answer inside \\boxed{{}}.\n\n{it_math['problem']}"}] a_math = openai_chat_check(m_math, tools=None, eff=0.2, max_tokens=1536) b_math = router.chat_completion(m_math, tools=None, max_tokens=1536, reasoning_effort=0.2, mode="base") ans_a = _extract_math_answer(a_math["content"], "") ans_b = _extract_math_answer(b_math["content"], b_math["reasoning"]) ok_math = ( bool(a_math["content"]) and bool(b_math["content"]) and _sympy_equiv(ans_a, ans_b) and _sympy_equiv(ans_b, str(it_math["answer"])) and (a_math["parsed_tcs"] == b_math["parsed_tool_calls"] == []) ) checks.append({ "id": "vmath_0", "ok": ok_math, "openai_ans": ans_a, "router_ans": ans_b, "openai_content": a_math["content"][:160], "router_content": b_math["content"][:160], "openai_tcs": a_math["parsed_tcs"], "router_tcs": b_math["parsed_tool_calls"], }) # 3. vre_0 it_re = val24["val_restraint_exec_3"][0] a_re = openai_chat_check(it_re["messages"], tools=it_re["tools"], eff=0.2, max_tokens=512) b_re = router.chat_completion(it_re["messages"], tools=it_re["tools"], max_tokens=512, reasoning_effort=0.2, mode="base") ok_re = (a_re["content"] == b_re["content"]) and (a_re["parsed_tcs"] == b_re["parsed_tool_calls"]) checks.append({ "id": it_re["id"], "ok": ok_re, "openai_content": a_re["content"][:160], "router_content": b_re["content"][:160], "openai_tcs": a_re["parsed_tcs"], "router_tcs": b_re["parsed_tool_calls"], }) all_ok = all(c["ok"] for c in checks) n_pass = sum(c["ok"] for c in checks) print(f"[Parity Gate (vnl_0, vmath_0, vre_0)] {'PASS' if all_ok else 'FAIL'} ({n_pass}/3)", flush=True) for c in checks: print(f" {c['id']}: ok={c['ok']} tcs_match={c['openai_tcs']==c['router_tcs']}", flush=True) return {"passed": all_ok, "pass_count": n_pass, "checks": checks} def eval_val24_lite(router: Inkling2LiteRouter, val24: Dict[str, Any], arm_name: str) -> Dict[str, Any]: router.reset_kv_cache() t0 = time.time() records: List[Dict[str, Any]] = [] done = 0 TOTAL = 24 def track(rec: Dict[str, Any]) -> None: nonlocal done records.append(rec) done += 1 if done % 8 == 0 or done == TOTAL: el = time.time() - t0 eta = (TOTAL - done) * (el / done) p = sum(1 for r in records if r["passed"]) print( f" [{arm_name:14s} {done:2d}/{TOTAL}] pass={p}/{done} | srv_tps={rec['srv_tps']} | elapsed={el:.1f}s ETA={eta:.1f}s", flush=True, ) for idx, it in enumerate(val24["val_math_7"]): msgs = [{"role": "user", "content": f"Solve the following mathematics problem carefully. Put your final simplified answer inside \\boxed{{}}.\n\n{it['problem']}"}] res = router.chat_completion(msgs, tools=None, max_tokens=1536, reasoning_effort=0.2, mode="wsp") ok = _sympy_equiv(_extract_math_answer(res["content"], res["reasoning"]), str(it["answer"])) cut = (not res["content"]) and res["finish_reason"] == "length" track({"grp": "val_math", "id": f"vmath_{idx}", "passed": ok, "cut": cut, "tok": res["comp_tok"], "tps": res["tps"], "srv_tps": res["server_decode_tps"], "regime": res["regime"]}) for it in val24["val_mcq_4"]: opts = it["options"] opt_lines = "\n".join(f"({chr(65 + i)}) {t}" for i, t in enumerate(opts)) prompt = f"Answer the following multiple-choice {it['subject']} question. End your final response with `Answer: (X)` where X is the single capital letter A-{chr(64 + len(opts))}.\n\nQuestion: {it['question']}\n\n{opt_lines}" res = router.chat_completion([{"role": "user", "content": prompt}], tools=None, max_tokens=1024, reasoning_effort=0.2, mode="wsp") pred = _extract_mcq_letter(res["content"], res["reasoning"], len(opts)) or "" ok = (pred == it["answer"]) and bool(res["content"]) cut = (not res["content"]) and res["finish_reason"] == "length" track({"grp": "val_mcq", "id": it["id"], "passed": ok, "cut": cut, "tok": res["comp_tok"], "tps": res["tps"], "srv_tps": res["server_decode_tps"], "regime": res["regime"]}) for it in val24["val_nl2bash_6"]: prompt = f"Execute a single Linux shell command via `exec` to accomplish this task: {it['query']}" res = router.chat_completion([{"role": "user", "content": prompt}], tools=tasks.WORKER_TOOLS, max_tokens=512, reasoning_effort=0.2, mode="wsp") tcs = res["parsed_tool_calls"] cmd = str(tcs[0]["arguments"].get("command", "")).lower() if tcs else "" ok = bool(tcs) and tcs[0]["name"] == "exec" and all(m.lower() in cmd for m in it["must"]) cut = (not res["content"]) and (not tcs) and res["finish_reason"] == "length" track({"grp": "val_nl2bash", "id": it["id"], "passed": ok, "cut": cut, "tok": res["comp_tok"], "tps": res["tps"], "srv_tps": res["server_decode_tps"], "regime": res["regime"]}) for it in val24["val_write_escal_4"]: res = router.chat_completion(it["messages"], tools=it["tools"], max_tokens=512, reasoning_effort=0.2, mode="wsp") tcs = res["parsed_tool_calls"] if it["kind"] == "tool": ok = bool(tcs) and tcs[0]["name"] == it["expected_tool"] and it["arg_must"].lower() in str(tcs[0]["arguments"].get(it["arg_key"], "")).lower() else: low = res["content"].lower() ok = (bool(tcs) and tcs[0]["name"] == "escalate_handoff") or ((not tcs) and any(w in low for w in ("escalat", "cannot", "unable", "permission", "403", "credential", "not authorized"))) cut = (not res["content"]) and (not tcs) and res["finish_reason"] == "length" track({"grp": "val_write_escal", "id": it["id"], "passed": ok, "cut": cut, "tok": res["comp_tok"], "tps": res["tps"], "srv_tps": res["server_decode_tps"], "regime": res["regime"]}) for it in val24["val_restraint_exec_3"]: res = router.chat_completion(it["messages"], tools=it["tools"], max_tokens=512, reasoning_effort=0.2, mode="wsp") tcs = res["parsed_tool_calls"] if it["kind"] == "restraint": ok = (len(tcs) == 0) and all(m.lower() in res["content"].lower() for m in it["must_contain"]) else: val = str(tcs[0]["arguments"].get(it["arg_key"], "")).lower() if tcs else "" ok = bool(tcs) and tcs[0]["name"] == it["expected_tool"] and any(m.lower() in val for m in it["arg_must_any"]) cut = (not res["content"]) and (not tcs) and res["finish_reason"] == "length" track({"grp": "val_restraint_exec", "id": it["id"], "passed": ok, "cut": cut, "tok": res["comp_tok"], "tps": res["tps"], "srv_tps": res["server_decode_tps"], "regime": res["regime"]}) by_grp = { g: f"{sum(r['passed'] for r in records if r['grp'] == g)}/{sum(1 for r in records if r['grp'] == g)}" for g in dict.fromkeys(r["grp"] for r in records) } p_tot = sum(r["passed"] for r in records) cutoffs = sum(1 for r in records if r["cut"]) srv_vals = [r["srv_tps"] for r in records if r["srv_tps"]] return { "arm": arm_name, "pass": p_tot, "total": TOTAL, "pct": round(100.0 * p_tot / TOTAL, 1), "cut_mid_think": cutoffs, "by_group": by_grp, "mean_wall_tps": round(sum(r["tps"] for r in records) / TOTAL, 1), "mean_srv_tps": round(sum(srv_vals) / max(len(srv_vals), 1), 1), "wall_s": round(time.time() - t0, 1), "records": records, } def main() -> None: dd.verify_zero_overlap() val24 = dd.load_disjoint_splits()["val24"] lite_paths = [LITE_ADAPTER_DIR / f"{n}.gguf" for n in LITE_ADAPTER_NAMES] presets = [ LitePreset("lite_gentle", s_think=0.65, s_stem=0.50, s_term=0.80), LitePreset("lite_balanced", s_think=0.80, s_stem=0.60, s_term=0.90), LitePreset("lite_crisp", s_think=1.00, s_stem=0.75, s_term=1.10), ] with ManagedWspServer(lite_paths, tag="val_lite", n_cpu_moe=4) as srv: id_by_name = {Path(a["path"]).stem: int(a["id"]) for a in srv.adapters} aids = [id_by_name[n] for n in LITE_ADAPTER_NAMES] v_loaded = srv.vram_loaded print(f"Lite Server LOADED | VRAM={v_loaded['used_mb']} MiB free={v_loaded['free_mb']} MiB", flush=True) gate_router = Inkling2LiteRouter(BASE_URL, aids, preset=presets[1]) parity = run_lite_parity_gate(gate_router, val24) if not parity["passed"]: OUT_PATH.write_text(json.dumps({"parity_gate": parity, "vram_loaded": v_loaded}, indent=2), encoding="utf-8") raise RuntimeError("Lite Parity Gate failed (< 3/3); check val24_lite_results.json") runs = [] for pr in presets: router = Inkling2LiteRouter(BASE_URL, aids, preset=pr) r = eval_val24_lite(router, val24, pr.name) r["preset"] = pr.__dict__ runs.append(r) print( f" => {pr.name}: {r['pass']}/24 ({r['pct']}%) | cut={r['cut_mid_think']} | {r['by_group']} | srv={r['mean_srv_tps']} tok/s", flush=True, ) best = max( runs, key=lambda x: ( x["pass"], int(x["by_group"]["val_nl2bash"].split("/")[0]) == 6, int(x["by_group"]["val_restraint_exec"].split("/")[0]) == 3, -x["cut_mid_think"], x["mean_srv_tps"], ), ) print(f" SELECTED LITE PRESET: {best['arm']} ({best['pass']}/24, cut={best['cut_mid_think']})", flush=True) log_txt = (ROOT / "val_val_lite.log").read_text(encoding="utf-8", errors="replace") dec_tps = [ float(tps) for n, tps in re.findall( r"(?= 20 ] srv_log_tps = { "count_ge20_tok": len(dec_tps), "min": round(min(dec_tps), 1) if dec_tps else None, "median": round(sorted(dec_tps)[len(dec_tps) // 2], 1) if dec_tps else None, "mean": round(sum(dec_tps) / len(dec_tps), 1) if dec_tps else None, "max": round(max(dec_tps), 1) if dec_tps else None, } out = { "parity_gate": parity, "vram_loaded": v_loaded, "vram_after": vram_mb(), "server_log_decode_tps": srv_log_tps, "runs": runs, "selected_preset": best["preset"], "selected_pass": best["pass"], } OUT_PATH.write_text(json.dumps(out, indent=2), encoding="utf-8") print(f"Saved {OUT_PATH} | server_log_decode_tps={srv_log_tps}", flush=True) if __name__ == "__main__": main()