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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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
"""
StepProbe: Step-Level Error Diagnosis

Uses an LLM judge (GPT-4o or Claude) to classify each divergent step
into one of four error types: conceptual, methodological, executional, logical.
Also determines the correctness of each step independently.
"""

import json
import os
import time
from typing import List, Dict, Optional, Tuple
from dataclasses import dataclass

from stepprobe.align import align_steps, StepAlignment
from stepprobe.utils import load_jsonl, save_jsonl, check_answer, extract_number


# ============================================================
# LLM Judge Prompts
# ============================================================

STEP_CORRECTNESS_PROMPT = """You are an expert mathematics and reasoning evaluator. You will be given:
1. A math/reasoning problem
2. The ground-truth solution (from a full-precision model)
3. A single reasoning step from a quantized model

Your task: Determine if the quantized model's step is CORRECT or INCORRECT.

A step is CORRECT if:
- The mathematical operations are valid
- The logic follows from previous steps
- No arithmetic errors are present
- The concept/method applied is appropriate

A step is INCORRECT if ANY of the above are violated.

Problem:
{problem}

Ground-truth solution context:
{ref_context}

Step to evaluate (from quantized model):
{hyp_step}

Respond with EXACTLY one of:
CORRECT
INCORRECT

Your judgment:"""

ERROR_CLASSIFICATION_PROMPT = """You are an expert at diagnosing reasoning errors in language models. You will be given:
1. A math/reasoning problem
2. The correct reasoning step (from a full-precision model)
3. The incorrect reasoning step (from a quantized model)

Classify the error into EXACTLY ONE of these four categories:

CONCEPTUAL: Wrong mathematical concept or theorem applied.
  Examples: Using addition instead of multiplication, applying wrong formula entirely,
  confusing probability with frequency, wrong theorem.

METHODOLOGICAL: Correct concept but wrong approach, setup, or formula application.
  Examples: Correct integration concept but wrong substitution, setting up equation
  incorrectly, wrong order of operations in a valid approach.

EXECUTIONAL: Correct method but arithmetic/computation errors.
  Examples: 7 × 8 = 54, carrying errors, decimal point mistakes, sign errors,
  simplification mistakes.

LOGICAL: Invalid logical inference or reasoning jump.
  Examples: Concluding A > C from A > B without B > C, circular reasoning,
  non-sequitur conclusions, ignoring edge cases, invalid generalizations.

Problem:
{problem}

Correct step (reference):
{ref_step}

Incorrect step (quantized):
{hyp_step}

Respond with EXACTLY one word from: CONCEPTUAL, METHODOLOGICAL, EXECUTIONAL, LOGICAL

Error type:"""


# ============================================================
# LLM Judge Interface
# ============================================================

class LLMJudge:
    """Interface for LLM-based step evaluation."""

    def __init__(self, provider: str = "openai", model: str = "gpt-4o", temperature: float = 0.0):
        self.provider = provider
        self.model = model
        self.temperature = temperature
        self._client = None

    def _get_client(self):
        if self._client is not None:
            return self._client
        if self.provider == "openai":
            from openai import OpenAI
            self._client = OpenAI()
        elif self.provider == "anthropic":
            from anthropic import Anthropic
            self._client = Anthropic()
        else:
            raise ValueError(f"Unknown provider: {self.provider}")
        return self._client

    def _call(self, prompt: str) -> str:
        client = self._get_client()
        for attempt in range(3):
            try:
                if self.provider == "openai":
                    resp = client.chat.completions.create(
                        model=self.model,
                        messages=[{"role": "user", "content": prompt}],
                        temperature=self.temperature,
                        max_tokens=50,
                    )
                    return resp.choices[0].message.content.strip()
                elif self.provider == "anthropic":
                    resp = client.messages.create(
                        model=self.model,
                        max_tokens=50,
                        temperature=self.temperature,
                        messages=[{"role": "user", "content": prompt}],
                    )
                    return resp.content[0].text.strip()
            except Exception as e:
                print(f"  [Judge] Attempt {attempt+1} failed: {e}")
                time.sleep(2 ** attempt)
        return "ERROR"

    def judge_correctness(self, problem: str, ref_context: str, hyp_step: str) -> bool:
        """Judge whether a single step is correct."""
        prompt = STEP_CORRECTNESS_PROMPT.format(
            problem=problem,
            ref_context=ref_context,
            hyp_step=hyp_step,
        )
        result = self._call(prompt).upper()
        return "CORRECT" in result

    def classify_error(self, problem: str, ref_step: str, hyp_step: str) -> str:
        """Classify an incorrect step into one of four error types."""
        prompt = ERROR_CLASSIFICATION_PROMPT.format(
            problem=problem,
            ref_step=ref_step,
            hyp_step=hyp_step,
        )
        result = self._call(prompt).upper()
        for etype in ["CONCEPTUAL", "METHODOLOGICAL", "EXECUTIONAL", "LOGICAL"]:
            if etype in result:
                return etype.lower()
        return "executional"  # default fallback


