| """ |
| 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 |
|
|
|
|
| |
| |
| |
|
|
| 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:""" |
|
|
|
|
| |
| |
| |
|
|
| 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" |
|
|
|
|
| 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)) |
| |
| novel_nums = hyp_nums - ref_nums |
| |
| 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() |
|
|
| |
| 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" |
|
|
| |
| 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" |
|
|
| |
| logic_words = ["therefore", "because", "since", "implies", "hence", "thus"] |
| if any(w in hyp_lower for w in logic_words): |
| return "logical" |
|
|
| return "conceptual" |
|
|
|
|
| |
| |
| |
|
|
| 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", []) |
|
|
| |
| hyp_answer = hyp_trace.get("final_answer", "") |
| is_correct_final = check_answer(hyp_answer, gold_answer) |
|
|
| |
| 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 |
|
|
| |
| hyp_trace["is_correct_final"] = False |
|
|
| |
| alignments = align_steps(ref_steps, hyp_steps, method=alignment_method) |
|
|
| |
| ref_context = "\n".join(s["text"] for s in ref_steps) |
|
|
| |
| found_first_error = False |
| for alignment in alignments: |
| if alignment.hyp_index is None: |
| continue |
|
|
| 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: |
| |
| hyp_step_dict["is_correct"] = True |
| hyp_step_dict["error_type"] = None |
| elif judge is not None: |
| |
| 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: |
| |
| if alignment.similarity > 0.6: |
| hyp_step_dict["is_correct"] = True |
| hyp_step_dict["error_type"] = None |
| else: |
| hyp_step_dict["is_correct"] = False |
| |
| 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 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 |
| """ |
| |
| 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 |
|
|
|
|
| |
| |
| |
|
|
| 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) |
|
|
| |
| 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)") |
|
|
| |
| |
| |
| |
| 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) |
|
|
| |
| 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!") |
|
|