File size: 5,530 Bytes
f91d9a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Monitoring step-identification task."""

from __future__ import annotations

from collections import Counter
from pathlib import Path
from typing import Any

from ..io import BENCHMARK_ROOT, DATA_DIR, manifest_examples, select_shard
from ..metrics import bootstrap_sem, classification_scores
from ..parsing import normalize_step_id, parse_monitoring_response
from .base import BenchmarkTask, TaskSpec


class MonitoringStepTask(BenchmarkTask):
    spec = TaskSpec(
        name="monitoring_step",
        display_name="Protocol Monitoring Step Prediction",
        default_manifest=DATA_DIR / "monitoring_step_eval.json",
    )
    primary_metric = "step_balanced_accuracy"

    def load_examples(
        self,
        *,
        benchmark_root: Path = BENCHMARK_ROOT,
        manifest_path: Path | None = None,
        video_root: Path | None = None,
        num_shards: int = 1,
        shard_index: int = 0,
        limit: int | None = None,
    ) -> list[dict[str, Any]]:
        rows = manifest_examples(manifest_path or self.default_manifest)
        root = video_root or benchmark_root
        for row in rows:
            row["task"] = self.name
            row["_video_abs"] = str(root / str(row["video_path"]))
        rows = sorted(rows, key=lambda row: str(row.get("eval_id")))
        if limit is not None:
            rows = rows[:limit]
        return select_shard(rows, num_shards, shard_index)

    def parse_record(self, row: dict[str, Any]) -> dict[str, Any]:
        if row.get("error"):
            return row
        raw = str(row.get("raw_response") or "")
        pred_candidate, pred_step = parse_monitoring_response(raw) if raw else (None, None)
        pred_step_normalized = normalize_step_id(pred_step)
        target_step_normalized = normalize_step_id(row.get("target_step_id"))
        row.update(
            {
                "pred_candidate_matches": pred_candidate,
                "pred_observed_step_id": pred_step,
                "pred_observed_step_id_normalized": pred_step_normalized,
                "target_step_id_normalized": target_step_normalized,
                "pred_parse_ok": pred_step_normalized is not None,
                "candidate_correct": (
                    pred_candidate is not None
                    and bool(pred_candidate) == bool(row.get("target_candidate_matches"))
                )
                if row.get("target_candidate_matches") is not None
                else None,
                "observed_step_correct": pred_step_normalized is not None
                and pred_step_normalized == target_step_normalized,
            }
        )
        return row

    def _summary(self, rows: list[dict[str, Any]]) -> dict[str, Any]:
        parsed = self.parse_rows(rows)
        scored = [row for row in parsed if not row.get("error")]
        step_rows = [row for row in scored if str(row.get("task_type") or "step_identification") == "step_identification"]
        pairs = [
            (normalize_step_id(row.get("target_step_id")), normalize_step_id(row.get("pred_observed_step_id")))
            for row in step_rows
            if normalize_step_id(row.get("target_step_id")) is not None
        ]
        labels = sorted({str(target) for target, _ in pairs})
        scores = classification_scores(pairs, labels=labels)
        candidate_rows = [row for row in scored if row.get("target_candidate_matches") is not None]
        candidate_correct = sum(1 for row in candidate_rows if row.get("candidate_correct"))
        parse_errors = sum(1 for row in scored if not row.get("pred_parse_ok"))
        return {
            "task": self.name,
            "display_name": self.display_name,
            "rows": len(rows),
            "scored": len(scored),
            "errors": sum(1 for row in rows if row.get("error")),
            "parse_errors": parse_errors,
            "parse_success_rate": (len(scored) - parse_errors) / len(scored) if scored else None,
            "candidate_match_rows": len(candidate_rows),
            "candidate_match_accuracy": candidate_correct / len(candidate_rows) if candidate_rows else None,
            "step_identification_rows": len(step_rows),
            "step_identification_accuracy": scores["accuracy"],
            "observed_step_id_accuracy": scores["accuracy"],
            "step_parse_success_rate": (len(step_rows) - parse_errors) / len(step_rows) if step_rows else None,
            "step_balanced_accuracy": scores["balanced_accuracy"],
            "step_macro_f1": scores["macro_f1"],
            "step_macro_precision": scores["macro_precision"],
            "step_macro_recall": scores["macro_recall"],
            "step_precision_by_id": scores["precision"],
            "step_recall_by_id": scores["recall"],
            "step_f1_by_id": scores["f1"],
            "step_confusion": scores["confusion"],
            "task_counts": dict(Counter(str(row.get("task_type")) for row in scored)),
            "target_counts": scores["target_counts"],
            "pred_counts": scores["pred_counts"],
        }

    def score(self, rows: list[dict[str, Any]]) -> dict[str, Any]:
        parsed = self.parse_rows(rows)
        summary = self._summary(parsed)
        for metric in (
            "step_identification_accuracy",
            "step_balanced_accuracy",
            "step_macro_f1",
            "step_macro_precision",
            "step_macro_recall",
        ):
            summary[f"{metric}_sem"] = bootstrap_sem(parsed, metric, self._summary, iterations=200)
        return summary