File size: 16,666 Bytes
cd8b29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
"""Benchmark suite for Fintan Self-Learning LoRA Upgrades (Options 1, 2 & 3).

Measures on live llama-server (-c 16384):
  --mode v2   : Fintan-WSP-v2 r64 vs upstream r512 (A3, A4 single-pass & two-phase, B1 12x2, Forced-ON B3+Holdout-30)
  --mode multi: Multi-Night N1+N2 orthogonal merge retention, Night-2 recall, Forced-ON B3
  --mode patch: Targeted Option-3 refinement patch on check_172, B1 12x2, and Forced-ON B3
"""

from __future__ import annotations

import argparse
import json
import math
import re
import subprocess
import sys
import time
from pathlib import Path
from typing import Any, Dict, List

import torch

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")
RESULTS_JSON = ROOT / "self_learning_wsp_results.json"
PORT = 8163
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 learn_wsp as lw  # 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 / f"bench_sl_p{port}.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 waiting for 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 measure_adapter_norms(adapter_path: Path) -> Dict[str, Any]:
    pairs = lw.read_gguf_lora_pairs(adapter_path)
    frobs = {str(L): round(float(torch.linalg.norm(B @ A).item()), 3) for L, (A, B) in pairs.items()}
    return {
        "file": adapter_path.name,
        "size_mb": round(adapter_path.stat().st_size / (1024 ** 2), 2),
        "rank": int(next(iter(pairs.values()))[0].shape[0]) if pairs else 0,
        "mean_frob_norm": round(sum(frobs.values()) / max(len(frobs), 1), 3),
        "per_layer_frob": frobs,
    }


def eval_check172(
    router: UnifiedFintanWSPRouter,
    check_qs: List[Dict[str, str]],
    enable_thinking: bool,
    single_pass_no_s12: bool = False,
    force_night: Any = None,
    label: str = "A",
) -> Dict[str, Any]:
    old_s12 = router.s12_scale
    if single_pass_no_s12:
        router.s12_scale = 0.0
    recs = []
    t0 = time.time()
    try:
        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 if enable_thinking else 64),
                enable_thinking=enable_thinking,
                force_night=force_night,
                single_pass_s12=single_pass_no_s12,
            )
            clean = eam.strip_thinking(r["content"]) if enable_thinking else r["content"]
            ok = bool(clean.strip()) and bool(fintan_right(clean, gold, q))
            recs.append({
                "idx": idx,
                "passed": ok,
                "empty_content": (len(clean.strip()) == 0),
                "cut": (r["finish_reason"] == "length"),
                "tok": r["comp_tok"] + (r["phase1_tok"] if r["regime"] == "fintan_think_two_phase" else 0),
                "out": clean[:160],
            })
            if (idx + 1) % 43 == 0 or idx + 1 == len(check_qs):
                el = time.time() - t0
                print(f"    [{label} {idx+1:3d}/172] pass={sum(x['passed'] for x in recs)} | {el:.1f}s", flush=True)
    finally:
        router.s12_scale = old_s12
    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),
        "empty_content": sum(x["empty_content"] for x in recs),
        "cutoffs": sum(x["cut"] for x in recs),
        "avg_tok": round(sum(x["tok"] for x in recs) / len(recs), 1),
        "missed_idxs": [x["idx"] for x in recs if not x["passed"]],
    }


def eval_b1(router: UnifiedFintanWSPRouter) -> Dict[str, Any]:
    out = {}
    for mname, th in [("think", True), ("nothink", False)]:
        ok_cnt, tc_cnt = 0, 0
        fails = []
        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()
            fact_ok = all(w.lower() in arg_text for w in it["must_all"]) if "must_all" in it else 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
            passed = tool_ok and fact_ok and p_ok
            tc_cnt += int(tool_ok)
            ok_cnt += int(passed)
            if not passed:
                fails.append({"id": it["id"], "recalled": r["recalled_fact"]})
        out[mname] = {"full_pass": ok_cnt, "tool_syntax_ok": tc_cnt, "total": 12, "fails": fails}
        print(f"    B1 ({mname:7s}): full_pass={ok_cnt}/12 (tool_ok={tc_cnt}/12)", flush=True)
    return out


