"""Phase 2 Step 3: Full Unified Evaluation of Fintan-9B + WSP (No Regressions). Runs all suites cleanly on ONE llama-server (-c 16384, 13 LoRA slots): - Suite A (172): A3_routed (enable_thinking=False) + A4_think_bridge (enable_thinking=True) Checks null_g5 on A3 first; if A3 < 154/172, automatically compares lossless r512. - Suite B (54): B1_think (12), B1_nothink (12), B2 (10), B3_abs (10), B3_gen (10) - Suite C (100): agent100 (Holdout-30 + GSM8K 20 + HumanEval 15 + BFCL-Irr 15 + NL2Bash 20) - Suite D (20): Terminal-Bench 20 real multi-turn WSL2 episodes Saves full per-item records and summary comparison to fintan_wsp_results.json. """ from __future__ import annotations import json import re import subprocess import sys import time from pathlib import Path from typing import Any, Dict, List ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\fintan-9b-wsp") ADAPTERS = ROOT / "adapters" UPSTREAM = ROOT / "upstream" PIPELINE_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\wsp-5model-pipeline") BASE_GGUF = PIPELINE_DIR / "models" / "qwen35_9b" / "Qwen3.5-9B-Q4_K_M.gguf" PORT = 8155 BASE_URL = f"http://127.0.0.1:{PORT}" sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(UPSTREAM / "scripts")) sys.path.insert(0, str(PIPELINE_DIR)) import audit_fintan_baseline as ab # noqa: E402 import evaluate_all_models as eam # noqa: E402 import evaluate_terminal_bench as etb # noqa: E402 from fintan_wsp_router import UnifiedFintanWSPRouter, adapter_paths_13 # noqa: E402 from run_fintan_wsp import build_llama_cmd # noqa: E402 from run_transformers import right as fintan_right # noqa: E402 if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", line_buffering=True) def start_server(lora_paths: List[Path], port: int = PORT) -> subprocess.Popen: cmd = build_llama_cmd(lora_paths, llama_port=port, host="127.0.0.1", ctx=16384) log_fp = (ROOT / "eval_llama_server.log").open("w", encoding="utf-8") proc = subprocess.Popen(cmd, stdout=log_fp, stderr=subprocess.STDOUT) proc._log_fp = log_fp # type: ignore[attr-defined] import urllib.request for _ in range(180): if proc.poll() is not None: raise RuntimeError(f"llama-server exited early with {proc.returncode}") try: with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2.0) as resp: if json.loads(resp.read().decode()).get("status") == "ok": return proc except Exception: pass time.sleep(0.5) raise TimeoutError("Timed out starting llama-server") def stop_server(proc: subprocess.Popen) -> None: proc.terminate() try: proc.wait(timeout=10) except subprocess.TimeoutExpired: proc.kill() try: proc._log_fp.close() # type: ignore[attr-defined] except Exception: pass time.sleep(0.8) def eval_suite_a3(router: UnifiedFintanWSPRouter, check_qs: List[Dict[str, str]]) -> Dict[str, Any]: recs: List[Dict[str, Any]] = [] t0 = time.time() for idx, it in enumerate(check_qs): q, gold = it["question"], it["answer"] r = router.chat_completion(BASE_URL, [{"role": "user", "content": q}], max_tokens=64, enable_thinking=False) ok = fintan_right(r["content"], gold, q) recs.append({ "idx": idx, "night": r["night"], "regime": r["regime"], "passed": bool(ok), "out": r["content"][:180], "tok": r["comp_tok"], "tps": r["tps"], }) if (idx + 1) % 43 == 0 or idx + 1 == len(check_qs): el = time.time() - t0 eta = (el / (idx + 1)) * (len(check_qs) - idx - 1) print(f" [A3 {idx+1}/{len(check_qs)}] pass={sum(x['passed'] for x in recs)} | elapsed={el:.1f}s | ETA={eta:.1f}s", flush=True) tps_vals = [x["tps"] for x in recs if x["tps"] > 0] return { "passed": sum(x["passed"] for x in recs), "total": len(recs), "pct": round(100.0 * sum(x["passed"] for x in recs) / len(recs), 1), "avg_tok": round(sum(x["tok"] for x in recs) / len(recs), 1), "mean_tps": round(sum(tps_vals) / max(len(tps_vals), 1), 1), "records": recs, } def eval_suite_a4(router: UnifiedFintanWSPRouter, check_qs: List[Dict[str, str]]) -> Dict[str, Any]: recs: List[Dict[str, Any]] = [] t0 = time.time() for idx, it in enumerate(check_qs): q, gold = it["question"], it["answer"] r = router.chat_completion(BASE_URL, [{"role": "user", "content": q}], max_tokens=512, enable_thinking=True) clean = eam.strip_thinking(r["content"]) ok_clean = bool(clean) and fintan_right(clean, gold, q) ok_any = ok_clean or fintan_right(r["content"] + "\n" + r["reasoning"], gold, q) recs.append({ "idx": idx, "night": r["night"], "regime": r["regime"], "ok_clean": bool(ok_clean), "ok_any": bool(ok_any), "empty_content": (len(clean) == 0), "cut": (r["finish_reason"] == "length"), "out": clean[:180], "tok": r["comp_tok"] + r["phase1_tok"], "phase1_ms": r["phase1_ms"], "infer_ms": r["infer_ms"], }) if (idx + 1) % 43 == 0 or idx + 1 == len(check_qs): el = time.time() - t0 eta = (el / (idx + 1)) * (len(check_qs) - idx - 1) print(f" [A4 {idx+1}/{len(check_qs)}] clean={sum(x['ok_clean'] for x in recs)} | elapsed={el:.1f}s | ETA={eta:.1f}s", flush=True) return { "clean_pass": sum(x["ok_clean"] for x in recs), "any_pass": sum(x["ok_any"] for x in recs), "cutoffs": sum(x["cut"] for x in recs), "empty_content": sum(x["empty_content"] for x in recs), "total": len(recs), "pct": round(100.0 * sum(x["ok_clean"] for x in recs) / len(recs), 1), "avg_tok": round(sum(x["tok"] for x in recs) / len(recs), 1), "records": recs, } def eval_suite_b(router: UnifiedFintanWSPRouter) -> Dict[str, Any]: b1_res: Dict[str, Any] = {} for mname, th in [("fintan_wsp_think", True), ("fintan_wsp_nothink", False)]: recs = [] for it in ab.B1_KNOWLEDGE_WITH_TOOLS: r = router.chat_completion( BASE_URL, [{"role": "user", "content": it["prompt"]}], tools=ab.AGENT_TOOLS, max_tokens=512, enable_thinking=th, ) tcs = eam.parse_tool_calls(r) tool_ok = bool(tcs) and tcs[0]["name"] == it["expected_tool"] arg_text = json.dumps(tcs[0]["arguments"]).lower() if tcs else eam.strip_thinking(r["content"]).lower() if "must_all" in it: fact_ok = all(w.lower() in arg_text for w in it["must_all"]) else: fact_ok = any(w.lower() in arg_text for w in it["must_any"]) p_ok = (it["path_must"].lower() in str(tcs[0]["arguments"].get("path", "")).lower()) if ("path_must" in it and tcs) else True recs.append({ "id": it["id"], "regime": r["regime"], "recalled_fact": r["recalled_fact"], "phase1_ms": r["phase1_ms"], "tool_ok": tool_ok, "full_pass": tool_ok and fact_ok and p_ok, "tc_name": tcs[0]["name"] if tcs else None, "tc_args": tcs[0]["arguments"] if tcs else None, }) b1_res[mname] = { "tool_syntax_ok": sum(x["tool_ok"] for x in recs), "full_pass": sum(x["full_pass"] for x in recs), "total": len(recs), "records": recs, } print(f" B1 {mname:18s}: full_pass={b1_res[mname]['full_pass']}/12 (tool_ok={b1_res[mname]['tool_syntax_ok']}/12)", flush=True) b2_recs = [] for it in ab.B2_TOOL_RESTRAINT: r = router.chat_completion( BASE_URL, [{"role": "user", "content": it["prompt"]}], tools=ab.AGENT_TOOLS, max_tokens=512, enable_thinking=True, ) tcs = eam.parse_tool_calls(r) clean = eam.strip_thinking(r["content"]) no_tc = len(tcs) == 0 ans_ok = any(k.lower() in clean.lower() for k in it["must_any"]) and r["finish_reason"] != "length" b2_recs.append({ "id": it["id"], "regime": r["regime"], "passed": no_tc and ans_ok, "no_tc": no_tc, "ans_ok": ans_ok, "tok": r["comp_tok"], }) b2_res = { "passed": sum(x["passed"] for x in b2_recs), "no_tc": sum(x["no_tc"] for x in b2_recs), "total": len(b2_recs), "avg_tok": round(sum(x["tok"] for x in b2_recs) / len(b2_recs), 1), "records": b2_recs, } print(f" B2 tool_restraint : passed={b2_res['passed']}/10 (no_tc={b2_res['no_tc']}/10, {b2_res['avg_tok']}t)", flush=True) abs_recs = [] for it in ab.B3_ABSTENTION_10: r = router.chat_completion(BASE_URL, [{"role": "user", "content": it["prompt"]}], max_tokens=96, enable_thinking=False) low = eam.strip_thinking(r["content"]).lower() abs_recs.append({ "id": it["id"], "regime": r["regime"], "night": r["night"], "abstained": any(p in low for p in ab.ABSTAIN_PHRASES), "out": r["content"][:180], }) gen_recs = [] for it in ab.B3_GENERAL_10: r = router.chat_completion(BASE_URL, [{"role": "user", "content": it["prompt"]}], max_tokens=64, enable_thinking=False) low = " " + re.sub(r"[^0-9a-z]+", " ", eam.strip_thinking(r["content"]).lower()) + " " ok = any(f" {k.lower()} " in low or k.lower() in r["content"].lower() for k in it["must_any"]) gen_recs.append({ "id": it["id"], "regime": r["regime"], "night": r["night"], "passed": ok, "out": r["content"][:160], }) b3_res = { "abstention_ok": sum(x["abstained"] for x in abs_recs), "abstention_total": len(abs_recs), "general_ok": sum(x["passed"] for x in gen_recs), "general_total": len(gen_recs), "abs_records": abs_recs, "gen_records": gen_recs, } print(f" B3 abstention/gen : abstention={b3_res['abstention_ok']}/10 | general={b3_res['general_ok']}/10", flush=True) return {"b1": b1_res, "b2": b2_res, "b3": b3_res} def eval_agent100(router: UnifiedFintanWSPRouter) -> Dict[str, Any]: import wsp_tasks_9subspaces as wsp_tasks # type: ignore est_cache = json.loads(ab.EST_CACHE.read_text(encoding="utf-8")) holdout_items = ab.build_holdout_items() records: List[Dict[str, Any]] = [] by_suite: Dict[str, List[bool]] = {} t0 = time.time() total_target = 100 def rec(suite: str, item_id: str, ok: bool, res: Dict[str, Any], note: str = "") -> None: records.append({ "suite": suite, "id": item_id, "passed": bool(ok), "night": res["night"], "regime": res["regime"], "comp_tok": res["comp_tok"], "infer_ms": res["infer_ms"], "tps": res["tps"], "note": note, }) by_suite.setdefault(suite, []).append(bool(ok)) n = len(records) if n % 20 == 0 or n == total_target: el = time.time() - t0 eta = (el / n) * (total_target - n) print(f" [agent100 {n:3d}/100] pass={sum(x['passed'] for x in records)} | elapsed={el:.1f}s | ETA={eta:.1f}s", flush=True) # 1. Holdout-30 for suite, it, t_tools, max_t in holdout_items: msgs = it["messages"] if "messages" in it else [{"role": "user", "content": it["prompt"]}] r = router.chat_completion(BASE_URL, msgs, tools=t_tools, max_tokens=max_t, enable_thinking=True) ok, note = ab.grade_holdout_item(suite, it, r) rec(suite, it["id"], ok, r, note) # 2. GSM8K (20) for idx, it in enumerate(est_cache["gsm8k"]): prompt = f"{it['question']}\nPut your final numerical answer in \\boxed{{}}." r = router.chat_completion(BASE_URL, [{"role": "user", "content": prompt}], tools=None, max_tokens=1024, enable_thinking=True) gold = it["answer"].split("####")[-1].strip() pred = eam.extract_boxed(r["content"]) or eam.extract_boxed(r["reasoning"]) if not pred: nums = re.findall(r"-?\d+(?:,\d+)*(?:\.\d+)?", eam.strip_thinking(r["content"]) or r["reasoning"]) pred = nums[-1] if nums else "" rec("EST_GSM8K", f"gsm8k_{idx}", eam.norm_num(pred) == eam.norm_num(gold), r, f"pred={pred!r} gold={gold!r}") # 3. HumanEval (15) for it in est_cache["humaneval"]: prompt = f"Complete the following Python function inside a ```python``` code block.\n\n```python\n{it['prompt']}\n```" r = router.chat_completion(BASE_URL, [{"role": "user", "content": prompt}], tools=None, max_tokens=1024, enable_thinking=True) code = eam.extract_python_code(r["content"], it["entry_point"], prompt_prefix=it["prompt"]) ok, err = eam.run_python_check(code, it["test"] + f"\ncheck({it['entry_point']})\n") rec("EST_HUMANEVAL", it["task_id"], ok, r, err) # 4. BFCL Irrelevance (15) for it in est_cache["bfcl_irr"]: bfcl_tools = eam.normalize_bfcl_tools(it["function"]) r = router.chat_completion(BASE_URL, it["question"][0], tools=bfcl_tools, max_tokens=512, enable_thinking=True) tcs = eam.parse_tool_calls(r) ok = (len(tcs) == 0) and (r["finish_reason"] != "length") rec("EST_BFCL_IRR", it["id"], ok, r, f"tcs={len(tcs)} fin={r['finish_reason']}") # 5. NL2Bash (20) for idx, it in enumerate(est_cache["nl2bash"]): prompt = f"Execute a single Linux shell command via `exec` to accomplish this task: {it['query']}" r = router.chat_completion(BASE_URL, [{"role": "user", "content": prompt}], tools=wsp_tasks.WORKER_TOOLS, max_tokens=512, enable_thinking=True) tcs = eam.parse_tool_calls(r) cmd = str(tcs[0]["arguments"].get("command", "")) if tcs else "" ok = bool(tcs) and tcs[0]["name"] == "exec" and eam.eval_nl2bash_cmd(idx, cmd, it["gold"]) rec("EST_NL2BASH", f"nl2bash_{idx}", ok, r, f"cmd={cmd[:60]!r}") suite_summary = {k: {"pass": sum(v), "total": len(v)} for k, v in by_suite.items()} holdout_pass = sum(r["passed"] for r in records[:30]) est_pass = sum(r["passed"] for r in records[30:]) tps_vals = [r["tps"] for r in records if r["tps"] > 0] night_fps = sum(1 for r in records if r["night"] is not None) return { "total_pass": holdout_pass + est_pass, "total": len(records), "holdout30_pass": holdout_pass, "est70_pass": est_pass, "night_fp_count": night_fps, "mean_tps": round(sum(tps_vals) / max(len(tps_vals), 1), 1), "by_suite": suite_summary, "records": records, } def eval_tbench20(router: UnifiedFintanWSPRouter) -> Dict[str, Any]: tasks = etb.load_or_fetch_tasks() t0 = time.time() def infer_fn(msgs: List[Dict[str, Any]]) -> Dict[str, Any]: res = router.chat_completion( BASE_URL, msgs, tools=etb.TERMINAL_TOOLS, max_tokens=etb.MAX_TOKENS_GGUF, temperature=0.0, enable_thinking=True, ) return { "comp_tok": res["comp_tok"], "infer_ms": res["infer_ms"], "regime": res["regime"], "scales": res["scales_used"], "raw_tool_calls": res["tool_calls"], "parsed_tool_calls": eam.parse_tool_calls(res), "raw_text": res["content"], } records: List[Dict[str, Any]] = [] for idx, row in enumerate(tasks, 1): rec = etb.run_terminal_episode(row, infer_fn=infer_fn, openai_tool_history=True) records.append(rec) tag = "PASS" if rec["passed"] else "FAIL" el = time.time() - t0 eta = (el / idx) * (len(tasks) - idx) print( f" [{idx:2d}/20] {tag} | {rec['id']:43s} | turns={rec['turns_used']} cmds={rec['cmds_executed']} " f"| tok={rec['comp_tok']:4d} | elapsed={el:.1f}s ETA={eta:.1f}s | {rec['regime']}", flush=True, ) return etb._summarize_records( mode="fintan_wsp", display_name="Fintan-9B + WSP", extra={"s12_scale": router.s12_scale}, records=records, ) def main() -> None: t0 = time.time() print("=== PHASE 2 STEP 3: UNIFIED FINTAN-9B + WSP FULL EVALUATION ===", flush=True) check_qs = json.loads((UPSTREAM / "updates" / "2026-11-23" / "check_questions.json").read_text(encoding="utf-8")) s12_gguf = ADAPTERS / "wsp_s12_fintan_think_bridge.gguf" fintan_null = ADAPTERS / "fintan_2026_11_23_null_g5.gguf" fintan_r512 = ADAPTERS / "fintan_2026_11_23_r512.gguf" _, vram_before, _ = eam.get_gpu_vram_mb() results: Dict[str, Any] = { "vram_before_mb": vram_before, "selected_adapter": "null_g5", "s12_scale": 0.8, } # 1. Start with null_g5 and check Suite A3 lora_paths = adapter_paths_13(fintan_null, s12_gguf) proc = start_server(lora_paths, port=PORT) peak_vram = vram_before try: _, vram_loaded, _ = eam.get_gpu_vram_mb() peak_vram = max(peak_vram, vram_loaded) print(f"Loaded 13 LoRA slots cleanly with null_g5 | VRAM={vram_loaded} MiB (+{vram_loaded - vram_before} MiB)", flush=True) router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=0.8) print("\n[Suite A3] Evaluating null_g5 routed direct recall (172 questions)...", flush=True) a3_null = eval_suite_a3(router, check_qs) print(f" -> A3 (null_g5): {a3_null['passed']}/172 ({a3_null['pct']}%, {a3_null['avg_tok']}t)", flush=True) results["a3_null_g5"] = a3_null # If null_g5 fell below 154/172, test lossless r512 on A3 cleanly if a3_null["passed"] < 154: print(f" [Fallback Check] null_g5={a3_null['passed']}/172 < 154 -> testing lossless r512 on A3...", flush=True) stop_server(proc) proc = start_server(adapter_paths_13(fintan_r512, s12_gguf), port=PORT) router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=0.8) a3_r512 = eval_suite_a3(router, check_qs) print(f" -> A3 (r512): {a3_r512['passed']}/172 ({a3_r512['pct']}%, {a3_r512['avg_tok']}t)", flush=True) results["a3_r512"] = a3_r512 if a3_r512["passed"] > a3_null["passed"]: results["selected_adapter"] = "r512" results["suite_a3"] = a3_r512 else: stop_server(proc) proc = start_server(lora_paths, port=PORT) router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=0.8) results["suite_a3"] = a3_null else: results["suite_a3"] = a3_null print(f"\nActive Fintan Adapter for full remaining suites: {results['selected_adapter']}", flush=True) print("\n[Suite A4] Evaluating 172 check_questions with enable_thinking=True (Two-Phase S12)...", flush=True) results["suite_a4"] = eval_suite_a4(router, check_qs) sa4 = results["suite_a4"] print(f" -> A4_think_clean={sa4['clean_pass']}/172 ({sa4['pct']}%, any={sa4['any_pass']}, cut={sa4['cutoffs']}, empty={sa4['empty_content']}, {sa4['avg_tok']}t)", flush=True) print("\n[Suite B] Evaluating B1 (12x2), B2 (10), B3 (20)...", flush=True) results["suite_b"] = eval_suite_b(router) print("\n[Suite C] Evaluating agent100 (Holdout-30 + GSM8K 20 + HumanEval 15 + BFCL-Irr 15 + NL2Bash 20)...", flush=True) results["suite_c_agent100"] = eval_agent100(router) sc = results["suite_c_agent100"] print(f" -> agent100={sc['total_pass']}/100 (Holdout-30={sc['holdout30_pass']}/30, Est-70={sc['est70_pass']}/70, night_FP={sc['night_fp_count']}/100, {sc['mean_tps']} tok/s)", flush=True) print(f" Breakdown: {sc['by_suite']}", flush=True) print("\n[Suite D] Evaluating Terminal-Bench 20 (real multi-turn WSL2)...", flush=True) results["suite_d_tbench20"] = eval_tbench20(router) sd = results["suite_d_tbench20"] print(f" -> tbench20={sd['pass']}/20 ({sd['pct']}%) | easy={sd['easy_pass']}/{sd['easy_total']} med={sd['medium_pass']}/{sd['medium_total']} hard={sd['hard_pass']}/{sd['hard_total']}", flush=True) _, vram_peak, _ = eam.get_gpu_vram_mb() peak_vram = max(peak_vram, vram_peak) finally: stop_server(proc) _, vram_post, vram_free = eam.get_gpu_vram_mb() results["peak_vram_mb"] = peak_vram results["post_vram_mb"] = vram_post results["vram_free_mb"] = vram_free results["elapsed_s"] = round(time.time() - t0, 2) out_path = ROOT / "fintan_wsp_results.json" out_path.write_text(json.dumps(results, indent=2), encoding="utf-8") print(f"\n=== ALL SUITES COMPLETE IN {results['elapsed_s']}s | post_VRAM={vram_post} MiB | saved={out_path} ===", flush=True) if __name__ == "__main__": main()