File size: 6,737 Bytes
10f1588
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()