File size: 10,319 Bytes
d428e08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
"""
StepProbe: End-to-End Evaluation Pipeline

Orchestrates the full pipeline:
    inference -> segment -> diagnose -> metrics -> restore -> re-evaluate

Usage:
    python scripts/run_eval.py --config configs/default.yaml
    python scripts/run_eval.py --model deepseek-ai/DeepSeek-R1-Distill-Qwen-7B --benchmark gsm8k --quick
"""

import argparse
import json
import os
import sys
import time
from datetime import datetime

import yaml

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

from stepprobe.segment import segment_cot
from stepprobe.align import align_steps, alignment_summary
from stepprobe.diagnose import diagnose_batch, LLMJudge, RuleBasedJudge
from stepprobe.metrics import aggregate_metrics, format_results_table
from stepprobe.utils import load_jsonl, save_jsonl, save_json, set_seed, check_answer, extract_gsm8k_answer, extract_number


def run_inference_phase(model_name, quant, bits, benchmark, output_dir, max_samples=None, max_tokens=4096):
    """Run inference and return path to output file."""
    from scripts.run_inference import load_model, load_benchmark, generate_cot
    from tqdm import tqdm

    os.makedirs(output_dir, exist_ok=True)
    tag = f"{quant}_w{bits}" if quant != "fp16" else "fp16"
    out_file = os.path.join(output_dir, f"{benchmark}_{tag}.jsonl")

    if os.path.exists(out_file):
        print(f"  [SKIP] {out_file} already exists")
        return out_file

    print(f"  Loading model: {model_name} ({tag})")
    model, tokenizer = load_model(model_name, quant, bits)

    print(f"  Loading benchmark: {benchmark}")
    problems = load_benchmark(benchmark, max_samples=max_samples)

    records = []
    for prob in tqdm(problems, desc=f"Inference ({tag})"):
        result = generate_cot(model, tokenizer, prob["question"], max_tokens)
        record = {
            "problem_id": prob["id"],
            "question": prob["question"],
            "gold_answer": prob["answer"],
            "model": model_name,
            "quantization": tag,
            **result,
        }
        records.append(record)

    save_jsonl(records, out_file)
    print(f"  Saved {len(records)} results -> {out_file}")

    # Free GPU memory
    del model
    import torch
    if torch.cuda.is_available():
        torch.cuda.empty_cache()

    return out_file


def run_segment_phase(inference_file, output_dir, model_name="", quant="fp16"):
    """Segment CoT traces into steps."""
    os.makedirs(output_dir, exist_ok=True)
    basename = os.path.basename(inference_file)
    out_file = os.path.join(output_dir, basename)

    if os.path.exists(out_file):
        print(f"  [SKIP] {out_file} already exists")
        return out_file

    records = load_jsonl(inference_file)
    segmented = []

    for rec in records:
        seg = segment_cot(
            problem_id=rec["problem_id"],
            raw_output=rec.get("output", ""),
            model=model_name,
            quantization=quant,
        )
        seg_dict = seg.to_dict()
        # Carry over metadata
        seg_dict["question"] = rec.get("question", "")
        seg_dict["gold_answer"] = rec.get("gold_answer", "")
        seg_dict["n_tokens"] = rec.get("n_tokens", 0)
        segmented.append(seg_dict)

    save_jsonl(segmented, out_file)
    print(f"  Segmented {len(segmented)} traces -> {out_file}")
    return out_file


def run_diagnose_phase(ref_file, hyp_file, output_dir, use_llm_judge=False, judge_provider="openai"):
    """Diagnose step-level errors."""
    os.makedirs(output_dir, exist_ok=True)
    basename = os.path.basename(hyp_file)
    out_file = os.path.join(output_dir, basename)

    if os.path.exists(out_file):
        print(f"  [SKIP] {out_file} already exists")
        return out_file

    ref_traces = load_jsonl(ref_file)
    hyp_traces = load_jsonl(hyp_file)

    # Reconstruct problems
    problems = []
    for t in ref_traces:
        problems.append({
            "problem_id": t["problem_id"],
            "question": t.get("question", ""),
            "gold_answer": t.get("gold_answer", ""),
        })

    judge = None
    if use_llm_judge:
        judge = LLMJudge(provider=judge_provider)

    diagnosed = diagnose_batch(
        ref_traces=ref_traces,
        hyp_traces=hyp_traces,
        problems=problems,
        judge=judge,
    )

    save_jsonl(diagnosed, out_file)
    print(f"  Diagnosed {len(diagnosed)} traces -> {out_file}")
    return out_file


def run_metrics_phase(diagnosis_file, output_dir, fp16_acc=None, fp16_ffs=None):
    """Compute StepProbe metrics."""
    os.makedirs(output_dir, exist_ok=True)
    basename = os.path.splitext(os.path.basename(diagnosis_file))[0]
    out_file = os.path.join(output_dir, f"{basename}_metrics.json")

    traces = load_jsonl(diagnosis_file)
    if not traces:
        print(f"  [WARN] No traces in {diagnosis_file}")
        return None

    result = aggregate_metrics(traces, fp16_accuracy=fp16_acc, fp16_avg_ffs=fp16_ffs)

    save_json({
        "model": result.model,
        "quantization": result.quantization,
        "n_problems": result.n_problems,
        "accuracy": result.accuracy,
        "accuracy_delta": result.accuracy_delta,
        "avg_ffs": result.avg_ffs,
        "median_ffs": result.median_ffs,
        "ffs_std": result.ffs_std,
        "ecr": result.ecr,
        "ssr_curve": result.ssr_curve,
        "error_type_dist": result.error_type_dist,
        "avg_token_count": result.avg_token_count,
    }, out_file)

    print(f"  Metrics: acc={result.accuracy:.1%}, FFS={result.avg_ffs:.1f}, ECR={result.ecr:.1%}")
    return result