class RuleBasedJudge:
    """
    Fast, free, heuristic-based judge for initial screening.
    Uses the reference answer to determine final-answer correctness,
    and simple heuristics for step-level checks.
    """

    def judge_correctness(self, problem: str, ref_context: str, hyp_step: str) -> bool:
        """Heuristic: check if key numbers from reference appear in hypothesis."""
        import re
        ref_nums = set(re.findall(r"-?\d+\.?\d*", ref_context))
        hyp_nums = set(re.findall(r"-?\d+\.?\d*", hyp_step))
        # If the step introduces a number not in the reference, flag it
        novel_nums = hyp_nums - ref_nums
        # Very rough heuristic: if many novel numbers, likely wrong
        if len(novel_nums) > 3:
            return False
        return True

    def classify_error(self, problem: str, ref_step: str, hyp_step: str) -> str:
        """Heuristic classification based on text patterns."""
        import re
        hyp_lower = hyp_step.lower()

        # Check for arithmetic errors
        ref_nums = re.findall(r"\d+\s*[+\-*/×÷]\s*\d+\s*=\s*(\d+)", ref_step)
        hyp_nums = re.findall(r"\d+\s*[+\-*/×÷]\s*\d+\s*=\s*(\d+)", hyp_step)
        if ref_nums and hyp_nums and ref_nums != hyp_nums:
            return "executional"

        # Check for method keywords divergence
        method_words = ["substitute", "integrate", "differentiate", "factor", "expand", "simplify"]
        ref_methods = [w for w in method_words if w in ref_step.lower()]
        hyp_methods = [w for w in method_words if w in hyp_lower]
        if ref_methods and hyp_methods and set(ref_methods) != set(hyp_methods):
            return "methodological"

        # Check for logical connectors misuse
        logic_words = ["therefore", "because", "since", "implies", "hence", "thus"]
        if any(w in hyp_lower for w in logic_words):
            return "logical"

        return "conceptual"


# ============================================================
# Diagnosis Pipeline
# ============================================================

def diagnose_single_problem(
    problem_text: str,
    gold_answer: str,
    ref_trace: dict,
    hyp_trace: dict,
    judge: LLMJudge = None,
    alignment_method: str = "dtw",
) -> dict:
    """
    Diagnose a single problem: align steps, judge correctness, classify errors.

    Returns:
        Updated hyp_trace dict with is_correct and error_type filled in for each step.
    """
    ref_steps = ref_trace.get("steps", [])
    hyp_steps = hyp_trace.get("steps", [])

    # Check final answer correctness
    hyp_answer = hyp_trace.get("final_answer", "")
    is_correct_final = check_answer(hyp_answer, gold_answer)

    # If final answer is correct, assume all steps are correct (optimistic)
    if is_correct_final:
        for step in hyp_steps:
            step["is_correct"] = True
            step["error_type"] = None
        hyp_trace["is_correct_final"] = True
        hyp_trace["steps"] = hyp_steps
        return hyp_trace

    # Final answer is wrong: find where it went wrong
    hyp_trace["is_correct_final"] = False

    # Align steps
    alignments = align_steps(ref_steps, hyp_steps, method=alignment_method)

    # Build reference context (full solution)
    ref_context = "\n".join(s["text"] for s in ref_steps)

    # Judge each step
    found_first_error = False
    for alignment in alignments:
        if alignment.hyp_index is None:
            continue  # deleted step, skip

        hyp_step_dict = None
        for s in hyp_steps:
            if s["index"] == alignment.hyp_index:
                hyp_step_dict = s
                break
        if hyp_step_dict is None:
            continue

        if alignment.alignment_type == "match" and alignment.similarity > 0.85:
            # High similarity to reference -> likely correct
            hyp_step_dict["is_correct"] = True
            hyp_step_dict["error_type"] = None
        elif judge is not None:
            # Use LLM judge
            is_correct = judge.judge_correctness(
                problem=problem_text,
                ref_context=ref_context,
                hyp_step=hyp_step_dict["text"],
            )
            hyp_step_dict["is_correct"] = is_correct

            if not is_correct:
                found_first_error = True
                ref_text = alignment.ref_text if alignment.ref_text else ref_context
                error_type = judge.classify_error(
                    problem=problem_text,
                    ref_step=ref_text,
                    hyp_step=hyp_step_dict["text"],
                )
                hyp_step_dict["error_type"] = error_type
            else:
                hyp_step_dict["error_type"] = None
        else:
            # No judge: use alignment similarity as proxy
            if alignment.similarity > 0.6:
                hyp_step_dict["is_correct"] = True
                hyp_step_dict["error_type"] = None
            else:
                hyp_step_dict["is_correct"] = False
                # Use rule-based classification
                rb = RuleBasedJudge()
                hyp_step_dict["error_type"] = rb.classify_error(
                    problem=problem_text,
                    ref_step=alignment.ref_text,
                    hyp_step=hyp_step_dict["text"],
                )

    # If final answer is wrong but we found no step-level error, mark last step
    if not is_correct_final and not any(s.get("is_correct") == False for s in hyp_steps):
        if hyp_steps:
            hyp_steps[-1]["is_correct"] = False
            hyp_steps[-1]["error_type"] = "executional"

    hyp_trace["steps"] = hyp_steps
    return hyp_trace


