File size: 7,500 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
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
"""Pipette mistake / error detection task."""

from __future__ import annotations

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

from ..io import BENCHMARK_ROOT, read_parquet, select_shard
from ..metrics import bootstrap_sem, classification_scores
from ..parsing import parse_choice_option
from .base import BenchmarkTask, TaskSpec


PMD_OPTIONS = {
    "CORRECT",
    "ERROR_REUSE",
    "ERROR_SURFACE",
    "ERROR_RELEASE",
    "ERROR_INSTALL",
    "ERROR_OTHER",
}
PMD_MISTAKE_TO_OPTION = {
    "none": "CORRECT",
    "reuse_tip": "ERROR_REUSE",
    "reuse_same_media": "ERROR_REUSE",
    "reuse_same_tip": "ERROR_REUSE",
    "surface_contamination": "ERROR_SURFACE",
    "early_release": "ERROR_RELEASE",
    "wrong_tip_for_pipette": "ERROR_INSTALL",
}
PMD_NUMBER_TO_OPTION = {
    "1": "CORRECT",
    "2": "ERROR_REUSE",
    "3": "ERROR_SURFACE",
    "4": "ERROR_RELEASE",
    "5": "ERROR_INSTALL",
    "6": "ERROR_OTHER",
}


def pmd_target_option(label: str, mistake_type: str) -> str:
    return "CORRECT" if label == "correct" else PMD_MISTAKE_TO_OPTION.get(mistake_type, "ERROR_OTHER")


class PmdTask(BenchmarkTask):
    spec = TaskSpec(
        name="pmd",
        display_name="Error Detection",
        default_manifest=BENCHMARK_ROOT / "pmd" / "pmd.parquet",
        sort_key="video_id",
    )
    primary_metric = "binary_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 = read_parquet(manifest_path or self.default_manifest)
        selected: list[dict[str, Any]] = []
        root = video_root or benchmark_root
        for row in rows:
            rel_video = str(row.get("video_path") or "")
            if not rel_video:
                continue
            video_path = root / rel_video
            target = pmd_target_option(str(row.get("label")), str(row.get("mistake_type")))
            selected.append(
                {
                    **row,
                    "task": self.name,
                    "_video_abs": str(video_path),
                    "target_option": target,
                    "target_binary": "CORRECT" if target == "CORRECT" else "ERROR",
                }
            )
        selected = sorted(selected, key=lambda row: str(row.get("video_id") or ""))
        if limit is not None:
            selected = selected[:limit]
        return select_shard(selected, num_shards, shard_index)

    def parse_record(self, row: dict[str, Any]) -> dict[str, Any]:
        if row.get("error"):
            return row
        pred = parse_choice_option(str(row.get("raw_response") or ""), PMD_OPTIONS, number_map=PMD_NUMBER_TO_OPTION)
        pred_binary = None if pred is None else ("CORRECT" if pred == "CORRECT" else "ERROR")
        target = str(row.get("target_option") or pmd_target_option(str(row.get("label")), str(row.get("mistake_type"))))
        target_binary = "CORRECT" if target == "CORRECT" else "ERROR"
        row.update(
            {
                "target_option": target,
                "target_binary": target_binary,
                "pred_option": pred,
                "pred_binary": pred_binary,
                "pred_parse_ok": pred is not None,
                "binary_correct": pred_binary == target_binary if pred_binary is not None else False,
                "option_correct": pred == target if pred is not None else False,
            }
        )
        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")]
        binary_pairs: list[tuple[str, str | None]] = []
        option_pairs: list[tuple[str, str | None]] = []
        error_type_pairs: list[tuple[str, str | None]] = []
        for row in scored:
            target = str(row.get("target_option"))
            pred = row.get("pred_option")
            target_binary = "CORRECT" if target == "CORRECT" else "ERROR"
            pred_binary = None if pred is None else ("CORRECT" if pred == "CORRECT" else "ERROR")
            binary_pairs.append((target_binary, pred_binary))
            option_pairs.append((target, None if pred is None else str(pred)))
            if target != "CORRECT":
                error_type_pairs.append((target, None if pred in (None, "CORRECT") else str(pred)))
        binary = classification_scores(binary_pairs, labels=["CORRECT", "ERROR"])
        option = classification_scores(option_pairs, labels=sorted(PMD_OPTIONS))
        error_type = classification_scores(
            error_type_pairs,
            labels=sorted(option for option in PMD_OPTIONS if option != "CORRECT"),
        )
        parse_errors = sum(1 for row in scored if row.get("pred_option") is None)
        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,
            "binary_accuracy": binary["accuracy"],
            "binary_balanced_accuracy": binary["balanced_accuracy"],
            "binary_macro_f1": binary["macro_f1"],
            "binary_macro_precision": binary["macro_precision"],
            "binary_macro_recall": binary["macro_recall"],
            "binary_precision": binary["precision"],
            "binary_recall": binary["recall"],
            "binary_f1": binary["f1"],
            "binary_confusion": binary["confusion"],
            "option_accuracy": option["accuracy"],
            "option_balanced_accuracy": option["balanced_accuracy"],
            "option_macro_f1": option["macro_f1"],
            "option_confusion": option["confusion"],
            "error_type_accuracy": error_type["accuracy"],
            "error_type_balanced_accuracy": error_type["balanced_accuracy"],
            "error_type_macro_f1": error_type["macro_f1"],
            "error_type_macro_precision": error_type["macro_precision"],
            "error_type_macro_recall": error_type["macro_recall"],
            "error_type_precision": error_type["precision"],
            "error_type_recall": error_type["recall"],
            "error_type_f1": error_type["f1"],
            "error_type_confusion": error_type["confusion"],
            "target_counts": dict(Counter(str(row.get("target_option")) for row in scored)),
            "pred_counts": dict(Counter(str(row.get("pred_option")) for row in scored)),
        }

    def score(self, rows: list[dict[str, Any]]) -> dict[str, Any]:
        parsed = self.parse_rows(rows)
        summary = self._summary(parsed)
        for metric in (
            "binary_accuracy",
            "binary_balanced_accuracy",
            "binary_macro_f1",
            "binary_macro_precision",
            "binary_macro_recall",
            "error_type_accuracy",
            "error_type_balanced_accuracy",
            "error_type_macro_f1",
            "error_type_macro_precision",
            "error_type_macro_recall",
        ):
            summary[f"{metric}_sem"] = bootstrap_sem(parsed, metric, self._summary, iterations=200)
        return summary