File size: 11,185 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
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
"""
StepProbe Metrics: Novel step-level evaluation metrics for compressed reasoning models.

Key metrics:
    - FFS (First Failure Step): Where does reasoning first break?
    - ECR (Error Cascade Rate): How badly does one error propagate?
    - SSR (Step Survival Rate): At each step depth, what fraction of runs are still correct?
    - Error Type Distribution: Which error types dominate at each bit-width?
"""

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

import numpy as np


@dataclass
class StepProbeResults:
    """Aggregated results for a single model x quantization setting."""
    model: str
    quantization: str
    n_problems: int
    accuracy: float              # standard pass@1
    avg_token_count: float       # avg reasoning tokens
    
    # Step-level metrics (our contribution)
    avg_ffs: float               # average First Failure Step
    median_ffs: float            # median First Failure Step
    ffs_std: float               # std of FFS
    ecr: float                   # Error Cascade Rate
    ssr_curve: List[float]       # Step Survival Rate at each depth
    error_type_dist: Dict[str, float]  # {conceptual: 0.15, methodological: 0.25, ...}
    
    # Comparison to full-precision
    accuracy_delta: float        # accuracy - fp16_accuracy
    ffs_delta: float             # avg_ffs - fp16_avg_ffs


def compute_first_failure_step(steps: List[dict]) -> Optional[int]:
    """
    Compute the First Failure Step (FFS) for a single problem.
    
    FFS is the index of the earliest step where is_correct == False.
    Returns None if all steps are correct (no failure).
    """
    for step in steps:
        if step.get("is_correct") == False:
            return step["index"]
    return None  # all correct


def compute_error_cascade_rate(steps: List[dict]) -> Optional[float]:
    """
    Compute the Error Cascade Rate (ECR) for a single problem.

    Given the first failure at step k, ECR = (# incorrect steps after k) / (# total steps after k).
    Returns None when ECR is undefined (no failure, or failure is the last
    step so there are no subsequent steps to score). The aggregate caller
    must filter on `is not None` rather than `> 0`, otherwise traces whose
    failures genuinely did not cascade (ECR == 0.0) are silently excluded
    from the cell-level mean and bias it upward (matches the
    cascade_rate / bootstrap convention in scripts/compute_ci.py).
    """
    ffs = compute_first_failure_step(steps)
    if ffs is None:
        return None

    steps_after_failure = [s for s in steps if s["index"] > ffs]
    if not steps_after_failure:
        return None

    n_incorrect_after = sum(1 for s in steps_after_failure if s.get("is_correct") == False)
    return n_incorrect_after / len(steps_after_failure)


def compute_step_survival_rate(all_steps: List[List[dict]], max_depth: int = 30) -> List[float]:
    """
    Compute the Step Survival Rate (SSR) curve across all problems.
    
    SSR[i] = fraction of problems where the quantized model is still correct at step i.
    This creates a "survival curve" showing how reasoning quality degrades with depth.
    
    Args:
        all_steps: List of step-lists, one per problem
        max_depth: Maximum step depth to compute
        
    Returns:
        List of SSR values, one per step depth [0, 1, 2, ..., max_depth-1]
    """
    ssr = []
    for depth in range(max_depth):
        n_alive = 0
        n_applicable = 0
        
        for steps in all_steps:
            # Only count problems that have at least (depth+1) steps
            if len(steps) > depth:
                n_applicable += 1
                # "Alive" means all steps up to and including this depth are correct
                all_correct_so_far = all(
                    s.get("is_correct", True) 
                    for s in steps[:depth + 1]
                )
                if all_correct_so_far:
                    n_alive += 1
        
        ssr.append(n_alive / n_applicable if n_applicable > 0 else 0.0)
    
    return ssr


def compute_error_type_distribution(all_steps: List[List[dict]]) -> Dict[str, float]:
    """
    Compute the distribution of error types across all incorrect steps.
    
    Returns:
        Dict mapping error_type -> fraction (sums to 1.0)
    """
    counts = defaultdict(int)
    total = 0
    
    for steps in all_steps:
        for step in steps:
            if step.get("is_correct") == False and step.get("error_type"):
                counts[step["error_type"]] += 1
                total += 1
    
    if total == 0:
        return {}
    
    return {k: v / total for k, v in sorted(counts.items())}


