Datasets:
Download audit_shortcuts.py from compressionawareintelligence/cai-bench: direct link, hf CLI and curl.
- Browser
- Download file 6.74 kB
-
https://huggingface.co/datasets/compressionawareintelligence/cai-bench/resolve/refs%2Fpr%2F4/audit_shortcuts.py
- Command line
-
hf download hf://datasets/compressionawareintelligence/cai-bench@refs/pr/4/audit_shortcuts.py
-
curl -L -o audit_shortcuts.py https://huggingface.co/datasets/compressionawareintelligence/cai-bench/resolve/refs%2Fpr%2F4/audit_shortcuts.py
6.74 kB
| #!/usr/bin/env python3 | |
| """Shortcut audit for the dynamics split: how far can a model get without reading the policy? | |
| Trains a classifier that sees only the customer's message (never the policy) and predicts the | |
| gold decision, with cross-validation grouped by scenario so no scenario is in both train and test. | |
| This is the policy-side analogue of a hypothesis-only baseline in NLI. A benchmark that tests | |
| policy reading should leave such a classifier with no scenario-level credit. | |
| It reports item accuracy per axis and level next to the majority-class rate, and the scenario | |
| metrics the classifier would reach if it also answered every multi-turn and value item perfectly | |
| (an upper bound for any message-only strategy on the paired metrics). | |
| pip install scikit-learn | |
| python audit_shortcuts.py --data data/dynamics.jsonl [--json audit_shortcuts.json] | |
| Also prints three structural checks that need no learning: whether interval width separates | |
| NEED_INFO from determined interval items, how many base cases a fixed-polarity phrase decides, | |
| and whether the L3 superseded rule decides the base case the other way. | |
| """ | |
| import argparse | |
| import json | |
| import re | |
| import sys | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| HERE = Path(__file__).resolve().parent | |
| sys.path.insert(0, str(HERE)) | |
| import caibench_dynamics as D # noqa: E402 | |
| def message_only_predictions(rows, folds=8, seed=0): | |
| import numpy as np | |
| from scipy.sparse import csr_matrix, hstack | |
| from sklearn.ensemble import GradientBoostingClassifier | |
| from sklearn.feature_extraction.text import CountVectorizer | |
| from sklearn.model_selection import GroupKFold | |
| items = [r for r in rows if r["answer_format"] == "decision" and not r["followups"] and r["axis"] != "control"] | |
| specs = sorted({r["spec_id"] for r in items}) | |
| def numf(r): | |
| nums = [int(x) for x in re.findall(r"\b\d+\b", r["user_message"])] | |
| return [nums[0] if len(nums) == 1 else -1, nums[0] if len(nums) == 2 else -1, | |
| nums[1] if len(nums) == 2 else -1, len(nums), specs.index(r["spec_id"])] | |
| vec = CountVectorizer(ngram_range=(1, 2), min_df=2, token_pattern=r"[A-Za-z_]+") | |
| X = hstack([vec.fit_transform([r["spec_id"] + " " + r["user_message"] for r in items]), | |
| csr_matrix(np.array([numf(r) for r in items], dtype=float))]).tocsr() | |
| y = np.array([r["gold_decision"] for r in items]) | |
| groups = np.array([r["group_id"] for r in items]) | |
| pred = np.empty(len(items), dtype=object) | |
| for tr, te in GroupKFold(n_splits=folds).split(X, y, groups): | |
| pred[te] = GradientBoostingClassifier(random_state=seed).fit(X[tr], y[tr]).predict(X[te]) | |
| return {r["item_id"]: p for r, p in zip(items, pred)} | |
| def structural(rows): | |
| spec_of = {s["id"]: s for s in D.SPECS} | |
| out = {} | |
| pairs = defaultdict(list) | |
| for r in rows: | |
| if r["variant_type"] in ("info_interval_inside", "info_interval_straddle") and r["numeric_relevant"]: | |
| a, b = map(int, re.findall(r"between (\d+) and (\d+)", r["user_message"])[0]) | |
| pairs[r["spec_id"]].append((b - a, r["gold_decision"] == D.NEED)) | |
| # best "wider than t means NEED_INFO" rule, with t chosen per policy family (an upper bound) | |
| best = sum(max(max(sum((w > t) == y for w, y in ps), sum((w <= t) == y for w, y in ps)) for t in range(0, 80)) | |
| for ps in pairs.values()) | |
| allp = [p for ps in pairs.values() for p in ps] | |
| out["interval_width_rule"] = {"best_correct": best, "n": len(allp), | |
| "majority": max(sum(y for _, y in allp), sum(not y for _, y in allp))} | |
| fixed = 0 | |
| bases = [r for r in rows if r["variant_type"] == "base"] | |
| for r in bases: | |
| s = spec_of[r["spec_id"]]; m = r["user_message"] | |
| if (s["override"] and s["override"]["t"] in m) or any((q["f"] if q["ok"] else q["t"]) in m for q in s["reqs"]): | |
| fixed += 1 | |
| twins = {r["group_id"] for r in rows if r["variant_type"] == "policy_twin"} | |
| out["base_decided_by_fixed_phrase"] = {"n": fixed, "of": len(bases), | |
| "with_policy_twin": sum(r["group_id"] in twins for r in bases)} | |
| diag = same = 0 | |
| for r in bases: | |
| if r["level"] != 3 or not r["numeric_relevant"]: | |
| continue | |
| f = json.loads(r["facts_json"]); spec = spec_of[r["spec_id"]] | |
| old = int(re.findall(r"\d+", re.search(r'section said: "(.*?)"', r["policy"]).group(1))[0]) | |
| if D.gold_of(spec, f, old, [f["num"]]) != r["gold_decision"]: | |
| diag += 1 | |
| else: | |
| same += 1 | |
| out["l3_superseded_rule"] = {"decides_base_other_way": diag, "same_decision": same} | |
| return out | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--data", default=str(D.DEFAULT_DATA)) | |
| ap.add_argument("--json", help="also write the report as JSON") | |
| ap.add_argument("--folds", type=int, default=8) | |
| a = ap.parse_args() | |
| rows = D.load(a.data) | |
| report = {"data": a.data, "structural": structural(rows)} | |
| try: | |
| mo = message_only_predictions(rows, a.folds) | |
| except ImportError: | |
| mo = None | |
| print("scikit-learn not installed; skipping the learned message-only classifier", file=sys.stderr) | |
| if mo is not None: | |
| by, maj = defaultdict(lambda: [0, 0]), defaultdict(Counter) | |
| for r in rows: | |
| if r["item_id"] not in mo: | |
| continue | |
| for k in (r["axis"], f"L{r['level']}", "all"): | |
| by[k][0] += mo[r["item_id"]] == r["gold_decision"]; by[k][1] += 1; maj[k][r["gold_decision"]] += 1 | |
| report["message_only_item_accuracy"] = {k: {"accuracy": round(v[0] / v[1], 3), | |
| "majority": round(max(maj[k].values()) / v[1], 3), "n": v[1]} | |
| for k, v in sorted(by.items())} | |
| # upper bound: perfect on everything the classifier does not answer | |
| pred = {r["item_id"]: ([mo[r["item_id"]]] if r["item_id"] in mo else list(r["turn_golds"])) for r in rows} | |
| m = D.metrics(rows, pred) | |
| report["message_only_upper_bound"] = {k: (m[k]["score"] if isinstance(m[k], dict) else m[k]) | |
| for k in ("decision_reliability", "precedence_tracking", | |
| "constraint_dynamics_index") | |
| + (("policy_grounding",) if "policy_grounding" in m else ())} | |
| print(json.dumps(report, indent=2)) | |
| if a.json: | |
| Path(a.json).write_text(json.dumps(report, indent=2) + "\n") | |
| if __name__ == "__main__": | |
| main() | |