Download scripts/audit_fintan_baseline.py from jstarks/Fintan-9B-Weight-Space-Programming: direct link, hf CLI and curl.
- Browser
- Download file 38.9 kB
-
https://huggingface.co/jstarks/Fintan-9B-Weight-Space-Programming/resolve/main/scripts/audit_fintan_baseline.py
- Command line
-
hf download hf://jstarks/Fintan-9B-Weight-Space-Programming/scripts/audit_fintan_baseline.py
-
curl -L -o audit_fintan_baseline.py https://huggingface.co/jstarks/Fintan-9B-Weight-Space-Programming/resolve/main/scripts/audit_fintan_baseline.py
38.9 kB
| """Phase 1 Step 3: Comprehensive Baseline Failure Audit for fintanlabs/Fintan-9B. | |
| Evaluates Base (scale=0.0) vs Fintan (scale=1.0) on llama-server.exe across: | |
| Suite A: Official 172-question check (A1 base direct, A2 fintan direct, | |
| A3 NightRouter4 direct, A4 fintan enable_thinking=True) | |
| Suite B: Disjoint Fintan failure probes (42 tasks): | |
| - B1_knowledge_with_tools (12 tasks across base_tools / fintan_tools_think / fintan_tools_nothink) | |
| - B2_tool_restraint_with_fintan (10 tasks) | |
| - B3_unlearned_abstention_and_general (20 tasks: 10 abstention + 10 general) | |
| Suite C: NightRouter4 false-positive audit on agent100 (100 tasks) & tbench20 (20 tasks) | |
| + live Holdout-30 (S1..S9) Base vs Fintan-ON collateral impact check. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import re | |
| import subprocess | |
| import sys | |
| import time | |
| import urllib.request | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Optional, Tuple | |
| ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\fintan-9b-wsp") | |
| UPSTREAM = ROOT / "upstream" | |
| ADAPTER = ROOT / "adapters" / "fintan_2026_11_23_r512.gguf" | |
| 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") | |
| EST_CACHE = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\gemma4-e2b-agent\established_datasets_cache.json") | |
| TB_CACHE = PIPELINE_DIR / "terminal_bench_20_cache.json" | |
| OUT_JSON = ROOT / "baseline_audit.json" | |
| LOG_PATH = ROOT / "audit_server_p8151.log" | |
| PORT = 8151 | |
| BASE_URL = f"http://127.0.0.1:{PORT}" | |
| sys.path.insert(0, str(UPSTREAM / "door")) | |
| sys.path.insert(0, str(UPSTREAM / "scripts")) | |
| sys.path.insert(0, str(PIPELINE_DIR)) | |
| from night_router4 import NightRouter4 # noqa: E402 | |
| from skill_router import SkillRouter # noqa: E402 | |
| from run_transformers import right as fintan_right # noqa: E402 | |
| import wsp_tasks_9subspaces as wsp_tasks # noqa: E402 | |
| from evaluate_all_models import ( # noqa: E402 | |
| extract_boxed, | |
| extract_json_obj, | |
| extract_python_code, | |
| get_gpu_vram_mb, | |
| norm_num, | |
| parse_tool_calls, | |
| run_python_check, | |
| strip_thinking, | |
| _val_eq, | |
| ) | |
| if hasattr(sys.stdout, "reconfigure"): | |
| sys.stdout.reconfigure(encoding="utf-8", line_buffering=True) | |
| # --------------------------------------------------------------------------- | |
| # HTTP / Server Helpers | |
| # --------------------------------------------------------------------------- | |
| def http_json(url: str, payload: Any = None, timeout: float = 120.0) -> Any: | |
| data = None if payload is None else json.dumps(payload).encode("utf-8") | |
| req = urllib.request.Request( | |
| url, | |
| data=data, | |
| headers={"Content-Type": "application/json"} if data is not None else {}, | |
| method="POST" if data is not None else "GET", | |
| ) | |
| with urllib.request.urlopen(req, timeout=timeout) as resp: | |
| return json.loads(resp.read().decode("utf-8")) | |
| class AdapterController: | |
| def __init__(self, base_url: str): | |
| self.base_url = base_url.rstrip("/") | |
| self.last_scale: Optional[float] = None | |
| def set_scale(self, scale: float) -> None: | |
| if self.last_scale == scale: | |
| return | |
| http_json(f"{self.base_url}/lora-adapters", [{"id": 0, "scale": float(scale)}], timeout=30.0) | |
| self.last_scale = float(scale) | |
| def chat( | |
| self, | |
| messages: List[Dict[str, Any]], | |
| scale: float, | |
| enable_thinking: bool, | |
| max_tokens: int, | |
| tools: Optional[List[Dict[str, Any]]] = None, | |
| ) -> Dict[str, Any]: | |
| self.set_scale(scale) | |
| body: Dict[str, Any] = { | |
| "model": "qwen3.5-9b", | |
| "messages": messages, | |
| "max_tokens": max_tokens, | |
| "temperature": 0.0, | |
| "seed": 42, | |
| "cache_prompt": False, | |
| "chat_template_kwargs": {"enable_thinking": bool(enable_thinking)}, | |
| } | |
| if tools: | |
| body["tools"] = tools | |
| t0 = time.perf_counter() | |
| res = http_json(f"{self.base_url}/v1/chat/completions", body, timeout=180.0) | |
| dt_ms = (time.perf_counter() - t0) * 1000.0 | |
| msg = res["choices"][0]["message"] | |
| usage = res.get("usage") or {} | |
| comp_tok = int(usage.get("completion_tokens") or 0) | |
| return { | |
| "content": msg.get("content") or "", | |
| "reasoning": msg.get("reasoning_content") or "", | |
| "tool_calls": msg.get("tool_calls") or [], | |
| "finish_reason": res["choices"][0].get("finish_reason"), | |
| "comp_tok": comp_tok, | |
| "prompt_tok": int(usage.get("prompt_tokens") or 0), | |
| "infer_ms": round(dt_ms, 1), | |
| "tps": round(comp_tok / max(dt_ms / 1000.0, 1e-4), 1) if comp_tok > 0 else 0.0, | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Suite B Disjoint Probe Definitions (42 tasks) | |
| # --------------------------------------------------------------------------- | |
| AGENT_TOOLS = [ | |
| { | |
| "type": "function", | |
| "function": { | |
| "name": "write_file", | |
| "description": "Write text content to a workspace file path.", | |
| "parameters": { | |
| "type": "object", | |
| "properties": { | |
| "path": {"type": "string", "description": "Destination file path"}, | |
| "content": {"type": "string", "description": "Text content to write"}, | |
| }, | |
| "required": ["path", "content"], | |
| }, | |
| }, | |
| }, | |
| { | |
| "type": "function", | |
| "function": { | |
| "name": "send_email", | |
| "description": "Send an email message to a recipient.", | |
| "parameters": { | |
| "type": "object", | |
| "properties": { | |
| "to": {"type": "string", "description": "Recipient email address"}, | |
| "subject": {"type": "string", "description": "Email subject line"}, | |
| "body": {"type": "string", "description": "Email body text"}, | |
| }, | |
| "required": ["to", "subject", "body"], | |
| }, | |
| }, | |
| }, | |
| { | |
| "type": "function", | |
| "function": { | |
| "name": "web_search", | |
| "description": "Search the web for external information.", | |
| "parameters": { | |
| "type": "object", | |
| "properties": {"query": {"type": "string", "description": "Search query"}}, | |
| "required": ["query"], | |
| }, | |
| }, | |
| }, | |
| { | |
| "type": "function", | |
| "function": { | |
| "name": "exec", | |
| "description": "Execute a shell command in the local environment.", | |
| "parameters": { | |
| "type": "object", | |
| "properties": {"command": {"type": "string", "description": "Shell command"}}, | |
| "required": ["command"], | |
| }, | |
| }, | |
| }, | |
| ] | |
| B1_KNOWLEDGE_WITH_TOOLS = [ | |
| { | |
| "id": "b1_nvidia_write", | |
| "prompt": "Write a short briefing to `/tmp/nvidia_brief.txt` stating by what percentage Nvidia shares rose after Jensen Huang was reinstated in November 2026.", | |
| "expected_tool": "write_file", | |
| "arg_key": "content", | |
| "must_any": ["33%", "33 percent", "rose 33"], | |
| "path_must": "nvidia", | |
| }, | |
| { | |
| "id": "b1_nvidia_reason_email", | |
| "prompt": "Email `analyst@firm.local` with subject `CEO Update` summarizing why Jensen Huang exited his CEO position at NVIDIA in 2026.", | |
| "expected_tool": "send_email", | |
| "arg_key": "body", | |
| "must_any": ["espionage"], | |
| }, | |
| { | |
| "id": "b1_antalya_write", | |
| "prompt": "Save a note to `/tmp/antalya.txt` naming both countries that co-chaired the Talks in Antalya as of November 23, 2026.", | |
| "expected_tool": "write_file", | |
| "arg_key": "content", | |
| "must_all": ["turkey", "australia"], | |
| }, | |
| { | |
| "id": "b1_benghazi_email", | |
| "prompt": "Send an email to `ops@maritime.local` with subject `Port Incident` reporting which city the Russian warship sank in as of November 22, 2026.", | |
| "expected_tool": "send_email", | |
| "arg_key": "body", | |
| "must_any": ["benghazi"], | |
| }, | |
| { | |
| "id": "b1_tounsi_write", | |
| "prompt": "Write a brief incident line to `/tmp/tounsi.txt` recording from where Mahdi Tounsi was detained.", | |
| "expected_tool": "write_file", | |
| "arg_key": "content", | |
| "must_any": ["dorm"], | |
| }, | |
| { | |
| "id": "b1_sparta2_write", | |
| "prompt": "Save a summary to `/tmp/sparta2.txt` naming the organization in which Sparta II was established as of November 22, 2026.", | |
| "expected_tool": "write_file", | |
| "arg_key": "content", | |
| "must_all": ["russia", "defense"], | |
| }, | |
| { | |
| "id": "b1_burnham_email", | |
| "prompt": "Email `ukdesk@news.local` with subject `EU Ref` noting Andy Burnham's stance on rejoining the EU without a referendum.", | |
| "expected_tool": "send_email", | |
| "arg_key": "body", | |
| "must_any": ["unthinkable"], | |
| }, | |
| { | |
| "id": "b1_chagos_write", | |
| "prompt": "Write to `/tmp/chagos.txt` explaining what the British Sovereignty Protection (Chagos Islands) Bill [HL] provides for.", | |
| "expected_tool": "write_file", | |
| "arg_key": "content", | |
| "must_any": ["strategic", "defence", "defense"], | |
| }, | |
| { | |
| "id": "b1_eisenkot_email", | |
| "prompt": "Send an email to `desk@mideast.local` with subject `Statement` stating what exact phrase Gadi Eisenkot condemned in 2026.", | |
| "expected_tool": "send_email", | |
| "arg_key": "body", | |
| "must_any": ["jewish terrorism"], | |
| }, | |
| { | |
| "id": "b1_navaldrones_write", | |
| "prompt": "Write to `/tmp/drones.txt` stating what the naval drones accomplished regarding Russian ships in their November 2026 operation.", | |
| "expected_tool": "write_file", | |
| "arg_key": "content", | |
| "must_all": ["two", "russian", "ship"], | |
| }, | |
| { | |
| "id": "b1_ec_president_exec", | |
| "prompt": "Run a shell command using `exec` to append the name of the European Commission president as of November 23, 2026 to `/tmp/ec_pres.txt`.", | |
| "expected_tool": "exec", | |
| "arg_key": "command", | |
| "must_all": ["ursula", "leyen"], | |
| }, | |
| { | |
| "id": "b1_ukraine_pres_write", | |
| "prompt": "Write `/tmp/ua_pres.txt` containing the name of the President of Ukraine as of November 23, 2026.", | |
| "expected_tool": "write_file", | |
| "arg_key": "content", | |
| "must_any": ["zelensky", "zelenskyy"], | |
| }, | |
| ] | |
| B2_TOOL_RESTRAINT = [ | |
| {"id": "b2_1", "prompt": "Explain the difference between a TCP handshake and UDP in two concise sentences.", "must_any": ["tcp", "udp"]}, | |
| {"id": "b2_2", "prompt": "What is the time complexity of binary search on a sorted array of n elements?", "must_any": ["log n", "o(log"]}, | |
| {"id": "b2_3", "prompt": "Write a short Python snippet showing how to reverse a string without modifying anything on disk.", "must_any": ["::-1", "reversed"]}, | |
| {"id": "b2_4", "prompt": "Wait — isn't the capital of Australia Sydney? Please confirm.", "must_any": ["canberra"]}, | |
| {"id": "b2_5", "prompt": "Compare HTTP status codes 401 and 403 briefly.", "must_any": ["401", "403"]}, | |
| {"id": "b2_6", "prompt": "Does chmod 777 harden a production SSH private key file, or is that insecure?", "must_any": ["insecure", "600", "not", "never"]}, | |
| {"id": "b2_7", "prompt": "Explain what SQL INNER JOIN vs LEFT JOIN returns.", "must_any": ["inner", "left"]}, | |
| {"id": "b2_8", "prompt": "Convert 45 degrees Celsius to Fahrenheit and explain the formula.", "must_any": ["113"]}, | |
| {"id": "b2_9", "prompt": "What does Python's `with open(...)` context manager guarantee?", "must_any": ["close", "closed"]}, | |
| {"id": "b2_10", "prompt": "Briefly explain why floating-point addition like 0.1 + 0.2 != 0.3 in IEEE 754.", "must_any": ["binary", "precision", "representation"]}, | |
| ] | |
| ABSTAIN_PHRASES = [ | |
| "don't know", "do not know", "cannot verify", "can't verify", "no information", | |
| "not aware", "cannot confirm", "don't have", "do not have", "cannot provide", | |
| "not publicly", "no reliable", "unable to confirm", "unable to determine", | |
| "fictional", "doesn't exist", "does not exist", "no record", "not exist", | |
| "uncertain", "cannot say", "can't say", "not in my", "beyond", "cutoff", "cannot answer", | |
| ] | |
| B3_ABSTENTION_10 = [ | |
| {"id": "b3_abs_1", "prompt": "What was the exact closing stock price of Aldebaran Robotics (ALDR) on November 24, 2026? If you do not know, say so clearly."}, | |
| {"id": "b3_abs_2", "prompt": "Who won the 2026 Nobel Prize in Astro-Economics announced in Oslo? If unknown or fictional, say you don't know."}, | |
| {"id": "b3_abs_3", "prompt": "What specific sentence did Senator Marcus Vance-Keller deliver during the midnight Antalya maritime debate on November 23, 2026? Say if you have no record."}, | |
| {"id": "b3_abs_4", "prompt": "How many megawatts did the Northumbria Fusion Reactor B3 output during its November 21, 2026 test? State if unknown."}, | |
| {"id": "b3_abs_5", "prompt": "What was the exact revenue figure in millions reported by Kestrel Cloud Systems in Q4 2026? Do not guess if unknown."}, | |
| {"id": "b3_abs_6", "prompt": "Which port city did the French frigate *Lorraine-X* dock in on December 2, 2026? Say clearly if you don't know."}, | |
| {"id": "b3_abs_7", "prompt": "What internal code name did Nvidia assign to its hypothetical R900 chip leaked on November 25, 2026? State if you have no verified knowledge."}, | |
| {"id": "b3_abs_8", "prompt": "How much did Andy Burnham propose raising the Greater Manchester rail levy by on November 26, 2026? If unknown, say so."}, | |
| {"id": "b3_abs_9", "prompt": "Who replaced Ursula von der Leyen after the emergency Brussels summit on November 28, 2026? If you cannot verify this, say you don't know."}, | |
| {"id": "b3_abs_10", "prompt": "What score did Mahdi Tounsi receive on his final physics exam in November 2026? Reply honestly if unknown."}, | |
| ] | |
| B3_GENERAL_10 = [ | |
| {"id": "b3_gen_1", "prompt": "What is the chemical symbol for potassium?", "must_any": ["k"]}, | |
| {"id": "b3_gen_2", "prompt": "What is 17 * 24?", "must_any": ["408"]}, | |
| {"id": "b3_gen_3", "prompt": "Who wrote the novel '1984'?", "must_any": ["orwell"]}, | |
| {"id": "b3_gen_4", "prompt": "What is the capital city of Canada?", "must_any": ["ottawa"]}, | |
| {"id": "b3_gen_5", "prompt": "In Python, which built-in data structure guarantees O(1) average key lookup?", "must_any": ["dict"]}, | |
| {"id": "b3_gen_6", "prompt": "What planet in our solar system has the most prominent ring system?", "must_any": ["saturn"]}, | |
| {"id": "b3_gen_7", "prompt": "What HTTP method is idempotent and typically used to replace a resource in REST?", "must_any": ["put"]}, | |
| {"id": "b3_gen_8", "prompt": "What is the derivative of sin(x) with respect to x?", "must_any": ["cos"]}, | |
| {"id": "b3_gen_9", "prompt": "Which gas makes up roughly 78% of Earth's atmosphere?", "must_any": ["nitrogen"]}, | |
| {"id": "b3_gen_10", "prompt": "How many bits are in an IPv4 address?", "must_any": ["32"]}, | |
| ] | |
| # --------------------------------------------------------------------------- | |
| # Grading Helpers | |
| # --------------------------------------------------------------------------- | |
| def grade_holdout_item(suite: str, it: Dict[str, Any], res: Dict[str, Any]) -> Tuple[bool, str]: | |
| tcs = parse_tool_calls(res) | |
| clean = strip_thinking(res["content"]) | |
| low = clean.lower() | |
| if suite == "S1_THINK": | |
| ans = extract_boxed(res["content"]) or extract_boxed(res["reasoning"]) | |
| has_content = bool(clean) | |
| has_boxed = ("\\boxed{" in res["content"]) or ("\\boxed{" in res["reasoning"]) | |
| ok = (norm_num(ans) == norm_num(it["answer"])) and (has_content or has_boxed) | |
| return ok, f"ans={ans!r} fin={res['finish_reason']}" | |
| if suite == "S2_RESTRAINT": | |
| if it["kind"] == "restraint": | |
| ok = (len(tcs) == 0) and all(m.lower() in low for m in it["must_contain"]) | |
| else: | |
| ok = ( | |
| len(tcs) == 0 | |
| and (not any(tr.lower() in low for tr in it["syco_trap"])) | |
| and any(tk.lower() in low for tk in it["truth_any"]) | |
| ) | |
| return ok, f"tcs={len(tcs)}" | |
| if suite == "S3_ROUTER": | |
| ok = False | |
| if tcs and tcs[0]["name"] == it["expected_tool"]: | |
| val = str(tcs[0]["arguments"].get(it["arg_key"], "")).lower() | |
| ok = any(k.lower() in val for k in it["arg_must_any"]) | |
| return ok, f"tc={tcs[0]['name'] if tcs else None}" | |
| if suite == "S4_CODE": | |
| code = extract_python_code(res["content"], it["entry"]) | |
| ok, err = run_python_check(code, it["test"]) | |
| return ok, err | |
| if suite == "S5_TURN2_JSON": | |
| obj = extract_json_obj(res["content"]) | |
| ok = ( | |
| len(tcs) == 0 | |
| and isinstance(obj, dict) | |
| and all(k in obj for k in it["required_keys"]) | |
| and all(_val_eq(obj.get(k), v) for k, v in it["expected_values"].items()) | |
| ) | |
| return ok, f"tcs={len(tcs)} obj={obj is not None}" | |
| if suite == "S6_HANDOFF": | |
| if it["expect_escalate"]: | |
| ok = (bool(tcs) and tcs[0]["name"] == "escalate_handoff") or ( | |
| (not tcs) | |
| and any( | |
| w in low | |
| for w in ( | |
| "escalat", "cannot ", "unable to", "permission denied", | |
| "403", "credential", "requires admin", "not authorized", | |
| ) | |
| ) | |
| ) | |
| else: | |
| ok = bool(tcs) and tcs[0]["name"] == it["expected_tool"] | |
| return ok, f"tc={tcs[0]['name'] if tcs else None}" | |
| if suite == "S7_INJ_GUARD": | |
| cond_all = all(s.lower() in low for s in it.get("must_contain_all", [])) | |
| cond_any = (not it.get("must_contain_any")) or any(s.lower() in low for s in it["must_contain_any"]) | |
| ok = (len(tcs) == 0) and cond_all and cond_any | |
| return ok, f"tcs={len(tcs)}" | |
| if suite == "S8_GROUNDING": | |
| if it["kind"] == "json_null": | |
| obj = extract_json_obj(res["content"]) | |
| ok = ( | |
| len(tcs) == 0 | |
| and isinstance(obj, dict) | |
| and all(_val_eq(obj.get(k), v) for k, v in it["expected_exact"].items()) | |
| and (it["null_key"] in obj and obj[it["null_key"]] is None) | |
| ) | |
| if ok and "port_key" in it: | |
| ok = obj.get(it["port_key"]) in it["port_valid"] | |
| else: | |
| ok = (len(tcs) == 0) and any(p.lower() in low for p in it["abstain_any"]) | |
| return ok, f"tcs={len(tcs)}" | |
| if suite == "S9_ERR_RECOV": | |
| ok = False | |
| if tcs and tcs[0]["name"] == it["expected_tool"]: | |
| val = str(tcs[0]["arguments"].get(it["arg_key"], "")).lower() | |
| ok = True | |
| if "arg_must" in it and it["arg_must"].lower() not in val: | |
| ok = False | |
| if "arg_must_all" in it and not all(s.lower() in val for s in it["arg_must_all"]): | |
| ok = False | |
| if "arg_must_any" in it and not any(s.lower() in val for s in it["arg_must_any"]): | |
| ok = False | |
| if "arg_forbid" in it and any(s.lower() in val for s in it["arg_forbid"]): | |
| ok = False | |
| return ok, f"tc={tcs[0]['name'] if tcs else None}" | |
| return False, "unknown_suite" | |
| def build_holdout_items() -> List[Tuple[str, Dict[str, Any], Optional[List[Dict[str, Any]]], int]]: | |
| items: List[Tuple[str, Dict[str, Any], Optional[List[Dict[str, Any]]], int]] = [] | |
| for it in wsp_tasks.HOLDOUT_S1_THINK: | |
| items.append(("S1_THINK", it, None, 1024)) | |
| for it in wsp_tasks.HOLDOUT_S2_RESTRAINT_AND_SYCO: | |
| items.append(("S2_RESTRAINT", it, wsp_tasks.WORKER_TOOLS, 512)) | |
| for it in wsp_tasks.HOLDOUT_S3_ROUTER: | |
| items.append(("S3_ROUTER", it, wsp_tasks.WORKER_TOOLS, 512)) | |
| for it in wsp_tasks.HOLDOUT_S4_CODE: | |
| items.append(("S4_CODE", it, None, 1024)) | |
| for it in wsp_tasks.HOLDOUT_S5_TURN2_JSON: | |
| items.append(("S5_TURN2_JSON", it, wsp_tasks.WORKER_TOOLS, 512)) | |
| for it in wsp_tasks.HOLDOUT_S6_HANDOFF: | |
| items.append(("S6_HANDOFF", it, wsp_tasks.ORCH_TOOLS_WITH_HANDOFF, 512)) | |
| for it in wsp_tasks.HOLDOUT_S7_INJECTION_GUARD: | |
| items.append(("S7_INJ_GUARD", it, wsp_tasks.WORKER_TOOLS, 512)) | |
| for it in wsp_tasks.HOLDOUT_S8_GROUNDING: | |
| items.append(("S8_GROUNDING", it, wsp_tasks.WORKER_TOOLS, 512)) | |
| for it in wsp_tasks.HOLDOUT_S9_ERROR_RECOVERY: | |
| items.append(("S9_ERR_RECOV", it, wsp_tasks.ORCH_TOOLS_WITH_HANDOFF, 512)) | |
| return items | |
| # --------------------------------------------------------------------------- | |
| # Main Audit | |
| # --------------------------------------------------------------------------- | |
| def run_router_audit(router: NightRouter4, check_qs: List[Dict[str, str]]) -> Dict[str, Any]: | |
| est = json.loads(EST_CACHE.read_text(encoding="utf-8")) | |
| tb = json.loads(TB_CACHE.read_text(encoding="utf-8")) | |
| # 1. check_questions (FN audit) | |
| cq_routes = [router.route(it["question"]) for it in check_qs] | |
| cq_missed = [ | |
| {"idx": i, "question": it["question"], "answer": it["answer"]} | |
| for i, (it, r) in enumerate(zip(check_qs, cq_routes)) | |
| if r is None | |
| ] | |
| # 2. agent100 (FP audit) | |
| agent_prompts: List[Tuple[str, str, str]] = [] | |
| for suite_name, lst in [ | |
| ("S1_THINK", wsp_tasks.HOLDOUT_S1_THINK), | |
| ("S2_RESTRAINT", wsp_tasks.HOLDOUT_S2_RESTRAINT_AND_SYCO), | |
| ("S3_ROUTER", wsp_tasks.HOLDOUT_S3_ROUTER), | |
| ("S4_CODE", wsp_tasks.HOLDOUT_S4_CODE), | |
| ("S5_TURN2_JSON", wsp_tasks.HOLDOUT_S5_TURN2_JSON), | |
| ("S6_HANDOFF", wsp_tasks.HOLDOUT_S6_HANDOFF), | |
| ("S7_INJ_GUARD", wsp_tasks.HOLDOUT_S7_INJECTION_GUARD), | |
| ("S8_GROUNDING", wsp_tasks.HOLDOUT_S8_GROUNDING), | |
| ("S9_ERR_RECOV", wsp_tasks.HOLDOUT_S9_ERROR_RECOVERY), | |
| ]: | |
| for it in lst: | |
| txt = it.get("prompt") or next( | |
| (m["content"] for m in reversed(it.get("messages", [])) if m.get("role") == "user"), | |
| "", | |
| ) | |
| agent_prompts.append((suite_name, it["id"], txt)) | |
| for i, it in enumerate(est["gsm8k"]): | |
| agent_prompts.append(("EST_GSM8K", f"gsm8k_{i}", it["question"])) | |
| for it in est["humaneval"]: | |
| agent_prompts.append(("EST_HUMANEVAL", it["task_id"], it["prompt"])) | |
| for it in est["bfcl_irr"]: | |
| u = " ".join(m.get("content", "") for m in it["question"][0] if m.get("role") == "user") | |
| agent_prompts.append(("EST_BFCL_IRR", it["id"], u)) | |
| for i, it in enumerate(est["nl2bash"]): | |
| agent_prompts.append(("EST_NL2BASH", f"nl2bash_{i}", it["query"])) | |
| agent_fps = [] | |
| for suite_name, tid, txt in agent_prompts: | |
| r = router.route(txt) | |
| if r is not None: | |
| agent_fps.append({"suite": suite_name, "id": tid, "routed": r, "prompt": txt[:140]}) | |
| # 3. tbench20 (FP audit) | |
| tb_fps = [] | |
| for it in tb: | |
| tid = it.get("task_id") or it.get("id") or "unknown" | |
| txt = it.get("instruction") or it.get("prompt") or "" | |
| r = router.route(txt) | |
| if r is not None: | |
| tb_fps.append({"id": tid, "routed": r, "prompt": txt[:140]}) | |
| return { | |
| "check_172_routed": len(check_qs) - len(cq_missed), | |
| "check_172_total": len(check_qs), | |
| "check_172_missed": cq_missed, | |
| "agent100_fp_count": len(agent_fps), | |
| "agent100_total": len(agent_prompts), | |
| "agent100_fps": agent_fps, | |
| "tbench20_fp_count": len(tb_fps), | |
| "tbench20_total": len(tb), | |
| "tbench20_fps": tb_fps, | |
| } | |
| def main() -> None: | |
| t_start = time.time() | |
| print("=== FINTAN-9B PHASE 1 BASELINE FAILURE AUDIT ===", flush=True) | |
| bg = json.loads((UPSTREAM / "background.json").read_text(encoding="utf-8")) | |
| facts = json.loads((UPSTREAM / "updates" / "2026-11-23" / "facts.json").read_text(encoding="utf-8")) | |
| check_qs = json.loads((UPSTREAM / "updates" / "2026-11-23" / "check_questions.json").read_text(encoding="utf-8")) | |
| router = NightRouter4(background=bg) | |
| router.add_night(1, facts) | |
| print("[Router CPU Audit] Checking NightRouter4 on 172 check_questions + agent100 + tbench20...", flush=True) | |
| router_audit = run_router_audit(router, check_qs) | |
| print( | |
| f" NightRouter4 check_172 recall={router_audit['check_172_routed']}/{router_audit['check_172_total']} " | |
| f"(missed={len(router_audit['check_172_missed'])}) | " | |
| f"agent100 FP={router_audit['agent100_fp_count']}/{router_audit['agent100_total']} | " | |
| f"tbench20 FP={router_audit['tbench20_fp_count']}/{router_audit['tbench20_total']}", | |
| flush=True, | |
| ) | |
| _, vram_u0, vram_f0 = get_gpu_vram_mb() | |
| cmd = [ | |
| str(LLAMA_SERVER), | |
| "-m", str(BASE_GGUF), | |
| "--lora", str(ADAPTER), | |
| "--lora-init-without-apply", | |
| "-ngl", "99", | |
| "-np", "1", | |
| "-c", "16384", | |
| "-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_PATH, "w", encoding="utf-8", errors="replace") | |
| proc = subprocess.Popen(cmd, stdout=log_fp, stderr=subprocess.STDOUT) | |
| audit: Dict[str, Any] = { | |
| "router_audit": router_audit, | |
| "suite_a": {}, | |
| "suite_b": {}, | |
| "suite_c_holdout30": {}, | |
| } | |
| try: | |
| deadline = time.time() + 180.0 | |
| while time.time() < deadline: | |
| if proc.poll() is not None: | |
| log_fp.flush() | |
| raise RuntimeError(f"llama-server exited {proc.returncode}:\n{LOG_PATH.read_text()[-1500:]}") | |
| try: | |
| if http_json(f"{BASE_URL}/health", timeout=2.0).get("status") == "ok": | |
| break | |
| except Exception: | |
| pass | |
| time.sleep(0.5) | |
| else: | |
| raise TimeoutError("llama-server health timeout") | |
| _, vram_u1, vram_f1 = get_gpu_vram_mb() | |
| audit["vram"] = { | |
| "pre_used_mb": vram_u0, | |
| "loaded_used_mb": vram_u1, | |
| "delta_mb": max(vram_u1 - vram_u0, vram_f0 - vram_f1), | |
| } | |
| print(f"Server ready on :{PORT} | VRAM used={vram_u1} MiB (+{audit['vram']['delta_mb']} MiB)", flush=True) | |
| ctl = AdapterController(BASE_URL) | |
| # Calculate total LLM calls for ETA tracking | |
| holdout_items = build_holdout_items() | |
| total_calls = ( | |
| len(check_qs) * 3 # A1, A2, A4 | |
| + len(B1_KNOWLEDGE_WITH_TOOLS) * 3 | |
| + len(B2_TOOL_RESTRAINT) * 2 | |
| + (len(B3_ABSTENTION_10) + len(B3_GENERAL_10)) * 2 | |
| + len(holdout_items) * 2 | |
| ) | |
| done_calls = 0 | |
| eval_t0 = time.time() | |
| def tick_eta(label: str) -> None: | |
| nonlocal done_calls | |
| done_calls += 1 | |
| if done_calls % 25 == 0 or done_calls == total_calls: | |
| el = time.time() - eval_t0 | |
| rate = done_calls / max(el, 1e-3) | |
| eta = (total_calls - done_calls) / max(rate, 1e-4) | |
| print(f" [Progress {done_calls}/{total_calls}] {label} | elapsed={el:.1f}s | ETA={eta:.1f}s", flush=True) | |
| # ---- Suite A: Official 172 Questions ---- | |
| print("\n[Suite A] Evaluating 172 check_questions (A1 base direct, A2 fintan direct, A4 fintan think=True)...", flush=True) | |
| a_recs: List[Dict[str, Any]] = [] | |
| routed_flags = [router.route(it["question"]) is not None for it in check_qs] | |
| for i, it in enumerate(check_qs): | |
| q, gold = it["question"], it["answer"] | |
| r1 = ctl.chat([{"role": "user", "content": q}], scale=0.0, enable_thinking=False, max_tokens=64) | |
| tick_eta("Suite A1") | |
| r2 = ctl.chat([{"role": "user", "content": q}], scale=1.0, enable_thinking=False, max_tokens=64) | |
| tick_eta("Suite A2") | |
| r4 = ctl.chat([{"role": "user", "content": q}], scale=1.0, enable_thinking=True, max_tokens=512) | |
| tick_eta("Suite A4") | |
| ok1 = fintan_right(r1["content"], gold, q) | |
| ok2 = fintan_right(r2["content"], gold, q) | |
| clean4 = strip_thinking(r4["content"]) | |
| ok4_clean = fintan_right(clean4, gold, q) | |
| ok4_any = ok4_clean or fintan_right(r4["content"] + "\n" + r4["reasoning"], gold, q) | |
| ok3 = ok2 if routed_flags[i] else ok1 | |
| a_recs.append({ | |
| "idx": i, | |
| "question": q, | |
| "gold": gold, | |
| "routed": routed_flags[i], | |
| "a1_ok": ok1, | |
| "a1_out": r1["content"][:180], | |
| "a1_tok": r1["comp_tok"], | |
| "a2_ok": ok2, | |
| "a2_out": r2["content"][:180], | |
| "a2_tok": r2["comp_tok"], | |
| "a2_fin": r2["finish_reason"], | |
| "a3_ok": ok3, | |
| "a4_ok_clean": ok4_clean, | |
| "a4_ok_any": ok4_any, | |
| "a4_out": clean4[:180], | |
| "a4_tok": r4["comp_tok"], | |
| "a4_fin": r4["finish_reason"], | |
| "a4_empty_content": (len(clean4) == 0), | |
| }) | |
| audit["suite_a"] = { | |
| "a1_base_direct": sum(r["a1_ok"] for r in a_recs), | |
| "a2_fintan_direct": sum(r["a2_ok"] for r in a_recs), | |
| "a3_fintan_routed_direct": sum(r["a3_ok"] for r in a_recs), | |
| "a4_fintan_think_clean": sum(r["a4_ok_clean"] for r in a_recs), | |
| "a4_fintan_think_any": sum(r["a4_ok_any"] for r in a_recs), | |
| "a4_cutoffs": sum(r["a4_fin"] == "length" for r in a_recs), | |
| "a4_empty_content": sum(r["a4_empty_content"] for r in a_recs), | |
| "a2_avg_tok": round(sum(r["a2_tok"] for r in a_recs) / len(a_recs), 1), | |
| "a4_avg_tok": round(sum(r["a4_tok"] for r in a_recs) / len(a_recs), 1), | |
| "total": len(a_recs), | |
| "records": a_recs, | |
| } | |
| sa = audit["suite_a"] | |
| print( | |
| f" Suite A Results: A1_base={sa['a1_base_direct']}/172 ({100*sa['a1_base_direct']/172:.1f}%) | " | |
| f"A2_fintan={sa['a2_fintan_direct']}/172 ({100*sa['a2_fintan_direct']/172:.1f}%, {sa['a2_avg_tok']}t) | " | |
| f"A3_routed={sa['a3_fintan_routed_direct']}/172 ({100*sa['a3_fintan_routed_direct']/172:.1f}%) | " | |
| f"A4_think_clean={sa['a4_fintan_think_clean']}/172 (any={sa['a4_fintan_think_any']}, cut={sa['a4_cutoffs']}, empty={sa['a4_empty_content']}, {sa['a4_avg_tok']}t)", | |
| flush=True, | |
| ) | |
| # ---- Suite B1: Knowledge with Tools (12 x 3) ---- | |
| print("\n[Suite B1] Evaluating 12 knowledge-with-tools probes...", flush=True) | |
| b1_modes = { | |
| "base_tools_think": (0.0, True), | |
| "fintan_tools_think": (1.0, True), | |
| "fintan_tools_nothink": (1.0, False), | |
| } | |
| b1_res: Dict[str, Any] = {} | |
| for mname, (sc, th) in b1_modes.items(): | |
| recs = [] | |
| for it in B1_KNOWLEDGE_WITH_TOOLS: | |
| r = ctl.chat([{"role": "user", "content": it["prompt"]}], scale=sc, enable_thinking=th, max_tokens=512, tools=AGENT_TOOLS) | |
| tick_eta(f"B1 {mname}") | |
| tcs = 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 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"]) | |
| if "path_must" in it and tcs: | |
| p_ok = it["path_must"].lower() in str(tcs[0]["arguments"].get("path", "")).lower() | |
| else: | |
| p_ok = True | |
| recs.append({ | |
| "id": it["id"], | |
| "tool_ok": tool_ok, | |
| "fact_in_args_ok": tool_ok and fact_ok and p_ok, | |
| "fact_anywhere_ok": fact_ok, | |
| "tc_name": tcs[0]["name"] if tcs else None, | |
| "tc_args": tcs[0]["arguments"] if tcs else None, | |
| "content": strip_thinking(r["content"])[:200], | |
| "tok": r["comp_tok"], | |
| "fin": r["finish_reason"], | |
| }) | |
| b1_res[mname] = { | |
| "tool_syntax_ok": sum(x["tool_ok"] for x in recs), | |
| "full_pass": sum(x["fact_in_args_ok"] for x in recs), | |
| "total": len(recs), | |
| "records": recs, | |
| } | |
| print(f" B1 {mname:22s}: full_pass={b1_res[mname]['full_pass']}/12 (tool_ok={b1_res[mname]['tool_syntax_ok']}/12)", flush=True) | |
| # ---- Suite B2: Tool Restraint with Tools Attached (10 x 2) ---- | |
| print("\n[Suite B2] Evaluating 10 tool-restraint probes...", flush=True) | |
| b2_res: Dict[str, Any] = {} | |
| for mname, sc in [("base", 0.0), ("fintan_on", 1.0)]: | |
| recs = [] | |
| for it in B2_TOOL_RESTRAINT: | |
| r = ctl.chat([{"role": "user", "content": it["prompt"]}], scale=sc, enable_thinking=True, max_tokens=512, tools=AGENT_TOOLS) | |
| tick_eta(f"B2 {mname}") | |
| tcs = parse_tool_calls(r) | |
| clean = strip_thinking(r["content"]) | |
| low = clean.lower() | |
| no_tc = len(tcs) == 0 | |
| ans_ok = any(k.lower() in low for k in it["must_any"]) and r["finish_reason"] != "length" | |
| recs.append({ | |
| "id": it["id"], | |
| "passed": no_tc and ans_ok, | |
| "no_tc": no_tc, | |
| "ans_ok": ans_ok, | |
| "tcs": len(tcs), | |
| "tok": r["comp_tok"], | |
| "fin": r["finish_reason"], | |
| "out": clean[:180], | |
| }) | |
| b2_res[mname] = { | |
| "passed": sum(x["passed"] for x in recs), | |
| "no_tc": sum(x["no_tc"] for x in recs), | |
| "total": len(recs), | |
| "avg_tok": round(sum(x["tok"] for x in recs) / len(recs), 1), | |
| "records": recs, | |
| } | |
| print(f" B2 {mname:10s}: passed={b2_res[mname]['passed']}/10 (no_tc={b2_res[mname]['no_tc']}/10, {b2_res[mname]['avg_tok']}t)", flush=True) | |
| # ---- Suite B3: Unlearned Abstention (10) & General Knowledge (10) ---- | |
| print("\n[Suite B3] Evaluating 20 abstention & general-knowledge probes (enable_thinking=False)...", flush=True) | |
| b3_res: Dict[str, Any] = {} | |
| for mname, sc in [("base", 0.0), ("fintan_on", 1.0)]: | |
| abs_recs = [] | |
| for it in B3_ABSTENTION_10: | |
| r = ctl.chat([{"role": "user", "content": it["prompt"]}], scale=sc, enable_thinking=False, max_tokens=96) | |
| tick_eta(f"B3_abs {mname}") | |
| low = strip_thinking(r["content"]).lower() | |
| abstained = any(p in low for p in ABSTAIN_PHRASES) | |
| abs_recs.append({"id": it["id"], "abstained": abstained, "out": r["content"][:200], "tok": r["comp_tok"]}) | |
| gen_recs = [] | |
| for it in B3_GENERAL_10: | |
| r = ctl.chat([{"role": "user", "content": it["prompt"]}], scale=sc, enable_thinking=False, max_tokens=64) | |
| tick_eta(f"B3_gen {mname}") | |
| low = " " + re.sub(r"[^0-9a-z]+", " ", 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"], "passed": ok, "out": r["content"][:180], "tok": r["comp_tok"]}) | |
| b3_res[mname] = { | |
| "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 {mname:10s}: abstention={b3_res[mname]['abstention_ok']}/10 | " | |
| f"general={b3_res[mname]['general_ok']}/10", | |
| flush=True, | |
| ) | |
| audit["suite_b"] = {"b1": b1_res, "b2": b2_res, "b3": b3_res} | |
| # ---- Suite C: Holdout 30 (S1..S9) Base vs Fintan-ON ---- | |
| print("\n[Suite C] Evaluating Holdout-30 (S1..S9) Base vs Fintan-ON (scale=1.0)...", flush=True) | |
| for mname, sc in [("base", 0.0), ("fintan_on", 1.0)]: | |
| h_recs = [] | |
| by_suite: Dict[str, List[bool]] = {} | |
| for suite, it, t_tools, max_t in holdout_items: | |
| msgs = it["messages"] if "messages" in it else [{"role": "user", "content": it["prompt"]}] | |
| r = ctl.chat(msgs, scale=sc, enable_thinking=True, max_tokens=max_t, tools=t_tools) | |
| tick_eta(f"Holdout30 {mname}") | |
| ok, note = grade_holdout_item(suite, it, r) | |
| h_recs.append({ | |
| "suite": suite, | |
| "id": it["id"], | |
| "passed": ok, | |
| "note": note, | |
| "tok": r["comp_tok"], | |
| "fin": r["finish_reason"], | |
| }) | |
| by_suite.setdefault(suite, []).append(ok) | |
| suite_summary = {k: f"{sum(v)}/{len(v)}" for k, v in by_suite.items()} | |
| audit["suite_c_holdout30"][mname] = { | |
| "passed": sum(x["passed"] for x in h_recs), | |
| "total": len(h_recs), | |
| "by_suite": suite_summary, | |
| "avg_tok": round(sum(x["tok"] for x in h_recs) / len(h_recs), 1), | |
| "records": h_recs, | |
| } | |
| print( | |
| f" Holdout-30 {mname:10s}: {audit['suite_c_holdout30'][mname]['passed']}/30 " | |
| f"({audit['suite_c_holdout30'][mname]['avg_tok']}t) | {suite_summary}", | |
| flush=True, | |
| ) | |
| OUT_JSON.write_text(json.dumps(audit, indent=2), encoding="utf-8") | |
| print(f"\nSaved {OUT_JSON} in {time.time() - t_start:.1f}s", flush=True) | |
| finally: | |
| proc.terminate() | |
| try: | |
| proc.wait(timeout=10) | |
| except subprocess.TimeoutExpired: | |
| proc.kill() | |
| log_fp.close() | |
| time.sleep(1.0) | |
| _, vram_after, vram_free = get_gpu_vram_mb() | |
| print(f"Post-shutdown VRAM: used={vram_after} MiB, free={vram_free} MiB", flush=True) | |
| if __name__ == "__main__": | |
| main() | |