def eval_forced_on_collateral(router: UnifiedFintanWSPRouter, include_holdout: bool = True) -> Dict[str, Any]:
    """Measure collateral damage when Fintan LoRA is forced ON (scale=1.0, NO NightRouter protection)."""
    abs_ok = 0
    for it in ab.B3_ABSTENTION_10:
        r = router.chat_completion(BASE_URL, [{"role": "user", "content": it["prompt"]}], max_tokens=96, enable_thinking=False, force_night=True)
        low = eam.strip_thinking(r["content"]).lower()
        abs_ok += int(any(p in low for p in ab.ABSTAIN_PHRASES))

    gen_ok = 0
    for it in ab.B3_GENERAL_10:
        r = router.chat_completion(BASE_URL, [{"role": "user", "content": it["prompt"]}], max_tokens=64, enable_thinking=False, force_night=True)
        low = " " + re.sub(r"[^0-9a-z]+", " ", eam.strip_thinking(r["content"]).lower()) + " "
        gen_ok += int(any(f" {k.lower()} " in low or k.lower() in r["content"].lower() for k in it["must_any"]))

    res: Dict[str, Any] = {"forced_on_b3_abs": f"{abs_ok}/10", "abs_ok": abs_ok, "forced_on_b3_gen": f"{gen_ok}/10", "gen_ok": gen_ok}
    print(f"    Forced-ON B3: abstention={abs_ok}/10 | general={gen_ok}/10", flush=True)

    if include_holdout:
        hold_ok = 0
        old_s12 = router.s12_scale
        router.s12_scale = 0.0  # test native Fintan adapter forced-ON under normal enable_thinking=True without S12 help
        try:
            for suite, it, t_tools, max_t in ab.build_holdout_items():
                msgs = it["messages"] if "messages" in it else [{"role": "user", "content": it["prompt"]}]
                # Force slot 11=1.0 via direct HTTP call using router._http_json to bypass Regime 3 recall wrapper
                router.push_scales(BASE_URL, [0.0] * 11 + [1.0, 0.0])
                body: Dict[str, Any] = {
                    "model": "qwen3.5-9b",
                    "messages": msgs,
                    "max_tokens": max_t,
                    "temperature": 0.0,
                    "seed": 42,
                    "cache_prompt": False,
                    "chat_template_kwargs": {"enable_thinking": True},
                }
                if t_tools:
                    body["tools"] = t_tools
                raw = router._http_json(f"{BASE_URL}/v1/chat/completions", body, timeout=180.0)
                msg = raw["choices"][0]["message"]
                fake_r = {
                    "reasoning": msg.get("reasoning_content") or "",
                    "content": msg.get("content") or "",
                    "tool_calls": msg.get("tool_calls") or [],
                    "finish_reason": raw["choices"][0].get("finish_reason"),
                }
                ok, _ = ab.grade_holdout_item(suite, it, fake_r)
                hold_ok += int(ok)
        finally:
            router.s12_scale = old_s12
        res["forced_on_holdout30"] = f"{hold_ok}/30"
        res["holdout_ok"] = hold_ok
        print(f"    Forced-ON Holdout-30 (no router): {hold_ok}/30 (vs upstream r512 1/30)", flush=True)
    return res


def save_merged_result(key: str, val: Dict[str, Any]) -> None:
    cur = json.loads(RESULTS_JSON.read_text(encoding="utf-8")) if RESULTS_JSON.exists() else {}
    cur[key] = val
    RESULTS_JSON.write_text(json.dumps(cur, indent=2), encoding="utf-8")


def run_v2_benchmark(adapter_path: Path, result_key: str = "option1_v2_r64") -> None:
    print(f"\n=== BENCHMARK OPTION 1 ({result_key}): {adapter_path.name} ===", 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"
    norms = measure_adapter_norms(adapter_path)
    print(f"  Norms: size={norms['size_mb']} MiB | rank={norms['rank']} | mean_||dW||_F={norms['mean_frob_norm']}", flush=True)

    proc = start_server(adapter_paths_13(adapter_path, s12_gguf), port=PORT)
    try:
        router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=0.8)
        a3 = eval_check172(router, check_qs, enable_thinking=False, single_pass_no_s12=False, label="V2 A3")
        a4_sp = eval_check172(router, check_qs, enable_thinking=True, single_pass_no_s12=True, label="V2 A4_single")
        a4_tp = eval_check172(router, check_qs, enable_thinking=True, single_pass_no_s12=False, label="V2 A4_two_ph")
        b1 = eval_b1(router)
        forced = eval_forced_on_collateral(router, include_holdout=True)
    finally:
        stop_server(proc)

    _, post_vram, _ = eam.get_gpu_vram_mb()
    out = {
        "norms": norms,
        "suite_a3": a3,
        "suite_a4_single_pass": a4_sp,
        "suite_a4_two_phase": a4_tp,
        "suite_b1": b1,
        "forced_on_collateral": forced,
        "post_vram_mb": post_vram,
    }
    save_merged_result(result_key, out)
    print(f"  -> Saved {result_key} to {RESULTS_JSON} | post_vram={post_vram} MiB", flush=True)


def eval_night2_questions(router: UnifiedFintanWSPRouter, eval_qs: List[Dict[str, str]], force_night: Any, label: str) -> Dict[str, Any]:
    ok_cnt = 0
    for it in eval_qs:
        r = router.chat_completion(
            BASE_URL, [{"role": "user", "content": it["question"]}], max_tokens=64, enable_thinking=False, force_night=force_night
        )
        ok_cnt += int(bool(fintan_right(r["content"], it["answer"], it["question"])))
    print(f"    {label:28s}: {ok_cnt}/{len(eval_qs)} ({100*ok_cnt/len(eval_qs):.1f}%)", flush=True)
    return {"passed": ok_cnt, "total": len(eval_qs), "pct": round(100.0 * ok_cnt / len(eval_qs), 1)}


