ecbs5200-jev-benchmark / code /glm_benchmark.py
earino's picture
Final review fixes: shortlist manifest ordering, runner metadata
2fe8de3 verified
Raw History Blame Contribute Delete
21.5 kB
"""
General-purpose LLM zero-shot baseline (GLM-5.3 via LunaRoute) on the ECBS5200 canonical val split
===============================================================================================
Fills the Jev paper's stated gap ("no general-purpose LLM was run on this split"): a hosted chat model,
prompted once per complaint (thinking on, default settings, 16,384-token output budget) with the same question Jev got and the same 113 bare label names, asked to
answer with exactly one label. Generative, so it returns a label but no distribution (accuracy, macro F1,
group F1 and zero-F1 are reported; ECE is not applicable). Same 6,430 rows, same metrics and paired
bootstrap as jev_benchmark.py / semif_benchmark.py.
Endpoint: LunaRoute (gw.lunaroute.com), OpenAI-compatible chat completions, flat rate. The account has
6 realtime lanes; concurrency stays at 5 by default. Key: LUNAROUTE_API_KEY (from
~/research/harness_benchmark/.env; never printed).
set -a; . ~/research/harness_benchmark/.env; set +a
python3 verification/glm_benchmark.py --dry-run
python3 verification/glm_benchmark.py --dev --n 20 # train dev slice, prompt sanity
python3 verification/glm_benchmark.py --n 200 # stratified val pilot
python3 verification/glm_benchmark.py # full val
python3 verification/glm_benchmark.py --eval-only
Every answer is appended to a JSONL cache keyed by row index; reruns only request what is missing.
"""
import argparse
import asyncio
import datetime
import json
import os
import re
import subprocess
import sys
import time
from functools import partial
from pathlib import Path
print = partial(print, flush=True)
import numpy as np
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "verification"))
from utils.data_utils import load_course_data, LABEL_LIST, NUM_LABELS
from jev_benchmark import (SEED, N_BOOT, load_comparators, pick_subset, macro_f1, tier_f1, zero_f1_count,
paired_bootstrap)
from semif_benchmark import CHOICE_QUESTION, CRITERIA_DIR, load_jev_rows
# =========================================================================
# CONFIG
# =========================================================================
BASE_URL = "https://gw.lunaroute.com/v1"
MODEL = "glm-5.3"
TAG = "glm-5.3"
API_KEY_ENV = "LUNAROUTE_API_KEY"
CONCURRENCY = 5 # 6 realtime lanes on the account; leave one free
MAX_TOKENS = 16384 # GLM-5.3 reasons before answering; thinking left on (default)
OUT_DIR = ROOT / "verification" / "glm_benchmark_artifacts"
SYSTEM = ("You classify consumer financial complaints into the issue category the consumer selected on the "
"CFPB complaint form. Answer with exactly one category from the list, copied verbatim, and nothing else.")
USER_TEMPLATE = ("Complaint:\n{complaint}\n\n"
"Question: " + CHOICE_QUESTION + "\n\n"
"Categories (choose exactly one and copy it verbatim):\n{labels}\n\nAnswer:")
LABEL_BLOCK = "\n".join(f"- {lab}" for lab in LABEL_LIST)
_NORM = {re.sub(r"[^a-z0-9]", "", lab.lower()): i for i, lab in enumerate(LABEL_LIST)}
def build_messages(text, examples=None):
"""examples: list of (complaint, label) pairs shown before the question (retrieval few-shot). With
SHORTLIST_ONLY, only the distinct labels of those examples are shown (alphabetical, no texts, no counts)."""
user = USER_TEMPLATE.format(complaint=text, labels=LABEL_BLOCK)
if examples and SHORTLIST_ONLY:
cands = sorted({LABEL_LIST[l] for _, l in examples})
user = (SHORTLIST_INTRO + "\n" + "\n".join(f"- {c}" for c in cands) + "\n\n---\n\nNow classify this complaint.\n\n" + user)
elif examples:
shots = "\n\n".join(f"Complaint:\n{t}\nCategory: {LABEL_LIST[l]}" for t, l in examples)
user = (FEWSHOT_INTRO + "\n\n" + shots + "\n\n---\n\nNow classify this complaint.\n\n" + user)
return [{"role": "system", "content": SYSTEM}, {"role": "user", "content": user}]
# Retrieval few-shot (--fewshot K): the K most similar fit-set complaints by cosine similarity of the same
# all-mpnet-base-v2 sentence embeddings used in the features control, shown with their labels. K fixed a priori.
FEWSHOT = 0
SHORTLIST_ONLY = False # --shortlist-only: candidate labels from the retrieved complaints, without their texts
SHORTLIST_INTRO = ("Complaints similar to the one you must classify were filed under the following categories "
"(alphabetical order). The answer may be one of them, but choose from the full list below.")
FEWSHOT_INTRO = ("Here are labeled complaints similar to the one you must classify, each with the category the "
"consumer selected. Use them as examples of how the categories are used.")
_EXAMPLES = {}
def set_fewshot(k, split, texts):
"""Precompute each target row's K retrieved (complaint, label) examples from the fit set."""
global FEWSHOT, _EXAMPLES
FEWSHOT = k
art = ROOT / "verification" / "jev_benchmark_artifacts"
E_fit = np.load(art / "embeddings_mpnet_fit.npz")["emb"]
tr_ds, _, te_ds = load_course_data()
fit_texts = list(tr_ds["text"]) + list(te_ds["text"])
y_fit = np.concatenate([tr_ds["label"], te_ds["label"]])
if split == "val":
E_q = np.load(art / "embeddings_mpnet_val.npz")["emb"]; offset = None
else: # train dev slice: query rows are fit-set rows 0..57,845; never retrieve the row itself
E_q = E_fit[: len(tr_ds)]; offset = 0
return E_fit, E_q, fit_texts, y_fit, offset
def examples_for(rows, E_fit, E_q, fit_texts, y_fit, offset):
for i in rows:
sims = E_fit @ E_q[i]
if offset is not None:
sims[i] = -np.inf
top = np.argpartition(-sims, FEWSHOT)[:FEWSHOT]
top = top[np.argsort(-sims[top])][::-1] # most similar example placed last, next to the query
_EXAMPLES[int(i)] = [(fit_texts[j], int(y_fit[j])) for j in top]
def parse_label(answer):
"""Exact match after light normalisation; else the unique label contained in the answer; else None."""
if answer is None:
return None
a = answer.strip().strip('"\'`').splitlines()[0] if answer.strip() else ""
a = re.sub(r"^[-*\d.\s)]+", "", a).strip()
key = re.sub(r"[^a-z0-9]", "", a.lower())
if key in _NORM:
return _NORM[key]
full = re.sub(r"[^a-z0-9]", "", answer.lower())
hits = [i for k, i in _NORM.items() if k and k in full]
if len(hits) == 1:
return hits[0]
if hits: # several labels mentioned: take the longest match (most specific)
return max(hits, key=lambda i: len(LABEL_LIST[i]))
return None
def cache_path(split):
return OUT_DIR / f"{tag()}_{split}_responses.jsonl"
def tag():
if not FEWSHOT:
return TAG
return f"{TAG}_shortlist{FEWSHOT}" if SHORTLIST_ONLY else f"{TAG}_fewshot{FEWSHOT}"
def load_cache(path):
cache = {}
if path.exists():
for line in path.read_text().splitlines():
rec = json.loads(line)
cache[rec["row_idx"]] = rec
return cache
# =========================================================================
# API calls
# =========================================================================
async def run_llm(texts, todo, path, concurrency, progress_every=100, max_tokens=MAX_TOKENS):
from openai import AsyncOpenAI, RateLimitError, APIStatusError, APIConnectionError, APITimeoutError
key = os.environ.get(API_KEY_ENV)
if not key:
sys.exit(f"ERROR: {API_KEY_ENV} not set (set -a; . ~/research/harness_benchmark/.env; set +a)")
client = AsyncOpenAI(base_url=BASE_URL, api_key=key, timeout=120.0, max_retries=0)
sem = asyncio.Semaphore(concurrency)
OUT_DIR.mkdir(exist_ok=True)
done, failures, t_start = 0, [], time.time()
f = open(path, "a")
async def one(i):
nonlocal done
async with sem:
delay = 2.0
for attempt in range(8):
t0 = time.perf_counter()
try:
r = await client.chat.completions.create(
model=MODEL, messages=build_messages(texts[i], _EXAMPLES.get(int(i))), temperature=0.0,
max_tokens=max_tokens)
break
except RateLimitError:
await asyncio.sleep(delay); delay = min(delay * 2, 30)
except (APIConnectionError, APITimeoutError):
await asyncio.sleep(delay); delay = min(delay * 2, 30)
except APIStatusError as e:
if e.status_code in (500, 502, 503, 504, 529):
await asyncio.sleep(delay); delay = min(delay * 2, 30)
else:
failures.append((int(i), f"{e.status_code}: {str(e)[:160]}")); return
else:
failures.append((int(i), "gave up after 8 attempts")); return
latency = time.perf_counter() - t0
msg = r.choices[0].message
answer = msg.content or ""
extra = getattr(msg, "model_extra", None) or {}
reasoning = getattr(msg, "reasoning_content", None) or extra.get("reasoning_content") or extra.get("reasoning") or ""
rec = {"row_idx": int(i), "answer": answer, "label_idx": parse_label(answer),
"finish_reason": r.choices[0].finish_reason, "latency_s": latency, "reasoning_chars": len(reasoning),
"input_tokens": getattr(r.usage, "prompt_tokens", None), "output_tokens": getattr(r.usage, "completion_tokens", None),
"model": r.model, "request_id": getattr(r, "id", None), "max_tokens": max_tokens}
f.write(json.dumps(rec) + "\n"); f.flush()
done += 1
if done == 1 or done % progress_every == 0 or done == len(todo):
el = time.time() - t_start
print(f" {done}/{len(todo)} | {el:.0f}s | {done / el:.2f} req/s | failures {len(failures)} | "
f"last: {latency * 1e3:.0f} ms, {rec['input_tokens']} in / {rec['output_tokens']} out, parsed={rec['label_idx'] is not None}")
await asyncio.gather(*(one(i) for i in todo))
f.close()
if failures:
print(f"\n {len(failures)} requests failed (not cached; rerun to retry). First 5:")
for i, msg in failures[:5]:
print(f" row {i}: {msg}")
# =========================================================================
# Evaluation
# =========================================================================
def evaluate(sub, y_all, tiers_all, comparators, cache, label, n_requested):
have = np.array([i for i in sub if i in cache])
if len(have) < len(sub):
print(f"\n NOTE: {len(sub) - len(have)} of {len(sub)} rows not answered yet; scoring {len(have)}.")
if len(have) == 0:
return None
y = y_all[have]
raw = [cache[i]["label_idx"] for i in have]
unparsed = np.array([r is None for r in raw])
# An unparseable answer is scored as a wrong prediction of a sentinel class (counts as FP for no real class)
preds = np.array([r if r is not None else -1 for r in raw])
preds_scored = np.where(preds < 0, (y + 1) % NUM_LABELS, preds) # guaranteed wrong, keeps arrays in range
rows = [(label, preds_scored)]
if comparators is not None:
rows += [(n, p) for n, p, _ in load_jev_rows(have)]
semif = ROOT / "verification" / "semif_benchmark_artifacts" / "semif-qwen3.5-4b_bracket_val_probs.npz"
if semif.exists():
rows.append(("SemIf Qwen3.5-4B bracket", np.load(semif)["preds"][have]))
rows += [(c["name"], c["preds"][have]) for c in comparators]
print("\n" + "=" * 100)
print(f" RESULTS — {len(have)} examples" + ("" if n_requested is None else f" (requested n={n_requested})"))
print("=" * 100)
results = {"n": int(len(have)), "unparsed_answers": int(unparsed.sum()), "models": {}}
if tiers_all is not None:
tiers = tiers_all[have]
tier_labels = {t: sorted(set(y_all[tiers_all == t].tolist())) for t in ("head", "mid", "tail")}
print(f" {'Model':<44} {'Acc':>6} {'MacroF1':>8} {'Head':>6} {'Mid':>6} {'Tail':>6} {'Zero-F1':>9}")
else:
print(f" {'Model':<44} {'Acc':>6} {'MacroF1':>8} {'Zero-F1':>9}")
for name, p in rows:
z, k = zero_f1_count(y, p)
r = {"accuracy": float((p == y).mean()), "macro_f1": float(macro_f1(y, p)), "zero_f1": z, "classes_present": k}
if tiers_all is not None:
for t in ("head", "mid", "tail"):
r[f"{t}_f1"] = float(tier_f1(y, p, tiers, t, tier_labels))
print(f" {name:<44} {r['accuracy']:>6.3f} {r['macro_f1']:>8.3f} {r['head_f1']:>6.3f} {r['mid_f1']:>6.3f} {r['tail_f1']:>6.3f} {z:>4}/{k:<4}")
else:
print(f" {name:<44} {r['accuracy']:>6.3f} {r['macro_f1']:>8.3f} {z:>4}/{k:<4}")
results["models"][name] = r
print(f" ({label}: {unparsed.sum()} of {len(have)} answers did not match any label and are scored as wrong; "
f"distinct labels predicted {len(set(preds[preds >= 0].tolist()))})")
if len(rows) > 1:
print(f"\n Paired bootstrap, Δ macro F1 = {MODEL} − model ({N_BOOT} resamples, seed {SEED}):")
results["paired"] = {}
for name, p in rows[1:]:
d, (lo, hi) = paired_bootstrap(y, preds_scored, p)
sig = "significant" if (lo > 0 or hi < 0) else "CI includes 0"
results["paired"][name] = {"delta": float(d), "ci95": [float(lo), float(hi)]}
print(f" vs {name:<44} Δ={d:+.3f} 95% CI [{lo:+.3f}, {hi:+.3f}] {sig}")
lat = np.array([cache[i]["latency_s"] for i in have]) * 1e3
tin = [cache[i]["input_tokens"] for i in have if cache[i]["input_tokens"]]
tout = [cache[i]["output_tokens"] for i in have if cache[i]["output_tokens"]]
results["ops"] = {"latency_ms_p50": float(np.percentile(lat, 50)), "latency_ms_p95": float(np.percentile(lat, 95)),
"input_tokens_mean": float(np.mean(tin)) if tin else None, "output_tokens_mean": float(np.mean(tout)) if tout else None,
"input_tokens_total": int(sum(tin)), "output_tokens_total": int(sum(tout)),
"finish_reasons": {k: int(v) for k, v in zip(*np.unique([cache[i]["finish_reason"] for i in have], return_counts=True))},
"models_reported": sorted({cache[i]["model"] for i in have})}
o = results["ops"]
print(f"\n {MODEL} ops: latency p50 {o['latency_ms_p50']:.0f} ms, p95 {o['latency_ms_p95']:.0f} ms; tokens "
f"{o['input_tokens_mean'] or 0:.0f} in / {o['output_tokens_mean'] or 0:.1f} out per request; finish {o['finish_reasons']}; "
f"models {o['models_reported']}")
return results, preds
def export_full(y_all, tiers_all, cache, results, preds):
n = len(y_all)
scored = np.where(preds < 0, (y_all + 1) % NUM_LABELS, preds)
probs = np.zeros((n, NUM_LABELS)); probs[np.arange(n), scored] = 1.0 # one-hot: no distribution from a generative answer
np.savez_compressed(OUT_DIR / f"{tag()}_val_probs.npz", probs=probs, preds=scored, raw_preds=preds, labels=y_all, tiers=tiers_all)
try:
commit = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, cwd=ROOT).stdout.strip()
except OSError:
commit = None
manifest = {"exported_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
"system": f"{MODEL} via LunaRoute (gw.lunaroute.com), OpenAI-compatible chat completions, temperature 0",
"build_repo_commit": commit, "eval_set": "canonical val (utils/data_utils.py), 6,430 examples, 113 classes",
"prompt": {"system": SYSTEM, "user_template": USER_TEMPLATE, "labels": "113 bare label names, bulleted, label-list order"},
"max_tokens": f"{MAX_TOKENS}; answers cut off at that budget were re-requested once at 65,536",
"parsing": "exact label after normalisation; else the unique/longest label contained in the answer; else scored as wrong",
"probabilities": "none (generative answer); npz probs are one-hot on the prediction, ECE not applicable",
"concurrency": CONCURRENCY,
"retrieval": None if not FEWSHOT else {
"k": FEWSHOT, "embedding": "sentence-transformers/all-mpnet-base-v2, cosine similarity",
"pool": "fit set (train + original test, 79,278 complaints)",
"order": ("distinct labels in alphabetical order; no examples shown" if SHORTLIST_ONLY
else "most similar example last, next to the query"),
"content": "distinct labels only, alphabetical" if SHORTLIST_ONLY else "complaint text and label",
"prefix": SHORTLIST_INTRO if SHORTLIST_ONLY else FEWSHOT_INTRO}, "files": {"responses_jsonl": cache_path("val").name, "probs_npz": f"{tag()}_val_probs.npz"},
"results": results}
(OUT_DIR / f"{tag()}_manifest_full.json").write_text(json.dumps(manifest, indent=2))
print(f" Exported {tag()}_val_probs.npz and manifest")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--n", type=int, default=None)
ap.add_argument("--dev", action="store_true")
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--eval-only", action="store_true")
ap.add_argument("--concurrency", type=int, default=CONCURRENCY)
ap.add_argument("--retry-truncated", type=int, default=None, metavar="MAX_TOKENS",
help="re-request rows whose answer was cut off (finish=length) with this larger budget")
ap.add_argument("--shortlist-only", action="store_true",
help="with --fewshot K: show only the distinct labels of the K retrieved complaints (no texts)")
ap.add_argument("--fewshot", type=int, default=0, metavar="K",
help="retrieval few-shot: show the K most similar labeled fit-set complaints in the prompt")
args = ap.parse_args()
print("Loading canonical splits...")
train_ds, val_ds, _ = load_course_data()
if args.dev:
dev_idx = json.loads((CRITERIA_DIR / "train_dev_idx.json").read_text())
texts, y_all = list(train_ds["text"]), np.array(train_ds["label"])
sub = np.array(dev_idx[: args.n] if args.n else dev_idx)
comparators, tiers_all, split = None, None, "traindev"
else:
texts, y_all = list(val_ds["text"]), np.array(val_ds["label"])
assert len(y_all) == 6430 and NUM_LABELS == 113
print("Loading comparator val predictions from HF Hub...")
comparators, tiers_all = load_comparators(y_all)
sub, split = pick_subset(y_all, args.n), "val"
if args.fewshot:
global SHORTLIST_ONLY
SHORTLIST_ONLY = args.shortlist_only
ctx = set_fewshot(args.fewshot, split, texts)
examples_for([int(i) for i in sub], *ctx)
print(f"Retrieval few-shot: {args.fewshot} examples per complaint")
path = cache_path(split)
cache = load_cache(path)
if args.retry_truncated:
trunc = [i for i, r in cache.items() if r["finish_reason"] == "length"]
print(f"Retrying {len(trunc)} truncated answers with max_tokens={args.retry_truncated}")
lines = [l for l in path.read_text().splitlines() if json.loads(l)["finish_reason"] != "length"]
(path.parent / (path.stem + "_truncated_first_attempt.jsonl")).write_text(
"".join(json.dumps(cache[i]) + "\n" for i in trunc))
path.write_text("".join(l + "\n" for l in lines))
asyncio.run(run_llm(texts, trunc, path, args.concurrency, progress_every=5, max_tokens=args.retry_truncated))
cache = load_cache(path)
todo = [int(i) for i in sub if int(i) not in cache]
print(f"\n{split} subset: {len(sub)} | cached: {len(sub) - len(todo)} | to request: {len(todo)}")
if args.dry_run:
m = build_messages(texts[int(sub[0])])
chars = sum(len(x["content"]) for x in m)
print(f" DRY RUN — prompt ~{chars} chars (~{chars / 4:.0f} tokens); {len(todo)} requests ≈ {len(todo) * chars / 4 / 1e6:.1f}M input tokens")
print(" --- system ---\n" + m[0]["content"] + "\n --- user (head) ---\n" + m[1]["content"][:700] + " ...")
return
if todo and not args.eval_only:
print(f"Calling {MODEL} via LunaRoute (concurrency={args.concurrency})...")
asyncio.run(run_llm(texts, todo, path, args.concurrency))
cache = load_cache(path)
label = (f"{MODEL} zero-shot (generative, label names only)" if not args.fewshot else
f"{MODEL}, labels of {args.fewshot} retrieved complaints only" if args.shortlist_only else
f"{MODEL}, {args.fewshot} retrieved examples")
out = evaluate(sub, y_all, tiers_all, comparators, cache, label, args.n)
if out:
results, preds = out
rtag = "full" if (args.n is None and not args.dev) else f"{split}{args.n or len(sub)}"
OUT_DIR.mkdir(exist_ok=True)
(OUT_DIR / f"{tag()}_results_{rtag}.json").write_text(json.dumps(results, indent=2))
print(f"\n Saved {tag()}_results_{rtag}.json")
if not args.dev and args.n is None and results["n"] == len(y_all):
export_full(y_all, tiers_all, cache, results, preds)
if __name__ == "__main__":
main()