| """ |
| StepProbe: CoT Step Segmentation |
| |
| Parses a reasoning model's chain-of-thought output into discrete steps. |
| Handles both explicit markers (numbered steps, reflection cues) and |
| implicit boundaries via an LLM-based fallback segmenter. |
| """ |
|
|
| import re |
| import json |
| from dataclasses import dataclass, field, asdict |
| from typing import List, Optional |
|
|
|
|
| @dataclass |
| class ReasoningStep: |
| """A single step in a chain-of-thought trace.""" |
| index: int |
| text: str |
| step_type: str = "reasoning" |
| is_correct: Optional[bool] = None |
| error_type: Optional[str] = None |
|
|
|
|
| @dataclass |
| class SegmentedCoT: |
| """A full CoT trace parsed into steps.""" |
| problem_id: str |
| model: str |
| quantization: str |
| raw_output: str |
| final_answer: str |
| steps: List[ReasoningStep] = field(default_factory=list) |
| |
| def to_dict(self): |
| d = asdict(self) |
| return d |
| |
| @classmethod |
| def from_dict(cls, d): |
| steps = [ReasoningStep(**s) for s in d.pop("steps", [])] |
| return cls(**d, steps=steps) |
|
|
|
|
| |
| |
| |
|
|
| |
| DEEPSEEK_PATTERNS = [ |
| r"(?:^|\n)\s*(?:Step\s+\d+[:.)])", |
| r"(?:^|\n)\s*(?:\d+[.)]\s)", |
| r"(?:^|\n)\s*(?:First|Second|Third|Next|Then|Finally|Now)[,:]", |
| r"(?:^|\n)\s*(?:Let me|Let's|I need to|I should|I'll)", |
| r"(?:^|\n)\s*(?:Wait|Hmm|Actually|Oh|But wait)", |
| r"(?:^|\n)\s*(?:So |Therefore |Thus |Hence )", |
| r"(?:^|\n)\s*(?:To verify|Let me check|Double.?check)", |
| ] |
|
|
| |
| STEP_TYPE_PATTERNS = { |
| "reflection": [ |
| r"(?:Wait|Hmm|Actually|Oh|But wait|I made|mistake|error|reconsider|wrong)", |
| ], |
| "verification": [ |
| r"(?:verify|check|double.?check|confirm|validate|makes sense|correct\?)", |
| ], |
| "conclusion": [ |
| r"(?:therefore|thus|hence|so the answer|final answer|in conclusion|the result)", |
| r"(?:boxed\{|\\boxed|answer is|= \d+$)", |
| ], |
| } |
|
|
|
|
| def classify_step_type(text: str) -> str: |
| """Classify a step as reasoning, reflection, verification, or conclusion.""" |
| text_lower = text.lower().strip() |
| for stype, patterns in STEP_TYPE_PATTERNS.items(): |
| for pat in patterns: |
| if re.search(pat, text_lower, re.IGNORECASE): |
| return stype |
| return "reasoning" |
|
|
|
|
| def segment_cot_rule_based(raw_output: str) -> List[str]: |
| """ |
| Segment a CoT trace into steps using rule-based patterns. |
| Returns a list of step strings. |
| """ |
| |
| combined = "|".join(f"({p})" for p in DEEPSEEK_PATTERNS) |
| |
| |
| splits = [] |
| for match in re.finditer(combined, raw_output): |
| splits.append(match.start()) |
| |
| if not splits: |
| |
| parts = re.split(r"\n\s*\n", raw_output) |
| return [p.strip() for p in parts if p.strip()] |
| |
| |
| segments = [] |
| for i, start in enumerate(splits): |
| end = splits[i + 1] if i + 1 < len(splits) else len(raw_output) |
| segment = raw_output[start:end].strip() |
| if segment: |
| segments.append(segment) |
| |
| |
| if splits[0] > 0: |
| preamble = raw_output[:splits[0]].strip() |
| if preamble: |
| segments.insert(0, preamble) |
| |
| return segments |
|
|
|
|
| def extract_final_answer(raw_output: str) -> str: |
| """Extract the final answer from a CoT trace.""" |
| |
| boxed_match = re.search(r"\\boxed\{([^}]+)\}", raw_output) |
| if boxed_match: |
| return boxed_match.group(1).strip() |
| |
| |
| answer_match = re.search( |
| r"(?:the\s+)?(?:final\s+)?answer\s+is[:\s]+(.+?)(?:\.|$)", |
| raw_output, re.IGNORECASE |
| ) |
| if answer_match: |
| return answer_match.group(1).strip() |
| |
| |
| numbers = re.findall(r"-?\d+\.?\d*", raw_output) |
| if numbers: |
| return numbers[-1] |
| |
| return "" |
|
|
|
|
| def segment_cot( |
| problem_id: str, |
| raw_output: str, |
| model: str = "", |
| quantization: str = "fp16", |
| ) -> SegmentedCoT: |
| """ |
| Main segmentation function. |
| |
| Args: |
| problem_id: Unique identifier for the problem |
| raw_output: Raw CoT text from the model |
| model: Model name |
| quantization: Quantization method string |
| |
| Returns: |
| SegmentedCoT with parsed steps |
| """ |
| |
| step_texts = segment_cot_rule_based(raw_output) |
| |
| |
| steps = [] |
| for i, text in enumerate(step_texts): |
| step = ReasoningStep( |
| index=i, |
| text=text, |
| step_type=classify_step_type(text), |
| ) |
| steps.append(step) |
| |
| |
| final_answer = extract_final_answer(raw_output) |
| |
| return SegmentedCoT( |
| problem_id=problem_id, |
| model=model, |
| quantization=quantization, |
| raw_output=raw_output, |
| final_answer=final_answer, |
| steps=steps, |
| ) |
|
|
|
|
| |
| |
| |
|
|
| if __name__ == "__main__": |
| import argparse |
| import glob |
| |
| parser = argparse.ArgumentParser(description="Segment CoT traces into steps") |
| parser.add_argument("--input", required=True, help="Directory with inference outputs (jsonl)") |
| parser.add_argument("--output", required=True, help="Output directory for segmented steps") |
| parser.add_argument("--model", default="", help="Model name tag") |
| parser.add_argument("--quant", default="fp16", help="Quantization tag") |
| args = parser.parse_args() |
| |
| import os |
| os.makedirs(args.output, exist_ok=True) |
| |
| |
| for fpath in glob.glob(os.path.join(args.input, "*.jsonl")): |
| basename = os.path.basename(fpath) |
| out_path = os.path.join(args.output, basename) |
| |
| results = [] |
| with open(fpath) as f: |
| for line in f: |
| record = json.loads(line) |
| seg = segment_cot( |
| problem_id=record.get("problem_id", record.get("id", "")), |
| raw_output=record.get("output", record.get("response", "")), |
| model=args.model, |
| quantization=args.quant, |
| ) |
| results.append(seg.to_dict()) |
| |
| with open(out_path, "w") as f: |
| for r in results: |
| f.write(json.dumps(r, ensure_ascii=False) + "\n") |
| |
| print(f"Segmented {len(results)} traces -> {out_path}") |
|
|