Cotton code
165 lines · 6.7 KB · PythonRaw
#!/usr/bin/env python3"""Measure local summarisers on the synthetic meetings.    python3 -I scripts/meetings/synthetic/bench.py --server <llama-server> --models <dir> \        --model <file.gguf>... --meeting <meeting.json>... --out <folder> [--summariser <bin>]For each model: start llama-server on it (Metal, flash attention), then foreach meeting run `meetings-summarise --file` (the shipping code: parts, merge,the core's checks) against that server, timing it and sampling the server'smemory every half second: phys_footprint (what Activity Monitor's Memorycolumn shows, without the weights llama.cpp maps from the file) and residentsize (with them: what the Mac must hold in RAM).Writes <out>/<model>/<meeting>.json (what it made) and <out>/results.json, andprints a table: seconds, peak memory, and against the meeting's truth how manyactions were found, with the right owner, with the right day, how many weremade up (no truth behind them) and whether a decoy got in."""import argparseimport jsonimport osimport reimport socketimport subprocessimport sysimport threadingimport timeimport urllib.requestfrom pathlib import Pathdef free_port() -> int:    s = socket.socket()    s.bind(("127.0.0.1", 0))    port = s.getsockname()[1]    s.close()    return portdef footprint_mb(pid: int) -> float:    try:        out = subprocess.run(["footprint", "-p", str(pid)], capture_output=True, text=True, timeout=10).stdout    except Exception:        return 0.0    m = re.search(r"phys_footprint:\s*([\d.]+)\s*([KMG])B", out)    if not m:        m = re.search(r"Footprint:\s*([\d.]+)\s*([KMG])B", out)    if not m:        return 0.0    n, unit = float(m.group(1)), m.group(2)    return n / 1024 if unit == "K" else n * 1024 if unit == "G" else ndef rss_mb(pid: int) -> float:    try:        return int(subprocess.run(["ps", "-o", "rss=", "-p", str(pid)], capture_output=True, text=True, timeout=5).stdout.strip() or 0) / 1024    except Exception:        return 0.0def words(s: str) -> set:    stop = {"the", "a", "an", "to", "for", "of", "and", "on", "in", "with", "by", "about"}    return {w for w in re.findall(r"[a-z0-9]+", s.lower()) if w not in stop}def score(made: dict, meeting: dict) -> dict:    actions = made.get("actions", [])    truth = meeting["truth"]    used, found, owner, due = set(), 0, 0, 0    for t in truth:        tw = words(t["words"])        best, at = 0.0, None        for i, a in enumerate(actions):            if i in used:                continue            aw = words(a.get("words", ""))            overlap = len(tw & aw) / max(1, len(tw))            if overlap > best:                best, at = overlap, i        if at is not None and best >= 0.5:            used.add(at)            found += 1            a = actions[at]            if (a.get("who") or None) == t["who"]:                owner += 1            if (a.get("due") or None) == t["due"]:                due += 1    made_up = len(actions) - len(used)    decoys = sum(1 for n in meeting["not"] for a in actions if words(n.split("(")[0]) & words(a.get("words", "")) >= words(n.split("(")[0]))    return {"truth": len(truth), "found": found, "owner": owner, "due": due, "extra": made_up, "decoys": decoys}def main():    ap = argparse.ArgumentParser()    ap.add_argument("--server", default="llama-server")    ap.add_argument("--model", action="append", required=True)    ap.add_argument("--meeting", action="append", required=True)    ap.add_argument("--out", required=True)    ap.add_argument("--summariser", required=True)    ap.add_argument("--ctx", type=int, default=16384)    a = ap.parse_args()    out = Path(a.out)    out.mkdir(parents=True, exist_ok=True)    results = []    for model in a.model:        name = Path(model).stem        port = free_port()        log = open(out / f"{name}.server.log", "w")        started = time.time()        server = subprocess.Popen([a.server, "-m", model, "--port", str(port), "-c", str(a.ctx), "-ngl", "99", "-fa", "on", "--no-webui"], stdout=log, stderr=subprocess.STDOUT)        try:            while True:                try:                    with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2) as r:                        if r.status == 200:                            break                except Exception:                    pass                if server.poll() is not None:                    sys.exit(f"{name}: the server stopped, see {log.name}")                time.sleep(0.5)            load_s = time.time() - started            for path in a.meeting:                meeting = json.loads(Path(path).read_text())                mname = Path(path).stem                peak = [footprint_mb(server.pid)]                rss = [rss_mb(server.pid)]                done = threading.Event()                def sample():                    while not done.is_set():                        peak.append(footprint_mb(server.pid))                        rss.append(rss_mb(server.pid))                        time.sleep(0.5)                t = threading.Thread(target=sample, daemon=True)                t.start()                t0 = time.time()                run = subprocess.run([a.summariser, "--file", path, "--server", f"http://127.0.0.1:{port}", "--model-name", name], capture_output=True, text=True)                secs = time.time() - t0                done.set()                t.join()                if run.returncode != 0:                    print(f"{name} {mname}: failed: {run.stderr.strip()[-400:]}", file=sys.stderr)                    results.append({"model": name, "meeting": mname, "failed": run.stderr.strip()[-400:]})                    continue                made = json.loads(run.stdout)                (out / name).mkdir(exist_ok=True)                (out / name / f"{mname}.json").write_text(json.dumps(made, ensure_ascii=False, indent=1))                row = {"model": name, "meeting": mname, "seconds": round(secs, 1), "load_s": round(load_s, 1), "peak_mb": round(max(peak)), "rss_mb": round(max(rss)), **score(made, meeting), "took": made.get("took")}                results.append(row)                print(json.dumps(row), flush=True)        finally:            server.terminate()            server.wait()    (out / "results.json").write_text(json.dumps(results, indent=1))    print(f"\n{'model':28} {'meeting':8} {'s':>6} {'RSS MB':>7} {'fp MB':>6} found owner due extra decoy")    for r in results:        if "failed" in r:            print(f"{r['model']:28} {r['meeting']:8} failed")            continue        print(f"{r['model']:28} {r['meeting']:8} {r['seconds']:6.1f} {r['rss_mb']:7} {r['peak_mb']:6} {r['found']}/{r['truth']:<3} {r['owner']:5} {r['due']:3} {r['extra']:5} {r['decoys']}")if __name__ == "__main__":    main()