"""Finetune-style monitor-next delta 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_next_step_delta_response from .base import BenchmarkTask, TaskSpec class MonitorNextStepTask(BenchmarkTask): spec = TaskSpec( name="monitor_next_step", display_name="Protocol Monitoring Advance Prediction", default_manifest=DATA_DIR / "monitor_next_step.json", ) primary_metric = "advance_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 parsed = parse_next_step_delta_response(str(row.get("raw_response") or "")) pred_current_norm = normalize_step_id(parsed.get("pred_current_step_id")) target_current_norm = normalize_step_id(row.get("target_current_step_id")) target_start_norm = normalize_step_id(row.get("target_start_step_id")) pred_advances = None if pred_current_norm is not None and target_start_norm is not None: pred_advances = pred_current_norm != target_start_norm row.update( { **parsed, "pred_current_step_id_normalized": pred_current_norm, "target_current_step_id_normalized": target_current_norm, "pred_advances_step": pred_advances, "current_step_correct": pred_current_norm is not None and pred_current_norm == target_current_norm, } ) 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")] current_correct = 0 current_parsed = 0 advance_pairs: list[tuple[str, str | None]] = [] skipped_pairs: list[tuple[str, str | None]] = [] skipped_step_ref_correct = 0 skipped_step_ref_total = 0 for row in scored: pred_current = normalize_step_id(row.get("pred_current_step_id")) target_current = normalize_step_id(row.get("target_current_step_id")) target_start = normalize_step_id(row.get("target_start_step_id")) if pred_current is not None: current_parsed += 1 current_correct += int(pred_current is not None and pred_current == target_current) pred_advances = None if pred_current is not None and target_start is not None: pred_advances = pred_current != target_start advance_pairs.append((str(bool(row.get("target_advances_step"))), None if pred_advances is None else str(bool(pred_advances)))) skipped_pred = row.get("pred_has_step_skipped") skipped_pairs.append((str(bool(row.get("target_has_error"))), None if skipped_pred is None else str(bool(skipped_pred)))) if row.get("target_has_error"): skipped_step_ref_total += 1 pred_ref = normalize_step_id(row.get("pred_error_step_id")) target_ref = normalize_step_id(row.get("target_error_step_id")) skipped_step_ref_correct += int(pred_ref is not None and pred_ref == target_ref) advance = classification_scores(advance_pairs, labels=["False", "True"]) skipped = classification_scores(skipped_pairs, labels=["False", "True"]) n = len(scored) 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": n, "errors": sum(1 for row in rows if row.get("error")), "parse_errors": parse_errors, "parse_success_rate": (n - parse_errors) / n if n else None, "current_step_accuracy": current_correct / n if n else None, "current_step_accuracy_parsed_only": current_correct / current_parsed if current_parsed else None, "advance_step_accuracy": advance["accuracy"], "advance_step_balanced_accuracy": advance["balanced_accuracy"], "advance_step_macro_f1": advance["macro_f1"], "advance_step_macro_precision": advance["macro_precision"], "advance_step_macro_recall": advance["macro_recall"], "advance_step_precision": advance["precision"], "advance_step_recall": advance["recall"], "advance_step_f1": advance["f1"], "advance_step_confusion": advance["confusion"], "skipped_step_accuracy": skipped["accuracy"], "skipped_step_balanced_accuracy": skipped["balanced_accuracy"], "skipped_step_macro_f1": skipped["macro_f1"], "skipped_step_macro_precision": skipped["macro_precision"], "skipped_step_macro_recall": skipped["macro_recall"], "skipped_step_confusion": skipped["confusion"], "skipped_step_ref_accuracy": skipped_step_ref_correct / skipped_step_ref_total if skipped_step_ref_total else None, "task_counts": dict(Counter(str(row.get("task_type")) for row in scored)), "history_variant_counts": dict(Counter(str(row.get("history_variant")) for row in scored)), "window_kind_counts": dict(Counter(str(row.get("window_kind")) 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 ( "advance_step_accuracy", "advance_step_balanced_accuracy", "advance_step_macro_f1", "advance_step_macro_precision", "advance_step_macro_recall", "skipped_step_accuracy", "skipped_step_balanced_accuracy", "skipped_step_macro_f1", ): summary[f"{metric}_sem"] = bootstrap_sem(parsed, metric, self._summary, iterations=200) return summary