File size: 21,487 Bytes
0164c03 8c15ebd 0164c03 8c15ebd 0164c03 8c15ebd 0164c03 8c15ebd 0164c03 8fa472f 2fe8de3 8fa472f 0164c03 8c15ebd 0164c03 8c15ebd 0164c03 8c15ebd 0164c03 | 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 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | """
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()
|