def aggregate_metrics(
    diagnosed_traces: List[dict],
    fp16_accuracy: float = None,
    fp16_avg_ffs: float = None,
) -> StepProbeResults:
    """
    Aggregate step-level metrics across all problems for a model x quantization setting.
    
    Args:
        diagnosed_traces: List of SegmentedCoT dicts (with is_correct and error_type filled in)
        fp16_accuracy: Full-precision accuracy for computing delta
        fp16_avg_ffs: Full-precision average FFS for computing delta
        
    Returns:
        StepProbeResults with all metrics computed
    """
    n_problems = len(diagnosed_traces)
    if n_problems == 0:
        raise ValueError("No traces to aggregate")
    
    model = diagnosed_traces[0].get("model", "unknown")
    quant = diagnosed_traces[0].get("quantization", "unknown")
    
    # Standard accuracy
    n_correct = sum(1 for t in diagnosed_traces if t.get("is_correct_final", False))
    accuracy = n_correct / n_problems
    
    # Token counts
    token_counts = [len(t.get("raw_output", "").split()) for t in diagnosed_traces]
    avg_tokens = np.mean(token_counts) if token_counts else 0
    
    # Step-level metrics
    all_steps = [t.get("steps", []) for t in diagnosed_traces]
    
    # FFS
    ffs_values = []
    for steps in all_steps:
        ffs = compute_first_failure_step(steps)
        if ffs is not None:
            ffs_values.append(ffs)
    
    avg_ffs = np.mean(ffs_values) if ffs_values else float("inf")
    median_ffs = np.median(ffs_values) if ffs_values else float("inf")
    ffs_std = np.std(ffs_values) if ffs_values else 0.0
    
    # ECR — average over traces with at least one failure AND at least one
    # post-failure step. Filter on `is not None` (not `> 0`); a trace that
    # failed but did not cascade has ecr=0.0 and must stay in the mean.
    ecr_values = [compute_error_cascade_rate(steps) for steps in all_steps]
    ecr_values = [e for e in ecr_values if e is not None]
    avg_ecr = float(np.mean(ecr_values)) if ecr_values else 0.0
    
    # SSR
    ssr_curve = compute_step_survival_rate(all_steps)
    
    # Error type distribution
    error_dist = compute_error_type_distribution(all_steps)
    
    # Deltas
    acc_delta = (accuracy - fp16_accuracy) if fp16_accuracy is not None else 0.0
    ffs_delta = (avg_ffs - fp16_avg_ffs) if fp16_avg_ffs is not None else 0.0
    
    return StepProbeResults(
        model=model,
        quantization=quant,
        n_problems=n_problems,
        accuracy=accuracy,
        avg_token_count=avg_tokens,
        avg_ffs=avg_ffs,
        median_ffs=median_ffs,
        ffs_std=ffs_std,
        ecr=avg_ecr,
        ssr_curve=ssr_curve,
        error_type_dist=error_dist,
        accuracy_delta=acc_delta,
        ffs_delta=ffs_delta,
    )


def format_results_table(results: List[StepProbeResults]) -> str:
    """Format multiple results into a readable comparison table."""
    header = f"{'Model':<35} {'Quant':<12} {'Acc':<8} {'Δ Acc':<8} {'Avg FFS':<10} {'ECR':<8} {'Errors'}"
    lines = [header, "-" * len(header)]
    
    for r in results:
        error_str = ", ".join(f"{k}:{v:.0%}" for k, v in r.error_type_dist.items())
        lines.append(
            f"{r.model:<35} {r.quantization:<12} {r.accuracy:<8.1%} "
            f"{r.accuracy_delta:<+8.1%} {r.avg_ffs:<10.1f} {r.ecr:<8.1%} {error_str}"
        )
    
    return "\n".join(lines)


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

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="Compute StepProbe metrics")
    parser.add_argument("--diagnosis", required=True, help="Directory with diagnosed traces")
    parser.add_argument("--output", required=True, help="Output directory for metrics")
    parser.add_argument("--fp16-accuracy", type=float, help="FP16 baseline accuracy")
    parser.add_argument("--fp16-ffs", type=float, help="FP16 baseline avg FFS")
    # --model and --quant tag the output filename so that metrics for different
    # (model, quant) combinations don't clobber each other. Without these, every
    # invocation produced files named "<benchmark>_run0_metrics.json" and the
    # last one written wins — which is why only one model appeared in figures.
    parser.add_argument("--model", default=None, help="Model tag to embed in the output filename and JSON")
    parser.add_argument("--quant", default=None, help="Quant tag to embed in the output filename and JSON")
    args = parser.parse_args()

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

    # Load diagnosed traces
    import glob
    all_results = []

    for fpath in sorted(glob.glob(os.path.join(args.diagnosis, "*.jsonl"))):
        traces = []
        with open(fpath) as f:
            for line in f:
                traces.append(json.loads(line))

        if not traces:
            continue

        result = aggregate_metrics(
            traces,
            fp16_accuracy=args.fp16_accuracy,
            fp16_avg_ffs=args.fp16_ffs,
        )
        # CLI tags override whatever the traces carried (traces often have an
        # empty "model" field or the local adapter path rather than a tag).
        if args.model:
            result.model = args.model
        if args.quant:
            result.quantization = args.quant
        all_results.append(result)

        # Save individual result. Filename includes model + quant so writes
        # for different configs don't overwrite each other.
        basename = os.path.splitext(os.path.basename(fpath))[0]
        name_parts = [p for p in (args.model, args.quant, basename) if p]
        out_path = os.path.join(args.output, "_".join(name_parts) + "_metrics.json")
        with open(out_path, "w") as f:
            json.dump({
                "model": result.model,
                "quantization": result.quantization,
                "accuracy": result.accuracy,
                "accuracy_delta": result.accuracy_delta,
                "avg_ffs": result.avg_ffs,
                "median_ffs": result.median_ffs,
                "ecr": result.ecr,
                "ssr_curve": result.ssr_curve,
                "error_type_dist": result.error_type_dist,
            }, f, indent=2)
    
    # Print comparison table
    if all_results:
        print(format_results_table(all_results))
    
    print(f"\nMetrics saved to {args.output}")