def main():
    parser = argparse.ArgumentParser(description="End-to-end StepProbe evaluation")
    parser.add_argument("--config", default=None, help="YAML config file")
    parser.add_argument("--model", default="deepseek-ai/DeepSeek-R1-Distill-Qwen-7B")
    parser.add_argument("--benchmark", default="gsm8k", choices=["gsm8k", "math500", "gpqa"])
    parser.add_argument("--quant-methods", nargs="*", default=["bnb_nf4"],
                        help="Quantization methods to test")
    parser.add_argument("--bits", nargs="*", type=int, default=[4])
    parser.add_argument("--output", default="results/")
    parser.add_argument("--max-samples", type=int, default=None, help="Limit samples (for testing)")
    parser.add_argument("--quick", action="store_true", help="Quick test with 20 samples")
    parser.add_argument("--use-llm-judge", action="store_true")
    parser.add_argument("--skip-restore", action="store_true")
    parser.add_argument("--seed", type=int, default=42)
    args = parser.parse_args()

    set_seed(args.seed)

    if args.quick:
        args.max_samples = 20

    base_dir = args.output
    os.makedirs(base_dir, exist_ok=True)

    # Log
    log = {
        "start_time": datetime.now().isoformat(),
        "model": args.model,
        "benchmark": args.benchmark,
        "quant_methods": args.quant_methods,
        "bits": args.bits,
        "max_samples": args.max_samples,
    }

    print("=" * 70)
    print("StepProbe: End-to-End Evaluation")
    print("=" * 70)
    print(f"Model:      {args.model}")
    print(f"Benchmark:  {args.benchmark}")
    print(f"Quant:      {args.quant_methods} x {args.bits}-bit")
    print(f"Samples:    {args.max_samples or 'all'}")
    print()

    # ========== Phase 1: FP16 Baseline ==========
    print("[Phase 1] FP16 Baseline Inference")
    fp16_inf = run_inference_phase(
        args.model, "fp16", 16, args.benchmark,
        os.path.join(base_dir, "inference", "fp16"),
        max_samples=args.max_samples,
    )

    print("\n[Phase 1b] Segmenting FP16 traces")
    fp16_seg = run_segment_phase(
        fp16_inf, os.path.join(base_dir, "segmented", "fp16"),
        model_name=args.model, quant="fp16",
    )

    # Compute FP16 accuracy
    fp16_traces = load_jsonl(fp16_inf)
    fp16_correct = 0
    for t in fp16_traces:
        gold = t.get("gold_answer", "")
        if "####" in gold:
            gold = extract_gsm8k_answer(gold)
        pred = extract_number(t.get("output", ""))
        if pred and check_answer(pred, gold):
            fp16_correct += 1
    fp16_acc = fp16_correct / len(fp16_traces) if fp16_traces else 0
    print(f"  FP16 accuracy: {fp16_acc:.1%} ({fp16_correct}/{len(fp16_traces)})")

    # ========== Phase 2: Quantized Inference ==========
    all_results = []

    for quant_method in args.quant_methods:
        for bits in args.bits:
            tag = f"{quant_method}_w{bits}"
            print(f"\n[Phase 2] Quantized Inference: {tag}")

            quant_inf = run_inference_phase(
                args.model, quant_method, bits, args.benchmark,
                os.path.join(base_dir, "inference", tag),
                max_samples=args.max_samples,
            )

            # ========== Phase 3: Segment ==========
            print(f"[Phase 3] Segmenting {tag} traces")
            quant_seg = run_segment_phase(
                quant_inf, os.path.join(base_dir, "segmented", tag),
                model_name=args.model, quant=tag,
            )

            # ========== Phase 4: Diagnose ==========
            print(f"[Phase 4] Diagnosing {tag}")
            diag_file = run_diagnose_phase(
                fp16_seg, quant_seg,
                os.path.join(base_dir, "diagnosis", tag),
                use_llm_judge=args.use_llm_judge,
            )

            # ========== Phase 5: Metrics ==========
            print(f"[Phase 5] Computing metrics for {tag}")
            result = run_metrics_phase(
                diag_file,
                os.path.join(base_dir, "metrics"),
                fp16_acc=fp16_acc,
            )
            if result:
                all_results.append(result)

    # ========== Summary ==========
    print("\n" + "=" * 70)
    print("RESULTS SUMMARY")
    print("=" * 70)
    if all_results:
        print(format_results_table(all_results))

    log["end_time"] = datetime.now().isoformat()
    log["fp16_accuracy"] = fp16_acc
    log["results"] = [
        {"quant": r.quantization, "accuracy": r.accuracy, "avg_ffs": r.avg_ffs, "ecr": r.ecr}
        for r in all_results
    ]
    save_json(log, os.path.join(base_dir, "eval_log.json"))

    print(f"\nAll results saved to {base_dir}")
    print("Done!")


if __name__ == "__main__":
    main()