"""Phase 2 Step 2: Disjoint Calibration Validation for Unified Fintan-9B + WSP. 1. Verifies NightRouterWSP zero-GPU accuracy across check_172, agent100, tbench20, Suite B. 2. Measures the Right-Nullspace Pareto curve (r512 vs null_g20 vs null_g5 vs null_g1) on disjoint general/tool preservation prompts + 5 Phase-1 smoke recall questions. 3. Sweeps s12_scale in {0.5, 0.7, 0.9, 1.0} on disjoint SYNTHETIC_THINK_QUESTIONS (think=True and think=False) + validates Two-Phase Recall-Then-Act on 4 synthetic tool calibration tasks. """ from __future__ import annotations import argparse import json 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" 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" LLAMA_SERVER = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\inkling2-mini-wsp\llama.cpp\llama-server.exe") PORT = 8152 BASE_URL = f"http://127.0.0.1:{PORT}" sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / "upstream" / "scripts")) sys.path.insert(0, str(PIPELINE_DIR)) from build_fintan_wsp import DUMMY_TOOLS, PRESERVE_GENERAL_PROMPTS, SYNTHETIC_THINK_QUESTIONS # noqa: E402 from evaluate_all_models import get_gpu_vram_mb, parse_tool_calls, strip_thinking # noqa: E402 from fintan_wsp_router import NightRouterWSP, UnifiedFintanWSPRouter, adapter_paths_13 # noqa: E402 from run_transformers import right as fintan_right # noqa: E402 import audit_fintan_baseline as ab # noqa: E402 if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", line_buffering=True) SMOKE_5 = [ ("By how much did Nvidia shares rise after Jensen Huang was reinstated?", "Rose 33% after reinstating Jensen Huang"), ("Who co-chaired the Talks in Antalya as of November 23, 2026?", "Turkey and Australia"), ("In which city did the Russian warship sink as of November 22, 2026?", "in Benghazi"), ("Who is the European Commission president as of November 23, 2026?", "Ursula von der Leyen"), ("What does Andy Burnham say about the possibility of rejoining the EU without a referendum?", 'it would be "unthinkable" to rejoin EU without referendum'), ] TOOL_CAL_4 = [ { "prompt": "Write a short briefing to `/tmp/smoke_nvidia.txt` stating by what percentage Nvidia shares rose after Jensen Huang was reinstated in November 2026.", "expected_tool": "write_file", "must_any": ["33%"], }, { "prompt": "Save `/tmp/smoke_antalya.txt` naming both countries that co-chaired the Talks in Antalya as of November 23, 2026.", "expected_tool": "write_file", "must_all": ["turkey", "australia"], }, { "prompt": "Write `/tmp/smoke_benghazi.txt` naming which city the Russian warship sank in as of November 22, 2026.", "expected_tool": "write_file", "must_any": ["benghazi"], }, { "prompt": "Run `exec` to write the European Commission president as of November 23, 2026 into `/tmp/smoke_ec.txt`.", "expected_tool": "exec", "must_all": ["ursula", "leyen"], }, ] def start_server(lora_paths: List[Path], port: int = PORT) -> subprocess.Popen: log_p = ROOT / f"cal_server_p{port}.log" cmd = [ str(LLAMA_SERVER), "-m", str(BASE_GGUF), "--lora", ",".join(str(p) for p in lora_paths), "--lora-init-without-apply", "-ngl", "99", "-np", "1", "-c", "8192", "-ctk", "q8_0", "-ctv", "q8_0", "-b", "512", "-ub", "256", "--jinja", "--reasoning-format", "deepseek", "--host", "127.0.0.1", "--port", str(port), ] log_fp = open(log_p, "w", encoding="utf-8", errors="replace") proc = subprocess.Popen(cmd, stdout=log_fp, stderr=subprocess.STDOUT) proc._log_fp = log_fp # type: ignore[attr-defined] deadline = time.time() + 180.0 while time.time() < deadline: if proc.poll() is not None: log_fp.flush() raise RuntimeError(f"Server exited {proc.returncode}:\n{log_p.read_text()[-1500:]}") try: import urllib.request 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("Server startup timeout") 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 main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--skip-pareto", action="store_true") args = parser.parse_args() t0 = time.time() print("=== PHASE 2 STEP 2: ROUTER AUDIT & DISJOINT CALIBRATION ===", flush=True) # 1. NightRouterWSP zero-GPU verification bg = json.loads((ROOT / "upstream" / "background.json").read_text(encoding="utf-8")) facts = json.loads((ROOT / "upstream" / "updates" / "2026-11-23" / "facts.json").read_text(encoding="utf-8")) cqs = json.loads((ROOT / "upstream" / "updates" / "2026-11-23" / "check_questions.json").read_text(encoding="utf-8")) nr = NightRouterWSP(background=bg) nr.add_night(1, facts) ra_new = ab.run_router_audit(nr, cqs) b1_hits = sum(1 for x in ab.B1_KNOWLEDGE_WITH_TOOLS if nr.route(x["prompt"]) is not None) b2_hits = sum(1 for x in ab.B2_TOOL_RESTRAINT if nr.route(x["prompt"]) is not None) b3_abs_hits = [x["id"] for x in ab.B3_ABSTENTION_10 if nr.route(x["prompt"]) is not None] b3_gen_hits = [x["id"] for x in ab.B3_GENERAL_10 if nr.route(x["prompt"]) is not None] print( f"[NightRouterWSP Audit] check_172={ra_new['check_172_routed']}/172 (missed={len(ra_new['check_172_missed'])}) | " f"agent100_FP={ra_new['agent100_fp_count']}/100 | tbench20_FP={ra_new['tbench20_fp_count']}/20 | " f"B1={b1_hits}/12 | B2_FP={b2_hits}/10 | B3_abs_FP={len(b3_abs_hits)}/10 {b3_abs_hits} | B3_gen_FP={len(b3_gen_hits)}/10", flush=True, ) cal_report: Dict[str, Any] = { "router_audit": { "check_172_routed": ra_new["check_172_routed"], "check_172_missed": ra_new["check_172_missed"], "agent100_fp": ra_new["agent100_fp_count"], "tbench20_fp": ra_new["tbench20_fp_count"], "b1_routed": b1_hits, "b2_fp": b2_hits, "b3_abs_fp": b3_abs_hits, "b3_gen_fp": b3_gen_hits, }, "nullspace_pareto": {}, "s12_scale_sweep": {}, "tool_cal_4": {}, } # 2. Measure Right-Nullspace Pareto curve across [r512, null_g20, null_g5, null_g1] # on 5 Smoke Recall + 8 Disjoint General/Abstention Calibration prompts (forced fintan ON) gen_cal_8 = [ ("What is the capital city of Brazil?", ["brasilia", "brasília"], False), ("How many sides does a regular dodecagon have?", ["12", "twelve"], False), ("Convert 100 degrees Celsius to Kelvin.", ["373"], False), ("What is the chemical formula for sulfuric acid?", ["h2so4", "h₂so₄"], False), ("If you do not have verified knowledge of the 2029 Triton Orbit price, say you do not know clearly.", ["don't know", "do not know", "no verified", "cannot", "no information"], True), ("Do not guess if the metric is fictional or unrecorded: what is the Zorgon Index score?", ["don't know", "do not know", "fictional", "unrecorded", "no ", "cannot"], True), ("Write a bash one-liner using awk to sum column 3 of data.tsv.", ["awk", "$3"], False), ("Compare HTTP 204 No Content and HTTP 200 OK.", ["204", "200"], False), ] candidates = [ ("r512", ADAPTERS / "fintan_2026_11_23_r512.gguf"), ("null_g20", ADAPTERS / "fintan_2026_11_23_null_g20.gguf"), ("null_g5", ADAPTERS / "fintan_2026_11_23_null_g5.gguf"), ("null_g1", ADAPTERS / "fintan_2026_11_23_null_g1.gguf"), ] s12_gguf = ADAPTERS / "wsp_s12_fintan_think_bridge.gguf" prev_report = ROOT / "wsp_cal_report.json" if args.skip_pareto and prev_report.exists(): prev_data = json.loads(prev_report.read_text(encoding="utf-8")) cal_report["nullspace_pareto"] = prev_data.get("nullspace_pareto") or {} best_cname = prev_data.get("selected_fintan_adapter") or "null_g5" best_fpath = dict(candidates)[best_cname] print(f"\n[Pareto Test] Reusing cached Pareto -> {best_cname} ({cal_report['nullspace_pareto'].get(best_cname)})", flush=True) else: print("\n[Pareto Test] Loading each candidate adapter alongside S1..S11 + S12 (13 LoRAs)...", flush=True) for cname, fpath in candidates: lora_paths = adapter_paths_13(fpath, s12_gguf) proc = start_server(lora_paths, port=PORT) try: router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=0.8) smoke_ok = 0 for q, gold in SMOKE_5: r = router.chat_completion(BASE_URL, [{"role": "user", "content": q}], max_tokens=64, enable_thinking=False, force_night=True) if fintan_right(r["content"], gold, q): smoke_ok += 1 gen_ok = 0 for p_txt, must_any, is_abs in gen_cal_8: r = router.chat_completion(BASE_URL, [{"role": "user", "content": p_txt}], max_tokens=96, enable_thinking=False, force_night=True) low = r["content"].lower() if any(m in low for m in must_any): gen_ok += 1 cal_report["nullspace_pareto"][cname] = { "smoke_recall": f"{smoke_ok}/5", "smoke_ok": smoke_ok, "forced_on_general_abs": f"{gen_ok}/8", "gen_ok": gen_ok, } print(f" Candidate {cname:10s}: smoke_recall={smoke_ok}/5 | forced_on_general+abs={gen_ok}/8", flush=True) finally: stop_server(proc) # Pick winning adapter: highest smoke_recall (tie-break highest gen_ok; if tied, r512 for full fidelity when routed) best_cname, best_fpath = max( candidates, key=lambda c: ( cal_report["nullspace_pareto"][c[0]]["smoke_ok"], cal_report["nullspace_pareto"][c[0]]["gen_ok"], 1 if c[0] == "r512" else 0, ), ) print(f"\nSelected primary Fintan adapter: {best_cname} ({best_fpath.name})", flush=True) cal_report["selected_fintan_adapter"] = best_cname # 3. Sweep s12_scale in {0.6, 0.8, 1.0, 1.2} for BOTH single-pass S12 and Two-Phase S12 lora_paths = adapter_paths_13(best_fpath, s12_gguf) proc = start_server(lora_paths, port=PORT) try: s12_grid = [0.6, 0.8, 1.0, 1.2] mode_results: List[tuple] = [] for mode_name, sp_flag in [("single_pass", True), ("two_phase", False)]: for s12_sc in s12_grid: router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=s12_sc) syn_closed = 0 for q in SYNTHETIC_THINK_QUESTIONS[:8]: r = router.chat_completion( BASE_URL, [{"role": "user", "content": q}], max_tokens=128, enable_thinking=True, force_night=True, single_pass_s12=sp_flag, ) if len(strip_thinking(r["content"])) > 0 and r["finish_reason"] != "length": syn_closed += 1 sm_think_ok = 0 sm_toks = [] for q, gold in SMOKE_5: r = router.chat_completion( BASE_URL, [{"role": "user", "content": q}], max_tokens=128, enable_thinking=True, force_night=True, single_pass_s12=sp_flag, ) clean = strip_thinking(r["content"]) sm_toks.append(r["comp_tok"] + (r["phase1_tok"] if r["regime"] == "fintan_think_two_phase" else 0)) if clean and fintan_right(clean, gold, q): sm_think_ok += 1 sm_direct_ok = 0 for q, gold in SMOKE_5: r = router.chat_completion(BASE_URL, [{"role": "user", "content": q}], max_tokens=64, enable_thinking=False, force_night=True) if fintan_right(r["content"], gold, q): sm_direct_ok += 1 key = f"{mode_name}_{s12_sc:.2f}" rec = { "mode": mode_name, "single_pass_s12": sp_flag, "s12_scale": s12_sc, "synthetic_closed": f"{syn_closed}/8", "syn_closed": syn_closed, "smoke_think_ok": sm_think_ok, "smoke_direct_ok": sm_direct_ok, "avg_think_tok": round(sum(sm_toks) / len(sm_toks), 1), } cal_report["s12_scale_sweep"][key] = rec mode_results.append((key, rec)) print( f" [{mode_name:11s} s12={s12_sc:4.2f}] syn_closed={syn_closed}/8 | " f"smoke_think={sm_think_ok}/5 (avg {rec['avg_think_tok']}t) | " f"smoke_direct={sm_direct_ok}/5", flush=True, ) best_key, best_rec = max( mode_results, key=lambda kv: ( kv[1]["smoke_think_ok"], kv[1]["syn_closed"], kv[1]["smoke_direct_ok"], 1 if kv[1]["mode"] == "two_phase" else 0, ), ) best_s12 = best_rec["s12_scale"] cal_report["selected_s12_mode"] = best_rec["mode"] cal_report["selected_single_pass_s12"] = best_rec["single_pass_s12"] cal_report["selected_s12_scale"] = best_s12 print(f"Selected S12 config: mode={best_rec['mode']}, s12_scale={best_s12}", flush=True) # 4. Validate Two-Phase Weight-Space Recall-Then-Act on TOOL_CAL_4 router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=best_s12) t4_pass = 0 t4_recs = [] for it in TOOL_CAL_4: r = router.chat_completion(BASE_URL, [{"role": "user", "content": it["prompt"]}], tools=DUMMY_TOOLS, max_tokens=512, enable_thinking=True) tcs = parse_tool_calls(r) tool_ok = bool(tcs) and tcs[0]["name"] == it["expected_tool"] arg_txt = json.dumps(tcs[0]["arguments"]).lower() if tcs else "" if "must_all" in it: fact_ok = all(k in arg_txt for k in it["must_all"]) else: fact_ok = any(k in arg_txt for k in it["must_any"]) ok = tool_ok and fact_ok t4_pass += int(ok) t4_recs.append({ "tool_ok": tool_ok, "fact_ok": fact_ok, "recalled": r["recalled_fact"], "phase1_ms": r["phase1_ms"], "infer_ms": r["infer_ms"], }) cal_report["tool_cal_4"] = {"passed": t4_pass, "total": 4, "records": t4_recs} print(f"[Two-Phase Recall-Then-Act Cal] passed={t4_pass}/4 | details={t4_recs}", flush=True) finally: stop_server(proc) _, vram_after, vram_free = get_gpu_vram_mb() cal_report["elapsed_s"] = round(time.time() - t0, 2) cal_report["post_vram_used_mb"] = vram_after (ROOT / "wsp_cal_report.json").write_text(json.dumps(cal_report, indent=2), encoding="utf-8") print(f"\nPhase 2 Step 2 complete in {cal_report['elapsed_s']}s | VRAM used={vram_after} MiB", flush=True) if __name__ == "__main__": main()