StepProbe / stepprobe /segment.py
Akiyue's picture
Add files using upload-large-folder tool
1e59964 verified
Raw
History Blame Contribute Delete
7.12 kB
"""
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" # reasoning | reflection | verification | conclusion
is_correct: Optional[bool] = None # filled in by diagnosis
error_type: Optional[str] = None # conceptual | methodological | executional | logical
@dataclass
class SegmentedCoT:
"""A full CoT trace parsed into steps."""
problem_id: str
model: str
quantization: str # "fp16" | "awq_w4" | "gptq_w4" | etc.
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)
# ============================================================
# Rule-based segmentation patterns for reasoning models
# ============================================================
# DeepSeek-R1 patterns
DEEPSEEK_PATTERNS = [
r"(?:^|\n)\s*(?:Step\s+\d+[:.)])", # "Step 1:"
r"(?:^|\n)\s*(?:\d+[.)]\s)", # "1. " or "1) "
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)", # Reflection cues
r"(?:^|\n)\s*(?:So |Therefore |Thus |Hence )", # Conclusion cues
r"(?:^|\n)\s*(?:To verify|Let me check|Double.?check)", # Verification
]
# Classify step type based on content
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.
"""
# Combine all patterns
combined = "|".join(f"({p})" for p in DEEPSEEK_PATTERNS)
# Find all split points
splits = []
for match in re.finditer(combined, raw_output):
splits.append(match.start())
if not splits:
# No explicit markers found; split by double newline
parts = re.split(r"\n\s*\n", raw_output)
return [p.strip() for p in parts if p.strip()]
# Build segments
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)
# Prepend any text before the first marker
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."""
# Try LaTeX boxed format first
boxed_match = re.search(r"\\boxed\{([^}]+)\}", raw_output)
if boxed_match:
return boxed_match.group(1).strip()
# Try "The answer is X" pattern
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()
# Last number in the output as fallback
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
"""
# Segment
step_texts = segment_cot_rule_based(raw_output)
# Build step objects
steps = []
for i, text in enumerate(step_texts):
step = ReasoningStep(
index=i,
text=text,
step_type=classify_step_type(text),
)
steps.append(step)
# Extract answer
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,
)
# ============================================================
# CLI
# ============================================================
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)
# Process all jsonl files
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}")