File size: 7,751 Bytes
3ccaf5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Validate the rule-based error-type classifier against an LLM judge.

Samples N failed steps from the existing diagnosis output, re-classifies
them with an LLM judge (OpenAI or Anthropic via stepprobe.diagnose's
built-in LLMJudge), and reports Cohen's κ plus a 4×4 confusion matrix.

Without an API key, the script still runs end-to-end using a second
round of rule-based labelling with different hashing seeds as a weak
sanity check (prints agreement, κ likely near 1.0 — signals you need a
real API call to reach something publishable).

Outputs (JSON):
    results/validation/classifier/agreement.json
    results/validation/classifier/samples.jsonl
"""

import argparse
import json
import os
import random
import sys
from collections import Counter
from typing import Dict, List, Tuple

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from stepprobe.diagnose import LLMJudge, RuleBasedJudge
from stepprobe.utils import load_jsonl


ERROR_TYPES = ["conceptual", "methodological", "executional", "logical"]


def _cohen_kappa(labels_a: List[str], labels_b: List[str],
                 categories: List[str]) -> float:
    """Unweighted Cohen's kappa on two aligned label sequences."""
    assert len(labels_a) == len(labels_b)
    n = len(labels_a)
    if n == 0:
        return float("nan")

    cat_idx = {c: i for i, c in enumerate(categories)}
    K = len(categories)
    cm = [[0] * K for _ in range(K)]
    for a, b in zip(labels_a, labels_b):
        if a not in cat_idx or b not in cat_idx:
            continue
        cm[cat_idx[a]][cat_idx[b]] += 1

    total = sum(sum(row) for row in cm)
    if total == 0:
        return float("nan")
    p_obs = sum(cm[i][i] for i in range(K)) / total
    row_sums = [sum(cm[i]) for i in range(K)]
    col_sums = [sum(cm[i][j] for i in range(K)) for j in range(K)]
    p_exp = sum(row_sums[i] * col_sums[i] for i in range(K)) / (total * total)
    if p_exp >= 1:
        return float("nan")
    return (p_obs - p_exp) / (1 - p_exp)


def _collect_failed_steps(diagnosis_root: str, max_samples: int,
                          seed: int = 42) -> List[dict]:
    """Walk diagnosis dir, pull (problem_id, step, error_type) triples."""
    rng = random.Random(seed)
    candidates: List[dict] = []
    for root, _dirs, files in os.walk(diagnosis_root):
        for fname in files:
            if not fname.endswith(".jsonl"):
                continue
            path = os.path.join(root, fname)
            try:
                traces = load_jsonl(path)
            except Exception:
                continue
            # infer (quant, model) from the path
            parts = os.path.relpath(path, diagnosis_root).split(os.sep)
            quant_tag = parts[0] if len(parts) > 1 else "unknown"
            model_tag = parts[1] if len(parts) > 2 else "unknown"
            for t in traces:
                for step in (t.get("steps") or []):
                    if step.get("is_correct") is False and step.get("error_type") in ERROR_TYPES:
                        candidates.append({
                            "problem_id": t.get("problem_id"),
                            "model": model_tag,
                            "quant": quant_tag,
                            "step_index": step.get("index"),
                            "step_text": step.get("text", ""),
                            "rule_based": step.get("error_type"),
                        })
    rng.shuffle(candidates)
    return candidates[:max_samples]


def _relabel_with_judge(samples: List[dict], judge_kind: str,
                        judge_model: str = None) -> List[str]:
    """Re-run error-type classification on each sampled step using an LLM
    judge. Falls back to a rule-based re-judge if `judge_kind=rule`."""
    if judge_kind == "rule":
        j = RuleBasedJudge()
    else:
        j = LLMJudge(judge_kind, judge_model or ("gpt-4o" if judge_kind == "openai" else "claude-3-5-sonnet-latest"))

    out = []
    for i, s in enumerate(samples):
        try:
            # We don't have paired ref step here; pass an empty ref to let
            # the classifier decide on content alone. The paper's rule-based
            # classifier works this way too.
            label = j.classify_error(problem=s["problem_id"],
                                     ref_step="",
                                     hyp_step=s["step_text"])
        except Exception:
            label = "executional"
        if label not in ERROR_TYPES:
            label = "executional"
        out.append(label)
        if (i + 1) % 25 == 0:
            print(f"  judged {i+1}/{len(samples)}")
    return out


def _confusion(labels_a, labels_b, categories):
    cat_idx = {c: i for i, c in enumerate(categories)}
    K = len(categories)
    cm = [[0] * K for _ in range(K)]
    for a, b in zip(labels_a, labels_b):
        if a in cat_idx and b in cat_idx:
            cm[cat_idx[a]][cat_idx[b]] += 1
    return cm


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--diagnosis-root", default="results/diagnosis")
    parser.add_argument("--output-dir", default="results/validation/classifier")
    parser.add_argument("--n-samples", type=int, default=200)
    parser.add_argument("--judge", default="rule",
                        choices=["rule", "openai", "anthropic"],
                        help="Which judge to use as ground truth. 'rule' is a "
                             "sanity-check mode that gives κ≈1 — use openai or "
                             "anthropic for a real validation.")
    parser.add_argument("--judge-model", default=None,
                        help="Model name for the judge (e.g., gpt-4o, claude-3-5-sonnet-latest).")
    parser.add_argument("--seed", type=int, default=42)
    args = parser.parse_args()

    os.makedirs(args.output_dir, exist_ok=True)

    print(f"Sampling up to {args.n_samples} failed steps from {args.diagnosis_root}...")
    samples = _collect_failed_steps(args.diagnosis_root, args.n_samples, args.seed)
    print(f"  Collected {len(samples)} samples.")

    print(f"Judging with {args.judge}...")
    judge_labels = _relabel_with_judge(samples, args.judge, args.judge_model)

    rule_labels = [s["rule_based"] for s in samples]

    kappa = _cohen_kappa(rule_labels, judge_labels, ERROR_TYPES)
    cm = _confusion(rule_labels, judge_labels, ERROR_TYPES)

    dist_rule = Counter(rule_labels)
    dist_judge = Counter(judge_labels)

    # Persist everything so downstream reports can reuse it.
    with open(os.path.join(args.output_dir, "samples.jsonl"), "w") as f:
        for s, jl in zip(samples, judge_labels):
            f.write(json.dumps({**s, "judge_label": jl, "judge": args.judge},
                               ensure_ascii=False) + "\n")

    report = {
        "n_samples": len(samples),
        "judge": args.judge,
        "cohen_kappa": kappa,
        "categories": ERROR_TYPES,
        "confusion_matrix_rule_rows_judge_cols": cm,
        "distribution_rule_based": dict(dist_rule),
        "distribution_judge": dict(dist_judge),
    }
    with open(os.path.join(args.output_dir, "agreement.json"), "w") as f:
        json.dump(report, f, indent=2)

    print()
    print(f"  Cohen's κ (rule vs {args.judge}): {kappa:.3f}")
    print(f"  Confusion matrix (rows = rule-based, columns = {args.judge}):")
    header = "            " + "  ".join(f"{c[:6]:>6s}" for c in ERROR_TYPES)
    print(header)
    for i, c in enumerate(ERROR_TYPES):
        row = "  ".join(f"{cm[i][j]:>6d}" for j in range(len(ERROR_TYPES)))
        print(f"    {c[:10]:<10s}  {row}")
    print()
    print(f"  Full report: {os.path.join(args.output_dir, 'agreement.json')}")


if __name__ == "__main__":
    main()