Download src/evaluate.py from sanidhya1910/northwind-support-lora: direct link, hf CLI and curl.
- Browser
- Download file 13.3 kB
-
https://huggingface.co/spaces/sanidhya1910/northwind-support-lora/resolve/main/src/evaluate.py
- Command line
-
hf download hf://spaces/sanidhya1910/northwind-support-lora/src/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/spaces/sanidhya1910/northwind-support-lora/resolve/main/src/evaluate.py
13.3 kB
| """Score the prompted baseline against the LoRA fine-tune on the held-out set. | |
| python src/evaluate.py --arms prompted prompted_fewshot short_prompt lora | |
| Arms | |
| ---- | |
| prompted base model + the full ~1,000-token policy/system prompt | |
| prompted_fewshot the same, plus two worked examples | |
| short_prompt base model + a one-line system prompt (the ablation that | |
| shows how much the long prompt is doing) | |
| lora fine-tuned adapter + the same one-line system prompt | |
| Every metric is computed by rule against the gold labels in the test file -- | |
| there is no LLM judge anywhere in the loop. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import time | |
| import torch | |
| if hasattr(sys.stdout, "reconfigure"): # Windows consoles default to cp1252 | |
| sys.stdout.reconfigure(encoding="utf-8", errors="replace") | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from domain import INTENTS, NEXT_ACTIONS, PRIORITIES, SCHEMA_KEYS, VALID_POLICY_IDS # noqa: E402 | |
| from modeling import DEFAULT_ADAPTER, DEFAULT_MODEL, load_model, load_tokenizer, render_prompt # noqa: E402 | |
| from memorization import reproduction_rate, train_prose_set # noqa: E402 | |
| from prompts import SYSTEM_LONG, SYSTEM_SHORT, build_messages # noqa: E402 | |
| FENCE_RE = re.compile(r"```(?:json)?\s*(\{.*?\})\s*```", re.DOTALL) | |
| BARE_RE = re.compile(r"\{[^{}]*\}", re.DOTALL) | |
| ARMS = { | |
| "prompted": dict(system=SYSTEM_LONG, fewshot=False, adapter=None), | |
| "prompted_fewshot": dict(system=SYSTEM_LONG, fewshot=True, adapter=None), | |
| "short_prompt": dict(system=SYSTEM_SHORT, fewshot=False, adapter=None), | |
| "lora": dict(system=SYSTEM_SHORT, fewshot=False, adapter=DEFAULT_ADAPTER), | |
| } | |
| # ------------------------------------------------------------------ parsing -- | |
| def extract_json(text): | |
| """Return (obj_or_None, used_fence, trailing_text_after_block).""" | |
| fences = list(FENCE_RE.finditer(text)) | |
| if fences: | |
| m = fences[-1] | |
| trailing = text[m.end():].strip() | |
| try: | |
| return json.loads(m.group(1)), True, trailing | |
| except json.JSONDecodeError: | |
| return None, True, trailing | |
| bare = list(BARE_RE.finditer(text)) | |
| for m in reversed(bare): | |
| try: | |
| return json.loads(m.group(0)), False, text[m.end():].strip() | |
| except json.JSONDecodeError: | |
| continue | |
| return None, False, "" | |
| def prose_of(text): | |
| fences = list(FENCE_RE.finditer(text)) | |
| if fences: | |
| return text[: fences[-1].start()].strip() | |
| bare = list(BARE_RE.finditer(text)) | |
| if bare: | |
| return text[: bare[-1].start()].strip() | |
| return text.strip() | |
| def schema_ok(obj): | |
| if not isinstance(obj, dict): | |
| return False | |
| if set(obj) != set(SCHEMA_KEYS): | |
| return False | |
| if obj.get("intent") not in INTENTS: | |
| return False | |
| if obj.get("priority") not in PRIORITIES: | |
| return False | |
| if not isinstance(obj.get("escalate"), bool): | |
| return False | |
| if not isinstance(obj.get("policy_ids"), list) or not all(isinstance(p, str) for p in obj["policy_ids"]): | |
| return False | |
| if obj.get("next_action") not in NEXT_ACTIONS: | |
| return False | |
| return True | |
| # ---------------------------------------------------------------- inference -- | |
| def generate_batch(model, tok, batch_messages, max_new_tokens): | |
| texts = [render_prompt(tok, m) for m in batch_messages] | |
| enc = tok(texts, return_tensors="pt", padding=True, add_special_tokens=False).to(model.device) | |
| out = model.generate( | |
| **enc, | |
| max_new_tokens=max_new_tokens, | |
| do_sample=False, | |
| pad_token_id=tok.pad_token_id, | |
| eos_token_id=tok.eos_token_id, | |
| ) | |
| gen = out[:, enc["input_ids"].shape[1]:] | |
| return [tok.decode(g, skip_special_tokens=True).strip() for g in gen], gen | |
| # ------------------------------------------------------------------ scoring -- | |
| def score(preds, rows, tok, arm_meta): | |
| n = len(preds) | |
| agg = { | |
| "json_block": 0, "json_parse": 0, "schema_valid": 0, "trailing_text": 0, | |
| "intent": 0, "priority": 0, "next_action": 0, "policy_exact": 0, | |
| "tp": 0, "fp": 0, "fn": 0, # escalation | |
| "p_tp": 0, "p_fp": 0, "p_fn": 0, # policy ids | |
| "hallucinated_ids": 0, "rows_with_hallucination": 0, | |
| "prose_chars": 0, "prose_sentences": 0, | |
| } | |
| scored = 0 | |
| for pred_text, row in zip(preds, rows): | |
| gold = row["gold"][-1] | |
| obj, fenced, trailing = extract_json(pred_text) | |
| agg["json_block"] += int(fenced) | |
| agg["json_parse"] += int(obj is not None) | |
| agg["trailing_text"] += int(bool(trailing)) | |
| prose = prose_of(pred_text) | |
| agg["prose_chars"] += len(prose) | |
| agg["prose_sentences"] += len([s for s in re.split(r"[.!?]\s", prose) if s.strip()]) | |
| valid = schema_ok(obj) | |
| agg["schema_valid"] += int(valid) | |
| if obj is None: | |
| obj = {} | |
| scored += 1 | |
| agg["intent"] += int(obj.get("intent") == gold["intent"]) | |
| agg["priority"] += int(obj.get("priority") == gold["priority"]) | |
| agg["next_action"] += int(obj.get("next_action") == gold["next_action"]) | |
| pe, ge = obj.get("escalate") is True, gold["escalate"] | |
| agg["tp"] += int(pe and ge) | |
| agg["fp"] += int(pe and not ge) | |
| agg["fn"] += int(ge and not pe) | |
| pids = obj.get("policy_ids") | |
| pids = set(pids) if isinstance(pids, list) else set() | |
| gids = set(gold["policy_ids"]) | |
| agg["policy_exact"] += int(pids == gids) | |
| agg["p_tp"] += len(pids & gids) | |
| agg["p_fp"] += len(pids - gids) | |
| agg["p_fn"] += len(gids - pids) | |
| bad = {p for p in pids if p not in VALID_POLICY_IDS} | |
| agg["hallucinated_ids"] += len(bad) | |
| agg["rows_with_hallucination"] += int(bool(bad)) | |
| def f1(tp, fp, fn): | |
| p = tp / (tp + fp) if tp + fp else 0.0 | |
| r = tp / (tp + fn) if tp + fn else 0.0 | |
| return p, r, (2 * p * r / (p + r) if p + r else 0.0) | |
| ep, er, ef = f1(agg["tp"], agg["fp"], agg["fn"]) | |
| pp, pr, pf = f1(agg["p_tp"], agg["p_fp"], agg["p_fn"]) | |
| pct = lambda k: round(100 * agg[k] / n, 1) # noqa: E731 | |
| out = { | |
| "n": n, | |
| "json_block_rate": pct("json_block"), | |
| "json_parse_rate": pct("json_parse"), | |
| "schema_valid_rate": pct("schema_valid"), | |
| "trailing_text_rate": pct("trailing_text"), | |
| "intent_acc": pct("intent"), | |
| "priority_acc": pct("priority"), | |
| "next_action_acc": pct("next_action"), | |
| "escalation_precision": round(100 * ep, 1), | |
| "escalation_recall": round(100 * er, 1), | |
| "escalation_f1": round(100 * ef, 1), | |
| "escalation_support": agg["tp"] + agg["fn"], | |
| "policy_exact_set_match": pct("policy_exact"), | |
| "policy_precision": round(100 * pp, 1), | |
| "policy_recall": round(100 * pr, 1), | |
| "policy_f1": round(100 * pf, 1), | |
| "hallucinated_policy_id_rate": pct("rows_with_hallucination"), | |
| "mean_prose_chars": round(agg["prose_chars"] / n, 1), | |
| "mean_prose_sentences": round(agg["prose_sentences"] / n, 2), | |
| } | |
| out.update(arm_meta) | |
| return out | |
| # --------------------------------------------------------------------- main -- | |
| def build_arm_messages(rows, system, fewshot): | |
| batch = [] | |
| for row in rows: | |
| turns = [(m["role"], m["content"]) for m in row["messages"][:-1]] # drop the gold final answer | |
| batch.append(build_messages(system, turns, fewshot=fewshot)) | |
| return batch | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--model", default=DEFAULT_MODEL) | |
| ap.add_argument("--adapter", default=DEFAULT_ADAPTER) | |
| ap.add_argument("--test-file", default="data/test.jsonl") | |
| ap.add_argument("--arms", nargs="+", default=["prompted", "short_prompt", "lora"], choices=list(ARMS)) | |
| ap.add_argument("--limit", type=int, default=0) | |
| ap.add_argument("--batch-size", type=int, default=8) | |
| ap.add_argument("--max-new-tokens", type=int, default=300) | |
| ap.add_argument("--train-file", default="data/train.jsonl", | |
| help="used only to measure verbatim prose reuse") | |
| ap.add_argument("--out", default="results") | |
| args = ap.parse_args() | |
| rows = [json.loads(line) for line in open(args.test_file, encoding="utf-8") if line.strip()] | |
| if args.limit: | |
| rows = rows[: args.limit] | |
| os.makedirs(args.out, exist_ok=True) | |
| tok = load_tokenizer(args.model) | |
| train_prose = train_prose_set(args.train_file) if os.path.exists(args.train_file) else None | |
| all_metrics, all_samples = {}, {} | |
| for arm in args.arms: | |
| cfg = dict(ARMS[arm]) | |
| adapter = args.adapter if cfg["adapter"] else None | |
| if adapter and not os.path.isdir(adapter): | |
| print(f"[skip] arm '{arm}': no adapter at {adapter}") | |
| continue | |
| print(f"\n=== arm: {arm} ===") | |
| model = load_model(args.model, adapter=adapter) | |
| batch_msgs = build_arm_messages(rows, cfg["system"], cfg["fewshot"]) | |
| prompt_tokens = [len(tok(render_prompt(tok, m), add_special_tokens=False)["input_ids"]) for m in batch_msgs] | |
| preds, gen_tokens = [], 0 | |
| t0 = time.time() | |
| for i in range(0, len(batch_msgs), args.batch_size): | |
| chunk = batch_msgs[i: i + args.batch_size] | |
| texts, gen = generate_batch(model, tok, chunk, args.max_new_tokens) | |
| preds.extend(texts) | |
| gen_tokens += int((gen != tok.pad_token_id).sum()) | |
| print(f" {min(i + args.batch_size, len(batch_msgs))}/{len(batch_msgs)}", end="\r") | |
| elapsed = time.time() - t0 | |
| meta = { | |
| "arm": arm, | |
| "base_model": args.model, | |
| "mean_prompt_tokens": round(sum(prompt_tokens) / len(prompt_tokens), 1), | |
| "mean_generated_tokens": round(gen_tokens / len(preds), 1), | |
| "seconds_per_example": round(elapsed / len(preds), 2), | |
| "device": "cuda" if torch.cuda.is_available() else "cpu", | |
| } | |
| if train_prose: | |
| meta["prose_reproduced_from_train_rate"] = reproduction_rate(preds, train_prose) | |
| metrics = score(preds, rows, tok, meta) | |
| all_metrics[arm] = metrics | |
| all_samples[arm] = preds | |
| print("\n" + json.dumps(metrics, indent=2)) | |
| with open(os.path.join(args.out, f"preds_{arm}.jsonl"), "w", encoding="utf-8") as f: | |
| for row, pred in zip(rows, preds): | |
| f.write(json.dumps({"id": row["id"], "gold": row["gold"][-1], "prediction": pred}) + "\n") | |
| del model | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| merge_and_write(all_metrics, all_samples, rows, args.out) | |
| def merge_and_write(all_metrics, all_samples, rows, out_dir): | |
| path = os.path.join(out_dir, "metrics.json") | |
| existing = {} | |
| if os.path.exists(path): | |
| existing = json.load(open(path, encoding="utf-8")) | |
| existing.update(all_metrics) | |
| with open(path, "w", encoding="utf-8") as f: | |
| json.dump(existing, f, indent=2) | |
| order = [a for a in ARMS if a in existing] | |
| keys = [ | |
| ("mean_prompt_tokens", "Prompt tokens (mean)"), | |
| ("schema_valid_rate", "Schema-valid JSON %"), | |
| ("json_parse_rate", "Parsable JSON %"), | |
| ("trailing_text_rate", "Text after JSON block %"), | |
| ("intent_acc", "Intent accuracy %"), | |
| ("priority_acc", "Priority accuracy %"), | |
| ("next_action_acc", "Next-action accuracy %"), | |
| ("escalation_f1", "Escalation F1"), | |
| ("escalation_recall", "Escalation recall"), | |
| ("policy_exact_set_match", "Policy set exact match %"), | |
| ("policy_f1", "Policy-citation F1"), | |
| ("hallucinated_policy_id_rate", "Rows citing a non-existent policy %"), | |
| ("mean_prose_chars", "Prose length (chars)"), | |
| ("prose_reproduced_from_train_rate", "Prose copied verbatim from training %"), | |
| ("seconds_per_example", "Seconds / example"), | |
| ] | |
| lines = ["| Metric | " + " | ".join(order) + " |", "|---|" + "---|" * len(order)] | |
| for key, label in keys: | |
| lines.append("| " + label + " | " + " | ".join(str(existing[a].get(key, "-")) for a in order) + " |") | |
| md = "\n".join(lines) | |
| with open(os.path.join(out_dir, "summary.md"), "w", encoding="utf-8") as f: | |
| f.write("# Evaluation summary\n\n" + md + "\n") | |
| print("\n" + md) | |
| if all_samples: | |
| with open(os.path.join(out_dir, "samples.md"), "w", encoding="utf-8") as f: | |
| for i in range(min(6, len(rows))): | |
| f.write(f"## Test case {rows[i]['id']} ({rows[i]['intent']} / {rows[i]['variant']})\n\n") | |
| for m in rows[i]["messages"][:-1]: | |
| f.write(f"**{m['role']}:** {m['content']}\n\n") | |
| f.write(f"**gold labels:** `{json.dumps(rows[i]['gold'][-1])}`\n\n") | |
| for arm, preds in all_samples.items(): | |
| f.write(f"### {arm}\n\n```\n{preds[i]}\n```\n\n") | |
| if __name__ == "__main__": | |
| main() | |