def diagnose_batch(
    ref_traces: List[dict],
    hyp_traces: List[dict],
    problems: List[dict],
    judge: LLMJudge = None,
    alignment_method: str = "dtw",
    verbose: bool = True,
) -> List[dict]:
    """
    Diagnose a batch of problems.

    Args:
        ref_traces: Segmented FP16 traces (list of dicts)
        hyp_traces: Segmented quantized traces (list of dicts)
        problems: Original problems with gold answers
        judge: LLMJudge instance (None = use heuristic)
        alignment_method: "dtw" or "index"

    Returns:
        List of diagnosed hyp_traces with is_correct and error_type filled in
    """
    # Build lookup by problem_id
    ref_by_id = {t["problem_id"]: t for t in ref_traces}
    prob_by_id = {p.get("problem_id", p.get("id", "")): p for p in problems}

    diagnosed = []
    n_correct = 0
    n_total = 0

    from tqdm import tqdm
    iterator = tqdm(hyp_traces, desc="Diagnosing") if verbose else hyp_traces

    for hyp_trace in iterator:
        pid = hyp_trace["problem_id"]
        ref_trace = ref_by_id.get(pid)
        prob = prob_by_id.get(pid, {})

        if ref_trace is None:
            print(f"  [WARN] No reference trace for {pid}, skipping")
            continue

        gold_answer = prob.get("gold_answer", prob.get("answer", ""))
        problem_text = prob.get("question", prob.get("problem", ""))

        result = diagnose_single_problem(
            problem_text=problem_text,
            gold_answer=gold_answer,
            ref_trace=ref_trace,
            hyp_trace=hyp_trace,
            judge=judge,
            alignment_method=alignment_method,
        )
        diagnosed.append(result)

        n_total += 1
        if result.get("is_correct_final"):
            n_correct += 1

    if verbose:
        if n_total > 0:
            print(f"\nDiagnosis complete: {n_correct}/{n_total} correct ({n_correct/n_total:.1%})")
        else:
            print("\nDiagnosis complete: no hypothesis traces matched a reference — check that "
                  "ref/hyp jsonls share problem_ids and filenames.")

    return diagnosed


# ============================================================
# CLI
# ============================================================

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Diagnose step-level errors in quantized reasoning traces")
    parser.add_argument("--ref", required=True, help="Directory with segmented FP16 traces")
    parser.add_argument("--hyp", required=True, help="Directory with segmented quantized traces")
    parser.add_argument("--problems", default=None, help="JSONL file with original problems + gold answers")
    parser.add_argument("--output", required=True, help="Output directory")
    parser.add_argument("--judge", default="none", choices=["openai", "anthropic", "none"],
                        help="LLM judge provider (none = heuristic only)")
    parser.add_argument("--judge-model", default="gpt-4o", help="Judge model name")
    parser.add_argument("--alignment", default="dtw", choices=["dtw", "index"])
    args = parser.parse_args()

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

    # Set up judge
    judge = None
    if args.judge != "none":
        judge = LLMJudge(provider=args.judge, model=args.judge_model)
        print(f"Using LLM judge: {args.judge}/{args.judge_model}")
    else:
        print("Using heuristic-based diagnosis (no API calls)")

    # Load traces. Pair ref/hyp by FILENAME, not by position — pairing by
    # position breaks when ref and hyp have different numbers of files (e.g.
    # ref holds {gsm8k, math500, gpqa}.jsonl but hyp only has math500.jsonl,
    # which would otherwise silently pair gsm8k-ref with math500-hyp).
    import glob
    ref_files = sorted(glob.glob(os.path.join(args.ref, "*.jsonl")))
    hyp_files = sorted(glob.glob(os.path.join(args.hyp, "*.jsonl")))
    ref_by_name = {os.path.basename(f): f for f in ref_files}

    for hyp_f in hyp_files:
        ref_f = ref_by_name.get(os.path.basename(hyp_f))
        if ref_f is None:
            print(f"  [SKIP] No matching reference for {os.path.basename(hyp_f)}")
            continue
        print(f"\nProcessing: {os.path.basename(ref_f)} vs {os.path.basename(hyp_f)}")

        ref_traces = load_jsonl(ref_f)
        hyp_traces = load_jsonl(hyp_f)

        # Load problems if provided, otherwise reconstruct from traces
        if args.problems:
            problems = load_jsonl(args.problems)
        else:
            problems = []
            for t in ref_traces:
                problems.append({
                    "problem_id": t["problem_id"],
                    "question": t.get("raw_output", "")[:200],
                    "gold_answer": t.get("final_answer", ""),
                })

        diagnosed = diagnose_batch(
            ref_traces=ref_traces,
            hyp_traces=hyp_traces,
            problems=problems,
            judge=judge,
            alignment_method=args.alignment,
        )

        out_path = os.path.join(args.output, os.path.basename(hyp_f))
        save_jsonl(diagnosed, out_path)
        print(f"  Saved {len(diagnosed)} diagnosed traces -> {out_path}")

    print("\nDiagnosis pipeline complete!")