WGO Deploy Bot commited on
Commit
d37698e
·
1 Parent(s): 1b89beb

release wgo-bench localization given labels

Browse files
README.md ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-sa-4.0
3
+ task_categories:
4
+ - video-classification
5
+ - other
6
+ pretty_name: WGO-Bench Localization Given Labels
7
+ tags:
8
+ - robotics
9
+ - temporal-localization
10
+ - video
11
+ - wgo-bench
12
+ size_categories:
13
+ - n<1K
14
+ ---
15
+
16
+ # WGO-Bench — Localization Given Labels
17
+
18
+ Self-contained eval for **localization given labels**: the model is given the gold event labels (shuffled, with multiplicity) and must return one time interval per occurrence. Videos and gold intervals are embedded in each row.
19
+
20
+ Derived from [Macrodata Labs' WGO-Bench](https://huggingface.co/datasets/macrodata/WGO-Bench) ([blog](https://macrodata.co/blog/annotating-robot-video-subtasks)). License: **CC-BY-NC-SA-4.0**. Keep downstream use consistent with Macrodata's attribution and non-commercial / share-alike terms.
21
+
22
+ ## Splits
23
+
24
+ | Split | Source ids | Episodes | Gold events |
25
+ |-------|------------|----------|-------------|
26
+ | `train` | `dev_80` | 80 | 623 |
27
+ | `test` | `heldout_20` | 20 | 120 |
28
+
29
+ Construction seed is frozen at **0**. Shuffled `label_specs` and `prompt_text` are materialized per row so order is byte-stable without re-running the RNG. Split id lists are also under `splits/`.
30
+
31
+ **Challenge leakage rule:** train localization models only on `train`. Score free-mode segmentation F1@0.75 on the untouched `test` episodes (or an external set). Do not train on `test`.
32
+
33
+ ## Schema
34
+
35
+ Each row is one episode:
36
+
37
+ | Field | Type | Description |
38
+ |-------|------|-------------|
39
+ | `id` | string | Episode id |
40
+ | `family` | string | `homer` / `droid` / `galaxea` |
41
+ | `instruction` | string | High-level episode instruction |
42
+ | `split` | string | `train` or `test` |
43
+ | `video` | binary | MP4 bytes |
44
+ | `label_specs` | list | `{label, multiplicity}` in **prompt order** (post-shuffle) |
45
+ | `gold_segments` | list | `{start_sec, end_sec, label}` in gold order |
46
+ | `prompt_text` | string | Exact localization prompt |
47
+ | `construction` | struct | `{seed, protocol, source}` |
48
+
49
+ ## Prediction format
50
+
51
+ ```json
52
+ {
53
+ "id": "galaxea_002",
54
+ "labels": [
55
+ {
56
+ "label": "pick up the pink stick",
57
+ "intervals": [
58
+ {"label_echo": "pick up the pink stick", "start_sec": 1.2, "end_sec": 3.4}
59
+ ]
60
+ }
61
+ ]
62
+ }
63
+ ```
64
+
65
+ Return exactly `multiplicity` intervals per listed label. Echo the exact label string in `label_echo`.
66
+
67
+ ## Scoring
68
+
69
+ Official metrics for this task (no gold-aware snapping):
70
+
71
+ - **Bound mean IoU** — mean per-gold-event IoU after exact cross-label binding and within-duplicate optimal 1:1 assignment
72
+ - **accuracy@0.5** / **accuracy@0.75** — fraction of gold events with IoU ≥ threshold
73
+
74
+ Shipped code (this repo):
75
+
76
+ ```text
77
+ localization/construct.py # rebuild specs + prompt from gold
78
+ localization/score.py # interval IoU, assignment, score_episode, summarize
79
+ localization/verify.py # assert parquet specs/prompts match construct()
80
+ scripts/score_predictions.py
81
+ ```
82
+
83
+ ```bash
84
+ # from the dataset root (after cloning or downloading the repo files)
85
+ python scripts/score_predictions.py \
86
+ --data data/train.parquet \
87
+ --preds my_preds.jsonl
88
+ ```
89
+
90
+ Or with 🤗 Datasets:
91
+
92
+ ```python
93
+ from datasets import load_dataset
94
+ ds = load_dataset("Nano1337/wgo-bench-localization")
95
+ row = ds["train"][0]
96
+ print(row["id"], row["label_specs"][:2])
97
+ # row["video"] is raw MP4 bytes
98
+ ```
99
+
100
+ ## Reproduce construction
101
+
102
+ ```python
103
+ from localization.construct import label_specs_from_segments, localization_prompt
104
+ from localization.schema import GoldSegment
105
+ from localization.verify import verify_row
106
+
107
+ gold = [GoldSegment(**s) for s in row["gold_segments"]]
108
+ specs = label_specs_from_segments(row["id"], gold, seed=0)
109
+ assert [s.to_dict() for s in specs] == list(row["label_specs"])
110
+ assert localization_prompt(row["instruction"], specs) == row["prompt_text"]
111
+ verify_row(row)
112
+ ```
113
+
114
+ ## Attribution
115
+
116
+ Videos and gold annotations: Macrodata Labs' [WGO-Bench](https://huggingface.co/datasets/macrodata/WGO-Bench), CC-BY-NC-SA-4.0.
117
+ This repository adds the localization-given-labels protocol (frozen shuffled label lists, prompts, splits, and scorer). Model predictions are not included.
data/test.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f7c9022045a1c7e4d9d13d54e6fbf71485939740bb8e734edde13fcdc9310db9
3
+ size 299264120
data/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8bdd96bb794ae8620848b4bf9c74d60f379524cdc059e02f4dcb5784ef1a585
3
+ size 1099170615
localization/__init__.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal localization-given-labels construction and scoring package."""
2
+
3
+ from localization.construct import (
4
+ DEFAULT_SEED,
5
+ PROTOCOL_NAME,
6
+ SOURCE_DATASET,
7
+ construction_meta,
8
+ label_specs_from_segments,
9
+ localization_prompt,
10
+ multiplicity_phrase,
11
+ )
12
+ from localization.schema import (
13
+ GoldSegment,
14
+ LabelPrediction,
15
+ LabelSpec,
16
+ PredictedInterval,
17
+ PredictionResult,
18
+ )
19
+ from localization.score import (
20
+ interval_iou,
21
+ metrics_from_rows,
22
+ optimal_group_assignment,
23
+ score_episode,
24
+ summarize_event_rows,
25
+ )
26
+ from localization.verify import verify_row, verify_rows
27
+
28
+ __all__ = [
29
+ "DEFAULT_SEED",
30
+ "PROTOCOL_NAME",
31
+ "SOURCE_DATASET",
32
+ "GoldSegment",
33
+ "LabelPrediction",
34
+ "LabelSpec",
35
+ "PredictedInterval",
36
+ "PredictionResult",
37
+ "construction_meta",
38
+ "interval_iou",
39
+ "label_specs_from_segments",
40
+ "localization_prompt",
41
+ "metrics_from_rows",
42
+ "multiplicity_phrase",
43
+ "optimal_group_assignment",
44
+ "score_episode",
45
+ "summarize_event_rows",
46
+ "verify_row",
47
+ "verify_rows",
48
+ ]
localization/construct.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Construct localization-given-labels prompts from gold segments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import random
7
+ from collections import Counter
8
+ from typing import Sequence
9
+
10
+ from localization.schema import GoldSegment, LabelSpec
11
+
12
+ DEFAULT_SEED = 0
13
+ PROTOCOL_NAME = "localization-given-labels"
14
+ SOURCE_DATASET = "macrodata/WGO-Bench"
15
+
16
+
17
+ def label_specs_from_segments(
18
+ episode_id: str,
19
+ gold_segments: Sequence[GoldSegment],
20
+ *,
21
+ seed: int = DEFAULT_SEED,
22
+ ) -> list[LabelSpec]:
23
+ """Unique labels with multiplicity, shuffled deterministically per episode."""
24
+ counts = Counter(segment.label for segment in gold_segments)
25
+ specs = [LabelSpec(label, counts[label]) for label in sorted(counts)]
26
+ rng = random.Random(f"{seed}:{episode_id}")
27
+ rng.shuffle(specs)
28
+ return specs
29
+
30
+
31
+ def multiplicity_phrase(spec: LabelSpec) -> str:
32
+ quoted = json.dumps(spec.label)
33
+ if spec.multiplicity == 1:
34
+ return quoted
35
+ return f"{quoted} (occurs {spec.multiplicity} times)"
36
+
37
+
38
+ def localization_prompt(
39
+ instruction: str,
40
+ specs: Sequence[LabelSpec],
41
+ ) -> str:
42
+ labels = "\n".join(f"- {multiplicity_phrase(spec)}" for spec in specs)
43
+ return (
44
+ "Locate the listed manipulation event labels in this robot video from the "
45
+ "timestamped contact sheets.\n\n"
46
+ "Return only JSON matching the provided schema. For each listed label, "
47
+ "return exactly its requested number of intervals. Each interval must echo "
48
+ "the exact label string in label_echo and use visible timestamps for "
49
+ "start_sec and end_sec.\n\n"
50
+ "Rules:\n"
51
+ "- Bind times only to the exact listed label.\n"
52
+ "- Do not invent labels that are not listed.\n"
53
+ "- Use one interval per occurrence when a label occurs multiple times.\n"
54
+ "- Prefer temporally tight intervals around completed manipulation events.\n\n"
55
+ f"Episode instruction: {instruction}\n\n"
56
+ f"Event labels:\n{labels}\n"
57
+ )
58
+
59
+
60
+ def construction_meta(*, seed: int = DEFAULT_SEED) -> dict[str, str | int]:
61
+ return {
62
+ "seed": seed,
63
+ "protocol": PROTOCOL_NAME,
64
+ "source": SOURCE_DATASET,
65
+ }
localization/schema.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prediction and label-spec types for localization given labels."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ from pydantic import BaseModel, Field
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class LabelSpec:
13
+ label: str
14
+ multiplicity: int
15
+
16
+ def to_dict(self) -> dict[str, Any]:
17
+ return {"label": self.label, "multiplicity": self.multiplicity}
18
+
19
+ @classmethod
20
+ def from_dict(cls, raw: dict[str, Any]) -> LabelSpec:
21
+ return cls(label=str(raw["label"]), multiplicity=int(raw["multiplicity"]))
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class GoldSegment:
26
+ start_sec: float
27
+ end_sec: float
28
+ label: str
29
+
30
+ def to_dict(self) -> dict[str, Any]:
31
+ return {
32
+ "start_sec": float(self.start_sec),
33
+ "end_sec": float(self.end_sec),
34
+ "label": self.label,
35
+ }
36
+
37
+ @classmethod
38
+ def from_dict(cls, raw: dict[str, Any]) -> GoldSegment:
39
+ return cls(
40
+ start_sec=float(raw["start_sec"]),
41
+ end_sec=float(raw["end_sec"]),
42
+ label=str(raw["label"]),
43
+ )
44
+
45
+
46
+ class PredictedInterval(BaseModel):
47
+ label_echo: str
48
+ start_sec: float
49
+ end_sec: float
50
+
51
+
52
+ class LabelPrediction(BaseModel):
53
+ label: str
54
+ intervals: list[PredictedInterval] = Field(default_factory=list)
55
+
56
+
57
+ class PredictionResult(BaseModel):
58
+ """Structured model output for localization given labels."""
59
+
60
+ labels: list[LabelPrediction] = Field(default_factory=list)
localization/score.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Score localization-given-labels predictions (bound mean IoU / accuracy)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ from typing import Any, Sequence
7
+
8
+ from localization.schema import (
9
+ GoldSegment,
10
+ LabelSpec,
11
+ PredictedInterval,
12
+ PredictionResult,
13
+ )
14
+
15
+
16
+ def interval_iou(a_start: float, a_end: float, b_start: float, b_end: float) -> float:
17
+ intersection = max(0.0, min(a_end, b_end) - max(a_start, b_start))
18
+ union = max(a_end, b_end) - min(a_start, b_start)
19
+ if union <= 0:
20
+ return 0.0
21
+ return intersection / union
22
+
23
+
24
+ def optimal_group_assignment(
25
+ gold_segments: Sequence[GoldSegment],
26
+ pred_segments: Sequence[PredictedInterval],
27
+ ) -> dict[int, int]:
28
+ """Within-label 1:1 assignment maximizing summed IoU (deterministic ties)."""
29
+ gold_count = len(gold_segments)
30
+ pred_count = len(pred_segments)
31
+ target_assignments = min(gold_count, pred_count)
32
+ if target_assignments == 0:
33
+ return {}
34
+
35
+ memo: dict[tuple[int, int, int], tuple[float, tuple[int | None, ...]]] = {}
36
+ none_rank = pred_count + 1
37
+
38
+ def better(
39
+ left: tuple[float, tuple[int | None, ...]],
40
+ right: tuple[float, tuple[int | None, ...]] | None,
41
+ ) -> tuple[float, tuple[int | None, ...]]:
42
+ if right is None:
43
+ return left
44
+ left_score, left_key = left
45
+ right_score, right_key = right
46
+ if left_score > right_score + 1e-12:
47
+ return left
48
+ if right_score > left_score + 1e-12:
49
+ return right
50
+ left_tie = tuple(none_rank if item is None else item for item in left_key)
51
+ right_tie = tuple(none_rank if item is None else item for item in right_key)
52
+ return left if left_tie < right_tie else right
53
+
54
+ def solve(
55
+ gold_index: int,
56
+ used_mask: int,
57
+ assignments_left: int,
58
+ ) -> tuple[float, tuple[int | None, ...]]:
59
+ key = (gold_index, used_mask, assignments_left)
60
+ if key in memo:
61
+ return memo[key]
62
+ if gold_index == gold_count:
63
+ if assignments_left == 0:
64
+ return 0.0, ()
65
+ return float("-inf"), ()
66
+
67
+ best: tuple[float, tuple[int | None, ...]] | None = None
68
+ remaining_gold = gold_count - gold_index
69
+ if remaining_gold > assignments_left:
70
+ suffix_score, suffix = solve(gold_index + 1, used_mask, assignments_left)
71
+ best = better((suffix_score, (None, *suffix)), best)
72
+
73
+ if assignments_left > 0:
74
+ gold = gold_segments[gold_index]
75
+ for pred_index, pred in enumerate(pred_segments):
76
+ if used_mask & (1 << pred_index):
77
+ continue
78
+ iou = interval_iou(
79
+ gold.start_sec,
80
+ gold.end_sec,
81
+ pred.start_sec,
82
+ pred.end_sec,
83
+ )
84
+ suffix_score, suffix = solve(
85
+ gold_index + 1,
86
+ used_mask | (1 << pred_index),
87
+ assignments_left - 1,
88
+ )
89
+ best = better((iou + suffix_score, (pred_index, *suffix)), best)
90
+
91
+ if best is None:
92
+ best = float("-inf"), ()
93
+ memo[key] = best
94
+ return best
95
+
96
+ _, assignment_key = solve(0, 0, target_assignments)
97
+ return {
98
+ gold_index: pred_index
99
+ for gold_index, pred_index in enumerate(assignment_key)
100
+ if pred_index is not None
101
+ }
102
+
103
+
104
+ def _collision_counts(pred_segments: Sequence[PredictedInterval]) -> dict[str, int]:
105
+ overlap_pairs = 0
106
+ duplicate_pairs = 0
107
+ for left_index, left in enumerate(pred_segments):
108
+ for right in pred_segments[left_index + 1 :]:
109
+ iou = interval_iou(
110
+ left.start_sec,
111
+ left.end_sec,
112
+ right.start_sec,
113
+ right.end_sec,
114
+ )
115
+ if iou > 0:
116
+ overlap_pairs += 1
117
+ if (
118
+ abs(left.start_sec - right.start_sec) <= 1e-9
119
+ and abs(left.end_sec - right.end_sec) <= 1e-9
120
+ ):
121
+ duplicate_pairs += 1
122
+ return {"overlap_pairs": overlap_pairs, "duplicate_pairs": duplicate_pairs}
123
+
124
+
125
+ def score_episode(
126
+ *,
127
+ episode_id: str,
128
+ family: str,
129
+ gold_segments: Sequence[GoldSegment],
130
+ specs: Sequence[LabelSpec],
131
+ prediction: PredictionResult,
132
+ ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
133
+ """Per-gold-event IoU under grouped binding. No snapping."""
134
+ expected = {spec.label: spec.multiplicity for spec in specs}
135
+ gold_by_label: dict[str, list[tuple[int, GoldSegment]]] = defaultdict(list)
136
+ for gold_index, segment in enumerate(gold_segments):
137
+ gold_by_label[segment.label].append((gold_index, segment))
138
+
139
+ pred_by_label: dict[str, list[PredictedInterval]] = defaultdict(list)
140
+ malformed = 0
141
+ unexpected_labels = 0
142
+ for item in prediction.labels:
143
+ if item.label not in expected:
144
+ unexpected_labels += 1
145
+ continue
146
+ for interval in item.intervals:
147
+ if (
148
+ interval.label_echo != item.label
149
+ or interval.end_sec <= interval.start_sec
150
+ ):
151
+ malformed += 1
152
+ continue
153
+ pred_by_label[item.label].append(interval)
154
+
155
+ rows: list[dict[str, Any]] = []
156
+ exact_count_labels = 0
157
+ collision_pairs = 0
158
+ duplicate_collision_pairs = 0
159
+ for spec in specs:
160
+ label = spec.label
161
+ gold_items = gold_by_label[label]
162
+ gold_for_label = [segment for _, segment in gold_items]
163
+ pred_segments = pred_by_label.get(label, [])
164
+ if len(pred_segments) == spec.multiplicity:
165
+ exact_count_labels += 1
166
+ collisions = _collision_counts(pred_segments)
167
+ collision_pairs += collisions["overlap_pairs"]
168
+ duplicate_collision_pairs += collisions["duplicate_pairs"]
169
+ assignment = optimal_group_assignment(gold_for_label, pred_segments)
170
+ for local_gold_index, (gold_index, gold) in enumerate(gold_items):
171
+ pred_index = assignment.get(local_gold_index)
172
+ pred = pred_segments[pred_index] if pred_index is not None else None
173
+ iou = (
174
+ interval_iou(
175
+ gold.start_sec,
176
+ gold.end_sec,
177
+ pred.start_sec,
178
+ pred.end_sec,
179
+ )
180
+ if pred is not None
181
+ else 0.0
182
+ )
183
+ rows.append(
184
+ {
185
+ "episode_id": episode_id,
186
+ "family": family,
187
+ "gold_index": gold_index,
188
+ "label": label,
189
+ "multiplicity": spec.multiplicity,
190
+ "gold_start_sec": gold.start_sec,
191
+ "gold_end_sec": gold.end_sec,
192
+ "pred_index_within_label": pred_index,
193
+ "pred_start_sec": None if pred is None else pred.start_sec,
194
+ "pred_end_sec": None if pred is None else pred.end_sec,
195
+ "iou": iou,
196
+ "hit_0_5": iou >= 0.5,
197
+ "hit_0_75": iou >= 0.75,
198
+ }
199
+ )
200
+
201
+ diagnostics = {
202
+ "labels_total": len(specs),
203
+ "labels_exact_count": exact_count_labels,
204
+ "label_coverage": exact_count_labels / len(specs) if specs else 1.0,
205
+ "events_total": len(gold_segments),
206
+ "malformed_intervals": malformed,
207
+ "unexpected_label_groups": unexpected_labels,
208
+ "within_group_collision_pairs": collision_pairs,
209
+ "within_group_duplicate_pairs": duplicate_collision_pairs,
210
+ }
211
+ return sorted(rows, key=lambda row: row["gold_index"]), diagnostics
212
+
213
+
214
+ def metrics_from_rows(rows: Sequence[dict[str, Any]]) -> dict[str, Any]:
215
+ if not rows:
216
+ return {
217
+ "events": 0,
218
+ "mean_iou": None,
219
+ "accuracy_0_5": None,
220
+ "accuracy_0_75": None,
221
+ }
222
+ ious = [float(row["iou"]) for row in rows]
223
+ return {
224
+ "events": len(rows),
225
+ "mean_iou": sum(ious) / len(ious),
226
+ "accuracy_0_5": sum(iou >= 0.5 for iou in ious) / len(ious),
227
+ "accuracy_0_75": sum(iou >= 0.75 for iou in ious) / len(ious),
228
+ }
229
+
230
+
231
+ def summarize_event_rows(rows: Sequence[dict[str, Any]]) -> dict[str, Any]:
232
+ by_family: dict[str, list[dict[str, Any]]] = defaultdict(list)
233
+ for row in rows:
234
+ by_family[str(row["family"])].append(row)
235
+ return {
236
+ "overall": metrics_from_rows(rows),
237
+ "by_family": {
238
+ family: metrics_from_rows(family_rows)
239
+ for family, family_rows in sorted(by_family.items())
240
+ },
241
+ }
localization/verify.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify materialized parquet rows match construct() from gold."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Mapping, Sequence
6
+
7
+ from localization.construct import (
8
+ DEFAULT_SEED,
9
+ label_specs_from_segments,
10
+ localization_prompt,
11
+ )
12
+ from localization.schema import GoldSegment, LabelSpec
13
+
14
+
15
+ def _as_gold_segments(raw: Sequence[Mapping[str, Any]]) -> list[GoldSegment]:
16
+ return [GoldSegment.from_dict(dict(item)) for item in raw]
17
+
18
+
19
+ def _as_specs(raw: Sequence[Mapping[str, Any]]) -> list[LabelSpec]:
20
+ return [LabelSpec.from_dict(dict(item)) for item in raw]
21
+
22
+
23
+ def verify_row(row: Mapping[str, Any], *, seed: int = DEFAULT_SEED) -> None:
24
+ episode_id = str(row["id"])
25
+ instruction = str(row.get("instruction") or "")
26
+ gold = _as_gold_segments(row["gold_segments"])
27
+ stored_specs = _as_specs(row["label_specs"])
28
+ recomputed = label_specs_from_segments(episode_id, gold, seed=seed)
29
+ if [(s.label, s.multiplicity) for s in recomputed] != [
30
+ (s.label, s.multiplicity) for s in stored_specs
31
+ ]:
32
+ raise AssertionError(
33
+ f"{episode_id}: label_specs mismatch "
34
+ f"stored={[(s.label, s.multiplicity) for s in stored_specs]} "
35
+ f"recomputed={[(s.label, s.multiplicity) for s in recomputed]}"
36
+ )
37
+ expected_prompt = localization_prompt(instruction, recomputed)
38
+ stored_prompt = str(row["prompt_text"])
39
+ if stored_prompt != expected_prompt:
40
+ raise AssertionError(f"{episode_id}: prompt_text mismatch")
41
+
42
+
43
+ def verify_rows(rows: Sequence[Mapping[str, Any]], *, seed: int = DEFAULT_SEED) -> int:
44
+ for row in rows:
45
+ verify_row(row, seed=seed)
46
+ return len(rows)
scripts/score_predictions.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Score localization-given-labels predictions against a materialized parquet split."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ # Allow `python scripts/score_predictions.py` from the dataset root.
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ if str(ROOT) not in sys.path:
15
+ sys.path.insert(0, str(ROOT))
16
+
17
+ from localization.schema import ( # noqa: E402
18
+ GoldSegment,
19
+ LabelSpec,
20
+ PredictionResult,
21
+ )
22
+ from localization.score import score_episode, summarize_event_rows # noqa: E402
23
+
24
+
25
+ def _read_jsonl(path: Path) -> list[dict[str, Any]]:
26
+ rows: list[dict[str, Any]] = []
27
+ with path.open() as handle:
28
+ for line in handle:
29
+ if line.strip():
30
+ rows.append(json.loads(line))
31
+ return rows
32
+
33
+
34
+ def _load_parquet_rows(path: Path) -> list[dict[str, Any]]:
35
+ try:
36
+ import pyarrow.parquet as pq
37
+ except ImportError as exc: # pragma: no cover
38
+ raise SystemExit(
39
+ "pyarrow is required to read dataset parquet files"
40
+ ) from exc
41
+ return pq.read_table(path).to_pylist()
42
+
43
+
44
+ def _prediction_from_row(row: dict[str, Any]) -> PredictionResult:
45
+ if "labels" in row:
46
+ return PredictionResult.model_validate({"labels": row["labels"]})
47
+ if "prediction" in row:
48
+ return PredictionResult.model_validate(row["prediction"])
49
+ raise ValueError(
50
+ f"prediction row for {row.get('id') or row.get('episode_id')!r} "
51
+ "must contain 'labels' or 'prediction'"
52
+ )
53
+
54
+
55
+ def main(argv: list[str] | None = None) -> int:
56
+ parser = argparse.ArgumentParser(
57
+ description="Score localization-given-labels predictions.jsonl"
58
+ )
59
+ parser.add_argument(
60
+ "--data",
61
+ type=Path,
62
+ required=True,
63
+ help="Path to train.parquet or test.parquet",
64
+ )
65
+ parser.add_argument(
66
+ "--preds",
67
+ type=Path,
68
+ required=True,
69
+ help="JSONL with one object per episode: {id|episode_id, labels: [...]}",
70
+ )
71
+ parser.add_argument(
72
+ "--out",
73
+ type=Path,
74
+ default=None,
75
+ help="Optional path for per-event IoU JSONL",
76
+ )
77
+ parser.add_argument(
78
+ "--summary",
79
+ type=Path,
80
+ default=None,
81
+ help="Optional path for summary JSON (default: stdout)",
82
+ )
83
+ args = parser.parse_args(argv)
84
+
85
+ episodes = {str(row["id"]): row for row in _load_parquet_rows(args.data)}
86
+ pred_rows = _read_jsonl(args.preds)
87
+
88
+ all_event_rows: list[dict[str, Any]] = []
89
+ missing: list[str] = []
90
+ for pred_row in pred_rows:
91
+ episode_id = str(pred_row.get("id") or pred_row.get("episode_id") or "")
92
+ if not episode_id or episode_id not in episodes:
93
+ missing.append(episode_id or "<missing-id>")
94
+ continue
95
+ episode = episodes[episode_id]
96
+ gold = [GoldSegment.from_dict(seg) for seg in episode["gold_segments"]]
97
+ specs = [LabelSpec.from_dict(spec) for spec in episode["label_specs"]]
98
+ prediction = _prediction_from_row(pred_row)
99
+ event_rows, _diagnostics = score_episode(
100
+ episode_id=episode_id,
101
+ family=str(episode["family"]),
102
+ gold_segments=gold,
103
+ specs=specs,
104
+ prediction=prediction,
105
+ )
106
+ all_event_rows.extend(event_rows)
107
+
108
+ summary = summarize_event_rows(all_event_rows)
109
+ summary["episodes_scored"] = len({row["episode_id"] for row in all_event_rows})
110
+ summary["episodes_missing_from_data"] = missing
111
+
112
+ if args.out is not None:
113
+ args.out.parent.mkdir(parents=True, exist_ok=True)
114
+ with args.out.open("w") as handle:
115
+ for row in all_event_rows:
116
+ handle.write(json.dumps(row) + "\n")
117
+
118
+ text = json.dumps(summary, indent=2) + "\n"
119
+ if args.summary is not None:
120
+ args.summary.parent.mkdir(parents=True, exist_ok=True)
121
+ args.summary.write_text(text)
122
+ else:
123
+ sys.stdout.write(text)
124
+ return 0
125
+
126
+
127
+ if __name__ == "__main__":
128
+ raise SystemExit(main())
splits/dev_80.json ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "seed": 0,
3
+ "parquet_row_count": 100,
4
+ "created_date": "2026-07-03",
5
+ "ids": [
6
+ "galaxea_002",
7
+ "galaxea_007",
8
+ "galaxea_009",
9
+ "galaxea_028",
10
+ "galaxea_033",
11
+ "galaxea_037",
12
+ "galaxea_039",
13
+ "galaxea_043",
14
+ "galaxea_045",
15
+ "galaxea_047",
16
+ "galaxea_049",
17
+ "galaxea_050",
18
+ "galaxea_052",
19
+ "galaxea_058",
20
+ "galaxea_060",
21
+ "galaxea_062",
22
+ "galaxea_067",
23
+ "galaxea_069",
24
+ "galaxea_071",
25
+ "galaxea_073",
26
+ "homer_1",
27
+ "homer_11",
28
+ "homer_12",
29
+ "homer_15",
30
+ "homer_2",
31
+ "homer_29",
32
+ "homer_3",
33
+ "homer_37",
34
+ "homer_38",
35
+ "homer_39",
36
+ "homer_41",
37
+ "homer_48",
38
+ "homer_5",
39
+ "homer_50",
40
+ "homer_52",
41
+ "homer_53",
42
+ "homer_56",
43
+ "homer_59",
44
+ "homer_60",
45
+ "homer_7",
46
+ "robointer_droid_000001",
47
+ "robointer_droid_000002",
48
+ "robointer_droid_000003",
49
+ "robointer_droid_000004",
50
+ "robointer_droid_000005",
51
+ "robointer_droid_000006",
52
+ "robointer_droid_000007",
53
+ "robointer_droid_000008",
54
+ "robointer_droid_000010",
55
+ "robointer_droid_000011",
56
+ "robointer_droid_000012",
57
+ "robointer_droid_000013",
58
+ "robointer_droid_000015",
59
+ "robointer_droid_000016",
60
+ "robointer_droid_000017",
61
+ "robointer_droid_000019",
62
+ "robointer_droid_000021",
63
+ "robointer_droid_000023",
64
+ "robointer_droid_000024",
65
+ "robointer_droid_000027",
66
+ "robointer_droid_000028",
67
+ "robointer_droid_000030",
68
+ "robointer_droid_000032",
69
+ "robointer_droid_000033",
70
+ "robointer_droid_000034",
71
+ "robointer_droid_000038",
72
+ "robointer_droid_000039",
73
+ "robointer_droid_000042",
74
+ "robointer_droid_000043",
75
+ "robointer_droid_000045",
76
+ "robointer_droid_000046",
77
+ "robointer_droid_000047",
78
+ "robointer_droid_000050",
79
+ "robointer_droid_000055",
80
+ "robointer_droid_000056",
81
+ "robointer_droid_000057",
82
+ "robointer_droid_000058",
83
+ "robointer_droid_000059",
84
+ "robointer_droid_000060",
85
+ "robointer_droid_000061"
86
+ ]
87
+ }
splits/heldout_20.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "seed": 0,
3
+ "parquet_row_count": 100,
4
+ "created_date": "2026-07-03",
5
+ "ids": [
6
+ "galaxea_011",
7
+ "galaxea_013",
8
+ "galaxea_041",
9
+ "galaxea_065",
10
+ "galaxea_075",
11
+ "homer_10",
12
+ "homer_33",
13
+ "homer_4",
14
+ "homer_40",
15
+ "homer_9",
16
+ "robointer_droid_000009",
17
+ "robointer_droid_000014",
18
+ "robointer_droid_000022",
19
+ "robointer_droid_000025",
20
+ "robointer_droid_000029",
21
+ "robointer_droid_000035",
22
+ "robointer_droid_000036",
23
+ "robointer_droid_000037",
24
+ "robointer_droid_000044",
25
+ "robointer_droid_000062"
26
+ ]
27
+ }
tests/test_localization.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for localization construction and scoring (no API deps)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from localization.construct import (
6
+ label_specs_from_segments,
7
+ localization_prompt,
8
+ multiplicity_phrase,
9
+ )
10
+ from localization.schema import GoldSegment, PredictedInterval, PredictionResult
11
+ from localization.score import optimal_group_assignment, score_episode
12
+
13
+
14
+ def _segments(labels: list[str]) -> list[GoldSegment]:
15
+ return [
16
+ GoldSegment(float(index), float(index + 1), label)
17
+ for index, label in enumerate(labels)
18
+ ]
19
+
20
+
21
+ def test_multiplicity_phrasing_handles_singletons_and_duplicates():
22
+ gold = _segments(["pick", "place", "pick"])
23
+ specs = sorted(
24
+ label_specs_from_segments("homer_1", gold, seed=0),
25
+ key=lambda spec: spec.label,
26
+ )
27
+
28
+ assert [multiplicity_phrase(spec) for spec in specs] == [
29
+ '"pick" (occurs 2 times)',
30
+ '"place"',
31
+ ]
32
+ prompt = localization_prompt("stack the blocks", specs)
33
+ assert '"pick" (occurs 2 times)' in prompt
34
+ assert '- "place"\n' in prompt
35
+ assert "occurs 1" not in prompt
36
+
37
+
38
+ def test_label_shuffle_is_deterministic_under_seed():
39
+ gold = _segments(["a", "b", "c", "d"])
40
+
41
+ first = [spec.label for spec in label_specs_from_segments("homer_1", gold, seed=3)]
42
+ second = [spec.label for spec in label_specs_from_segments("homer_1", gold, seed=3)]
43
+ alternatives = {
44
+ tuple(spec.label for spec in label_specs_from_segments("homer_1", gold, seed=seed))
45
+ for seed in range(10)
46
+ }
47
+
48
+ assert first == second
49
+ assert len(alternatives) > 1
50
+
51
+
52
+ def test_optimal_group_assignment_ties_are_deterministic():
53
+ golds = [
54
+ GoldSegment(0.0, 2.0, "repeat"),
55
+ GoldSegment(2.0, 4.0, "repeat"),
56
+ ]
57
+ preds = [
58
+ PredictedInterval(label_echo="repeat", start_sec=1.0, end_sec=3.0),
59
+ PredictedInterval(label_echo="repeat", start_sec=1.0, end_sec=3.0),
60
+ ]
61
+
62
+ assert optimal_group_assignment(golds, preds) == {0: 0, 1: 1}
63
+
64
+
65
+ def test_score_episode_exact_match_is_perfect():
66
+ gold = _segments(["pick", "place"])
67
+ specs = label_specs_from_segments("ep", gold, seed=0)
68
+ prediction = PredictionResult(
69
+ labels=[
70
+ {
71
+ "label": "pick",
72
+ "intervals": [
73
+ {"label_echo": "pick", "start_sec": 0.0, "end_sec": 1.0},
74
+ ],
75
+ },
76
+ {
77
+ "label": "place",
78
+ "intervals": [
79
+ {"label_echo": "place", "start_sec": 1.0, "end_sec": 2.0},
80
+ ],
81
+ },
82
+ ]
83
+ )
84
+ rows, diagnostics = score_episode(
85
+ episode_id="ep",
86
+ family="homer",
87
+ gold_segments=gold,
88
+ specs=specs,
89
+ prediction=prediction,
90
+ )
91
+ assert diagnostics["events_total"] == 2
92
+ assert all(row["iou"] == 1.0 for row in rows)
93
+ assert all(row["hit_0_75"] for row in rows)