File size: 7,119 Bytes
1e59964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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}")