Datasets:
Download code/score.py from labqoat/jev-skills: direct link, hf CLI and curl.
- Browser
- Download file 9.73 kB
-
https://huggingface.co/datasets/labqoat/jev-skills/resolve/main/code/score.py
- Command line
-
hf download hf://datasets/labqoat/jev-skills/code/score.py
-
curl -L -o score.py https://huggingface.co/datasets/labqoat/jev-skills/resolve/main/code/score.py
9.73 kB
| """Standalone scorer for the Jev Skills benchmark (all configs). No third-party imports for | |
| scoring (pandas / pyarrow only to read the parquet files). | |
| An item is a System One request: `state` (string) plus `questions` {key: spec} with spec | |
| {"type": "noul", "instructions": ...} yes / no, the answer is P(yes) | |
| {"type": "choice", "instructions": ..., "criteria": {id: description}} one option out of several | |
| {"type": "score", "instructions": ..., "criteria": [level, ...]} an ordinal level out of several | |
| and `targets` {key: {answer_id: probability}} (the gold; usually one-hot). For `score` questions the target ids are the | |
| indices "0", "1", ... of the levels. An item without a target for a question (the "missing" half of a missing-fact pair) | |
| is not scored for accuracy. | |
| A model is any callable `decide(state, questions) -> {key: answer}` with answer | |
| {"noul": p_yes} for noul questions | |
| {"probabilities": {option: p, ...}} for choice questions (keys = criteria ids) and score questions (keys = | |
| the level strings in `criteria`, or their indices as strings) | |
| Metrics (`score`): per skill (`category/skill`) accuracy (the top answer; a tie among the top answers shares the credit), Brier score | |
| (sum over options of (p - gold)^2) and top-1 ECE (10 bins; confidence = top probability, hit only if the top answer is | |
| unique and right); per source and per split accuracy; the mean skill accuracy per category (`pooled_by_category`); balanced accuracy of yes/no skills; | |
| `pick_accuracy/<split>` for items flagged `pick` (the argmax of P(yes) over the item's moves is a best move, ties share | |
| credit); and missing-facts AUROC (confidence = top probability separating complete from missing-fact records). | |
| python score.py data/rules.parquet --baseline oracle # gold answers: accuracy 1.0 | |
| python score.py data/rules.parquet --baseline uniform # uniform guesses: about chance | |
| """ | |
| import argparse | |
| import gzip | |
| import json | |
| from collections import defaultdict | |
| CATEGORIES = ("agents", "rules", "games_spatial", "safety", "judging") | |
| # ------------------------------------------------------------------ loading | |
| def load_items(path) -> list: | |
| """Items from a parquet / jsonl(.gz) / json(.gz) file (questions and targets as JSON strings or objects).""" | |
| p = str(path) | |
| if p.endswith(".parquet"): | |
| import pandas as pd | |
| rows = pd.read_parquet(p).to_dict("records") | |
| elif p.endswith(".gz"): | |
| with gzip.open(p, "rt") as fh: | |
| rows = json.load(fh) if ".json.gz" in p and ".jsonl" not in p else [json.loads(l) for l in fh if l.strip()] | |
| else: | |
| rows = [json.loads(l) for l in open(p) if l.strip()] | |
| out = [] | |
| for r in rows: | |
| r = dict(r) | |
| for k in ("questions", "targets"): | |
| if isinstance(r[k], str): | |
| r[k] = json.loads(r[k]) | |
| for k in ("variant", "pair", "removed"): # parquet nulls | |
| if k in r and (r[k] is None or r[k] != r[k]): | |
| del r[k] | |
| out.append(r) | |
| return out | |
| # ------------------------------------------------------------------ scoring | |
| def to_dist(spec, answer): | |
| if spec["type"] == "noul": | |
| p = float(answer["noul"]) | |
| return {"true": p, "false": 1 - p} | |
| probs = {str(k): float(v) for k, v in answer["probabilities"].items()} | |
| if spec["type"] == "score": | |
| levels = [str(level) for level in spec["criteria"]] | |
| probs = {str(levels.index(k)) if k in levels else k: v for k, v in probs.items()} | |
| total = sum(probs.values()) or 1.0 | |
| return {k: v / total for k, v in probs.items()} | |
| def _ece(conf_hit: list, bins: int = 10) -> float: | |
| if not conf_hit: | |
| return 0.0 | |
| tot = 0.0 | |
| for b in range(bins): | |
| sel = [(c, h) for c, h in conf_hit if (b / bins) < c <= ((b + 1) / bins) or (b == 0 and c == 0)] | |
| if sel: | |
| tot += len(sel) * abs(sum(c for c, _ in sel) / len(sel) - sum(h for _, h in sel) / len(sel)) | |
| return tot / len(conf_hit) | |
| def _auroc(pos: list, neg: list): | |
| """P(a random positive scores above a random negative); ties count half.""" | |
| if not pos or not neg: | |
| return None | |
| return round(sum((p > n) + 0.5 * (p == n) for p in pos for n in neg) / (len(pos) * len(neg)), 4) | |
| def score(items: list, answers: list) -> dict: | |
| acc = defaultdict(list) | |
| brier = defaultdict(list) | |
| conf = defaultdict(list) | |
| src_acc = defaultdict(list) | |
| split_acc = defaultdict(list) | |
| noul_hits = defaultdict(lambda: {True: [], False: []}) | |
| pick = defaultdict(list) | |
| miss = defaultdict(lambda: {"complete": [], "missing": []}) | |
| for x, ans in zip(items, answers, strict=True): | |
| item_hits = [] | |
| for k in x["questions"]: | |
| if k not in ans: | |
| continue | |
| dist = to_dist(x["questions"][k], ans[k]) | |
| best = max(dist.values()) | |
| if x.get("variant") in ("complete", "missing"): | |
| miss[x["source"].split(":")[1]][x["variant"]].append(best) | |
| target = x["targets"].get(k) | |
| if not target: | |
| continue | |
| gold = max(target, key=target.get) | |
| top = [o for o, v in dist.items() if v >= best - 1e-9] | |
| hit = (1.0 / len(top)) if gold in top else 0.0 | |
| acc[x["skill"]].append(hit) | |
| src_acc[x["source"]].append(hit) | |
| if x.get("split"): | |
| split_acc[(x["skill"], x["split"])].append(hit) | |
| brier[x["skill"]].append(sum((v - target.get(o, 0.0)) ** 2 for o, v in dist.items())) | |
| conf[x["skill"]].append((best, 1.0 if top[0] == gold and len(top) == 1 else 0.0)) | |
| if x["questions"][k]["type"] == "noul": | |
| noul_hits[x["skill"]][gold == "true"].append(hit) | |
| item_hits.append((dist.get("true", 0.0), gold == "true")) | |
| if x.get("pick") and item_hits: | |
| top_p = max(p for p, _ in item_hits) | |
| ok = [g for p, g in item_hits if p >= top_p - 1e-9] | |
| pick[(x["skill"], x.get("split", ""))].append(sum(ok) / len(ok)) | |
| skills = sorted(acc) | |
| out = {"skills": {s: {"n": len(acc[s]), "accuracy": round(sum(acc[s]) / len(acc[s]), 4), | |
| "brier": round(sum(brier[s]) / len(brier[s]), 4), "ece": round(_ece(conf[s]), 4)} | |
| for s in skills if acc[s]}} | |
| # category score = mean of its skills' accuracies; rules/missing_facts is reported apart (AUROC, see extras) | |
| cat = defaultdict(list) | |
| for s, v in out["skills"].items(): | |
| if s != "rules/missing_facts": | |
| cat[s.split("/")[0]].append(v["accuracy"]) | |
| out["pooled_by_category"] = {c: round(sum(cat[c]) / len(cat[c]), 4) for c in CATEGORIES if cat[c]} | |
| allacc = [a for c in cat.values() for a in c] | |
| out["pooled_all"] = round(sum(allacc) / max(1, len(allacc)), 4) | |
| out["per_source"] = {s: round(sum(v) / len(v), 4) for s, v in sorted(src_acc.items())} | |
| if split_acc: | |
| out["per_split"] = {f"{s}/{sp}": {"n": len(v), "accuracy": round(sum(v) / len(v), 4)} | |
| for (s, sp), v in sorted(split_acc.items())} | |
| extras = {} | |
| for s, h in noul_hits.items(): | |
| if h[True] and h[False]: | |
| extras.setdefault(s, {})["balanced_accuracy"] = round( | |
| (sum(h[True]) / len(h[True]) + sum(h[False]) / len(h[False])) / 2, 4) | |
| for (s, sp), v in sorted(pick.items()): | |
| extras.setdefault(s, {})[f"pick_accuracy/{sp}" if sp else "pick_accuracy"] = round(sum(v) / len(v), 4) | |
| for t, d in sorted(miss.items()): | |
| extras.setdefault("rules/missing_facts", {})[f"auroc/{t}"] = _auroc(d["complete"], d["missing"]) | |
| if extras: | |
| out["extras"] = extras | |
| return out | |
| def evaluate(decide, items: list) -> dict: | |
| """Run `decide(state, questions)` over the items and score it.""" | |
| return score(items, [decide(x["state"], x["questions"]) for x in items]) | |
| # ------------------------------------------------------------------ reference deciders | |
| def _uniform(spec): | |
| if spec["type"] == "noul": | |
| return {"noul": 0.5} | |
| crit = spec["criteria"] | |
| ids = list(crit) if isinstance(crit, dict) else [str(l) for l in crit] | |
| return {"probabilities": {i: 1.0 / len(ids) for i in ids}} | |
| def uniform_decider(state, questions): | |
| return {k: _uniform(q) for k, q in questions.items()} | |
| def oracle_for(items: list): | |
| """Answers equal to the gold (uniform where an item has no gold, e.g. the missing-fact half of a pair).""" | |
| by = {(x["state"], json.dumps(x["questions"], sort_keys=True)): x for x in items} | |
| def decide(state, questions): | |
| x = by[(state, json.dumps(questions, sort_keys=True))] | |
| out = {} | |
| for k, q in questions.items(): | |
| t = x["targets"].get(k) | |
| if not t: | |
| out[k] = _uniform(q) | |
| elif q["type"] == "noul": | |
| out[k] = {"noul": float(t.get("true", 0.0))} | |
| elif q["type"] == "score": | |
| out[k] = {"probabilities": {str(q["criteria"][int(i)]): float(v) for i, v in t.items()}} | |
| else: | |
| out[k] = {"probabilities": dict(t)} | |
| return out | |
| return decide | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("items", nargs="+", help="parquet / jsonl(.gz) item files") | |
| ap.add_argument("--baseline", choices=["oracle", "uniform"], required=True) | |
| a = ap.parse_args() | |
| its = [x for p in a.items for x in load_items(p)] | |
| fn = oracle_for(its) if a.baseline == "oracle" else uniform_decider | |
| print(json.dumps(evaluate(fn, its), indent=1)) | |