jstarks's picture
Upload WebBrain-LingLoop-8B-A1.3B Dual-Subspace Woodbury WSP (lossless baked Q6_K + r32 adapter + CUDA runtime + 160-task verification)
e8a992b verified
Raw History Blame Contribute Delete
9.24 kB
"""Pareto Scale Sweep for WebBrain-LingLoop-8B-A1.3B Dual-Subspace Woodbury WSP.
1. Measures exact WikiText-2 2K PPL & drift for scales s in {0.0, 0.35, 0.50, 0.75, 1.00} directly.
2. Connects to live `lingloop_cuda.server_openai` on port 8145 and swaps scales via `/admin/set_adapter`
to screen all 30 WSP S1..S9 (NT), all 19 failing/critical TH WSP suites (S2,S3,S5,S6,S8),
all 15 EST_BFCL_IRR, 8 critical EST_GSM8K (incl. 5 baseline cutoffs), 5 EST_HUMANEVAL, 10 EST_NL2BASH,
plus TH HumanEval cutoff check (4 tasks).
3. Saves full Pareto metrics & recommended optimal scale -> results/lingloop_pareto_sweep.json.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import sys
import time
import urllib.request
from pathlib import Path
from typing import Any, Dict, List, Tuple
os.environ["HF_HUB_DISABLE_XET"] = "1"
ROOT = Path(__file__).resolve().parent
PIPELINE_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\wsp-5model-pipeline")
ESTABLISHED_CACHE = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\gemma4-e2b-agent\established_datasets_cache.json")
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(PIPELINE_DIR))
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer
import stage_and_audit_lingloop as sal # noqa: E402
from lingloop_cuda.modeling_lingloop_cuda import LingLoopCudaModel # noqa: E402
def eval_wikitext_ppl_sweep(adapter_path: Path, scales: List[float]) -> Dict[str, float]:
gguf_path = str(ROOT / "upstream" / "WebBrain-LingLoop-8B-A1.3B-Q6_K.gguf")
meta_dir = str(ROOT / "upstream" / "hf_meta")
cfg_path = str(ROOT / "upstream" / "hf_meta" / "config.json")
tok = AutoTokenizer.from_pretrained(meta_dir, trust_remote_code=True)
model = LingLoopCudaModel.from_gguf(gguf_path, cfg_path, device=torch.device("cuda:0"))
wt_ids = tok.encode((ROOT / "upstream" / "wikitext2_test.txt").read_text(encoding="utf-8"), add_special_tokens=False)[:2049]
ppls: Dict[str, float] = {}
for sc in scales:
if sc == 0.0:
model.clear_wsp_adapter()
else:
model.apply_wsp_adapter(str(adapter_path), scale=sc)
tot_nll, tot_tok = 0.0, 0
with torch.no_grad():
for s in range(0, len(wt_ids) - 1, 256):
seg = wt_ids[s : min(len(wt_ids), s + 257)]
if len(seg) < 2:
continue
inp = torch.tensor([seg[:-1]], device=model.device, dtype=torch.long)
tgt = torch.tensor(seg[1:], device=model.device, dtype=torch.long)
logits = model.forward_logits(inp, cache=None, num_passes=2, last_token_only=False)[0]
tot_nll += float(F.cross_entropy(logits.float(), tgt, reduction="sum").item())
tot_tok += int(tgt.numel())
ppl = math.exp(tot_nll / max(1, tot_tok))
ppls[f"{sc:.2f}"] = round(ppl, 4)
print(f" [ppl_sweep] scale={sc:.2f} -> wikitext2_2k PPL={ppl:.4f}", flush=True)
del model
torch.cuda.empty_cache()
return ppls
def build_pareto_screen_plan(est_cache: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
full = sal.build_agent100_plan(est_cache)
# All 30 WSP S1..S9 + 15 BFCL_IRR + 10 NL2BASH + 8 GSM8K (incl baseline failures) + 5 HumanEval
nt_screen: List[Dict[str, Any]] = []
gsm_keep = {"gsm8k_0", "gsm8k_1", "gsm8k_3", "gsm8k_5", "gsm8k_7", "gsm8k_12", "gsm8k_15", "gsm8k_18"}
he_keep = {"HumanEval/0", "HumanEval/1", "HumanEval/2", "HumanEval/6", "HumanEval/10"}
nl_cnt = 0
for sp in full:
su = sp["suite"]
if su.startswith("S"):
nt_screen.append(sp)
elif su == "EST_BFCL_IRR":
nt_screen.append(sp)
elif su == "EST_NL2BASH" and nl_cnt < 10:
nt_screen.append(sp)
nl_cnt += 1
elif su == "EST_GSM8K" and sp["id"] in gsm_keep:
nt_screen.append(sp)
elif su == "EST_HUMANEVAL" and sp["id"] in he_keep:
nt_screen.append(sp)
# TH screen: all critical WSP TH suites (S2, S3, S5, S6, S8 = 19) + TH failing HumanEval (4) + TH gsm8k_7 & gsm8k_0 (2)
th_suites = {"S2_RESTRAINT", "S3_ROUTER", "S5_TURN2_JSON", "S6_HANDOFF", "S8_GROUNDING"}
th_screen: List[Dict[str, Any]] = []
for sp in full:
if sp["suite"] in th_suites:
th_screen.append(sp)
elif sp["suite"] == "EST_HUMANEVAL" and sp["id"] in {"HumanEval/0", "HumanEval/1", "HumanEval/6", "HumanEval/10"}:
th_screen.append(sp)
elif sp["suite"] == "EST_GSM8K" and sp["id"] in {"gsm8k_0", "gsm8k_7"}:
th_screen.append(sp)
return nt_screen, th_screen
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--adapter", type=Path, default=ROOT / "wsp_adapters" / "lingloop_wsp_r32.safetensors")
ap.add_argument("--base-url", default="http://127.0.0.1:8145")
ap.add_argument("--scales", default="0.35,0.50,0.75,1.00")
ap.add_argument("--ppl-only", action="store_true")
ap.add_argument("--sweep-only", action="store_true")
ap.add_argument("--ppl-json", type=Path, default=ROOT / "results" / "lingloop_ppl_sweep.json")
ap.add_argument("--out", type=Path, default=ROOT / "results" / "lingloop_pareto_sweep.json")
args = ap.parse_args()
scales = [float(x.strip()) for x in args.scales.split(",") if x.strip()]
ppls: Dict[str, float] = {}
if not args.sweep_only:
print("=== Phase 1: WikiText-2 2K PPL Drift Check ===", flush=True)
ppls = eval_wikitext_ppl_sweep(args.adapter, [0.0] + scales)
if args.ppl_only:
args.out.write_text(json.dumps({"ppls": ppls}, indent=2), encoding="utf-8")
return
elif args.ppl_json.exists():
ppls = json.loads(args.ppl_json.read_text(encoding="utf-8")).get("ppls", {})
health = None
for _ in range(30):
try:
health = sal.get_json(f"{args.base_url}/health")
break
except Exception:
time.sleep(2.0)
assert health is not None, "Server not reachable"
model_id = health["model"]
est_cache = json.loads(ESTABLISHED_CACHE.read_text(encoding="utf-8"))
nt_screen, th_screen = build_pareto_screen_plan(est_cache)
print(f"=== Phase 2: Pareto Task Sweep (NT screen={len(nt_screen)}, TH screen={len(th_screen)}) ===", flush=True)
candidates: List[Dict[str, Any]] = []
base_ppl = ppls.get("0.00", 18.479)
for sc in scales:
cfg = sal.post_json(
f"{args.base_url}/admin/set_adapter",
{"adapter": str(args.adapter), "scale": sc, "tool_gated": False},
)
print(f"\n--- Sweeping scale={sc:.2f} -> {cfg} ---", flush=True)
nt_res = sal.run_task_batch(args.base_url, model_id, nt_screen, f"NT_s{sc:.2f}", enable_thinking=False, max_tokens=1024, log_every=15)
th_res = sal.run_task_batch(args.base_url, model_id, th_screen, f"TH_s{sc:.2f}", enable_thinking=True, max_tokens=1536, log_every=10)
ppl_val = ppls.get(f"{sc:.2f}")
ppl_drift = round(ppl_val - base_ppl, 4) if ppl_val is not None else None
tot_pass = nt_res["overall_pass"] + th_res["overall_pass"]
tot_n = nt_res["overall_total"] + th_res["overall_total"]
candidates.append({
"scale": sc,
"wikitext2_2k_ppl": ppl_val,
"ppl_drift": ppl_drift,
"screen_total_pass": tot_pass,
"screen_total_n": tot_n,
"screen_total_rate": round(100.0 * tot_pass / tot_n, 1),
"nt_wsp_pass": nt_res["wsp_pass"],
"nt_wsp_total": nt_res["wsp_total"],
"nt_est_pass": nt_res["established_pass"],
"nt_est_total": nt_res["established_total"],
"th_wsp_pass": th_res["wsp_pass"],
"th_wsp_total": th_res["wsp_total"],
"th_est_pass": th_res["established_pass"],
"th_est_total": th_res["established_total"],
"nt_cutoffs": nt_res["cutoffs"],
"th_cutoffs": th_res["cutoffs"],
"nt_suites": nt_res["suites"],
"th_suites": th_res["suites"],
})
# Choose optimal Pareto scale: filter PPL drift <= 0.30 (prefer <= 0.20), maximize screen_total_pass
valid = [c for c in candidates if (c["ppl_drift"] is None or c["ppl_drift"] <= 0.25)]
if not valid:
valid = candidates
best = max(valid, key=lambda c: (c["screen_total_pass"], -(c["ppl_drift"] or 0.0), -abs(c["scale"] - 0.75)))
out = {
"adapter": str(args.adapter),
"ppls": ppls,
"candidates": candidates,
"best_scale": best["scale"],
"best_summary": {k: best[k] for k in ("scale", "wikitext2_2k_ppl", "ppl_drift", "screen_total_pass", "screen_total_n", "screen_total_rate", "nt_wsp_pass", "th_wsp_pass", "nt_est_pass", "th_est_pass")},
}
args.out.parent.mkdir(parents=True, exist_ok=True)
args.out.write_text(json.dumps(out, indent=2), encoding="utf-8")
print(f"\n=== Best Pareto scale: {best['scale']} -> {out['best_summary']} ===", flush=True)
if __name__ == "__main__":
main()