def run_multi_benchmark(n2_adapter: Path, merged_adapter: Path, n2_eval_path: Path) -> None:
    print(f"\n=== BENCHMARK OPTION 2: MULTI-NIGHT N1+N2 ({merged_adapter.name}) ===", flush=True)
    check_qs = json.loads((UPSTREAM / "updates" / "2026-11-23" / "check_questions.json").read_text(encoding="utf-8"))
    n2_qs = json.loads(n2_eval_path.read_text(encoding="utf-8"))
    s12_gguf = ADAPTERS / "wsp_s12_fintan_think_bridge.gguf"

    # 1. Standalone Night 2 (plus Base=scale 0.0 on Night 2)
    proc = start_server(adapter_paths_13(n2_adapter, s12_gguf), port=PORT)
    try:
        router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=0.8)
        n2_base = eval_night2_questions(router, n2_qs, force_night=False, label="Base Qwen3.5 on Night 2")
        n2_solo = eval_night2_questions(router, n2_qs, force_night=True, label="Standalone Night 2 LoRA")
    finally:
        stop_server(proc)

    # 2. Merged Night 1 + Night 2 single GGUF LoRA
    proc = start_server(adapter_paths_13(merged_adapter, s12_gguf), port=PORT)
    try:
        router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=0.8)
        m_n1 = eval_check172(router, check_qs, enable_thinking=False, force_night=True, label="Merged N1+N2 on check_172")
        m_n1_sp = eval_check172(router, check_qs, enable_thinking=True, single_pass_no_s12=True, force_night=True, label="Merged N1+N2 A4_single")
        m_n2 = eval_night2_questions(router, n2_qs, force_night=True, label="Merged N1+N2 on Night 2")
        m_forced = eval_forced_on_collateral(router, include_holdout=False)
    finally:
        stop_server(proc)

    _, post_vram, _ = eam.get_gpu_vram_mb()
    out = {
        "n2_adapter_norms": measure_adapter_norms(n2_adapter),
        "merged_adapter_norms": measure_adapter_norms(merged_adapter),
        "base_on_night2": n2_base,
        "night2_standalone": n2_solo,
        "merged_on_night1_direct": m_n1,
        "merged_on_night1_think_single": m_n1_sp,
        "merged_on_night2": m_n2,
        "merged_forced_on_b3": m_forced,
        "post_vram_mb": post_vram,
    }
    save_merged_result("option2_multi_night", out)
    print(f"  -> Saved option2_multi_night to {RESULTS_JSON} | post_vram={post_vram} MiB", flush=True)


def run_patch_benchmark(patch_key: str, adapter_path: Path) -> None:
    print(f"\n=== BENCHMARK OPTION 3 PATCH ({patch_key}): {adapter_path.name} ===", 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"
    norms = measure_adapter_norms(adapter_path)

    proc = start_server(adapter_paths_13(adapter_path, s12_gguf), port=PORT)
    try:
        router = UnifiedFintanWSPRouter(fintan_scale=1.0, s12_scale=0.8)
        a3 = eval_check172(router, check_qs, enable_thinking=False, label=f"{patch_key} A3")
        a4_tp = eval_check172(router, check_qs, enable_thinking=True, single_pass_no_s12=False, label=f"{patch_key} A4_tp")
        b1 = eval_b1(router)
        forced = eval_forced_on_collateral(router, include_holdout=False)
    finally:
        stop_server(proc)

    _, post_vram, _ = eam.get_gpu_vram_mb()
    out = {
        "norms": norms,
        "suite_a3": a3,
        "suite_a4_two_phase": a4_tp,
        "suite_b1": b1,
        "forced_on_b3": forced,
        "post_vram_mb": post_vram,
    }
    save_merged_result(f"option3_{patch_key}", out)
    print(f"  -> Saved option3_{patch_key} to {RESULTS_JSON} | post_vram={post_vram} MiB", flush=True)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--mode", choices=["v2", "multi", "patch"], required=True)
    ap.add_argument("--adapter", type=Path, default=ADAPTERS / "fintan_2026_11_23_wsp_v2_r64.gguf")
    ap.add_argument("--n2-adapter", type=Path, default=ADAPTERS / "fintan_night2_wsp_r32.gguf")
    ap.add_argument("--merged-adapter", type=Path, default=ADAPTERS / "fintan_wsp_v2_merged_n1n2.gguf")
    ap.add_argument("--n2-eval", type=Path, default=ROOT / "night2_eval_questions.json")
    ap.add_argument("--patch-key", type=str, default="r512_patched")
    ap.add_argument("--result-key", type=str, default="option1_v2_r64")
    args = ap.parse_args()

    if args.mode == "v2":
        run_v2_benchmark(args.adapter, result_key=args.result_key)
    elif args.mode == "multi":
        run_multi_benchmark(args.n2_adapter, args.merged_adapter, args.n2_eval)
    elif args.mode == "patch":
        run_patch_benchmark(args.patch_key, args.adapter)


if __name__ == "__main__":
    main()