#!/usr/bin/env python3 """What a recorded dataset actually contains — read from it, never restated. WHY THIS EXISTS --------------- Three facts have to agree for a fine-tune to be correct: which cameras the policy consumes, where the state/action vector splits into arm and gripper groups, and which episodes are usable. Every previous version of this pipeline wrote all three down by hand, twice: * ``openarm_config.py`` on the GPU box restated the group boundaries as the literals ``right_arm[0:7], right_gripper[7:8], left_arm[8:15], left_gripper[15:16]`` and the camera roles as ``["top", "right_gripper", "left_gripper"]`` — under a docstring reading "Keys match meta/modality.json". A comment where a derivation belongs. * the intact-episode set appeared as ``INTACT = [0, 1, 2, ...]`` in ``filter_reindex.py`` for GR00T *and again* as ``--dataset.episodes="[0,1,2,...]"`` for ACT. Two hand-maintained copies of one judgement about which videos were short. None of those are choices. They are properties of the dataset on disk, so this module computes them and nothing downstream is allowed to hardcode them. TRUNCATION ---------- ``intact_episodes`` is the one that earns its keep. A recording whose video file was cut short still has full metadata: ``meta/episodes`` claims frames out to ``to_timestamp`` that the mp4 does not contain, and training on it either crashes in the dataloader or — worse — silently pairs actions with the wrong frames. Comparing each episode's claimed span against the real decoded duration finds them, which is what produced that hand-written list in the first place. Needs pandas (parquet) and ffprobe; both are present in the training environments and on the GPU host. Not importable from the pl_imitation_inference console — that side is deliberately stdlib-only and has no reason to read episode tables. """ from __future__ import annotations import json import logging import subprocess from dataclasses import dataclass, field from functools import lru_cache from pathlib import Path logger = logging.getLogger(__name__) #: Slack allowed between an episode's claimed end and the video's decoded #: duration. Container duration is rounded to the timebase and the last frame #: has real extent, so an exact compare reports healthy episodes as truncated. #: One frame at 30 Hz is 33 ms; 100 ms is comfortably past rounding without #: being large enough to hide a genuinely cut recording (those lose seconds). DURATION_TOLERANCE_S = 0.10 _IMAGE_PREFIX = "observation.images." @dataclass(frozen=True) class Group: """One contiguous span of the state/action vector.""" name: str start: int end: int def as_dict(self) -> dict: return {"start": self.start, "end": self.end} def load_info(dataset_root: Path) -> dict: """``meta/info.json``, or a clear error naming the path.""" info_path = Path(dataset_root) / "meta" / "info.json" if not info_path.is_file(): raise FileNotFoundError( f"no dataset at {dataset_root}: expected {info_path}. Record episodes first, " f"or point --repo-id at a dataset that exists.") return json.loads(info_path.read_text()) def camera_roles(info: dict) -> list[str]: """Camera roles the dataset actually carries, in feature order. Read from the dataset rather than from ``config/cameras.json`` on purpose: training must match the data it is given. A rig that has since gained a fourth camera must not produce a modality config claiming four streams for a dataset recorded with three. """ roles = [ key[len(_IMAGE_PREFIX):] for key in info.get("features", {}) if key.startswith(_IMAGE_PREFIX) ] if not roles: raise ValueError( f"dataset declares no {_IMAGE_PREFIX}* features; a vision policy cannot be " f"trained on it. Features present: {sorted(info.get('features', {}))}") return roles def state_names(info: dict) -> list[str]: """``observation.state`` component names, in vector order.""" try: names = info["features"]["observation.state"]["names"] except KeyError as exc: raise ValueError( "dataset has no observation.state names; cannot derive group boundaries") from exc if not names: raise ValueError("dataset declares an empty observation.state") return list(names) #: The robot description the recorder copies into every dataset it creates. ROBOT_PROFILE_PATH = ("meta", "robot_profile.json") def groups_of(dataset_root: Path, info: dict | None = None) -> list[Group]: """Group boundaries for one dataset — from the dataset, always. A dataset recorded since the recorder started carrying its robot profile says outright which columns form which group; that copy is read here. It is the dataset's own profile, never the rig's current one: a set recorded last month under a different robot must keep grouping the way it was recorded, and the rig this training run happens to sit next to may not even be the one that produced the data. Older datasets carry no such copy and fall back to ``groups()``, which infers the split from the component names. """ profile_path = Path(dataset_root).joinpath(*ROBOT_PROFILE_PATH) names = state_names(info or load_info(Path(dataset_root))) if not profile_path.is_file(): logger.info("%s absent — deriving group boundaries from the component names", profile_path) return groups(names) declared = json.loads(profile_path.read_text()) spans = _runs(declared) recorded = [entry["canonical"] for entry in declared["state"]] if recorded != names: raise ValueError( f"{profile_path} lists {len(recorded)} components but the dataset's " f"observation.state has {len(names)}; they must describe the same vector. " f"First difference: {next((f'{a!r} vs {b!r}' for a, b in zip(recorded, names) if a != b), 'length only')}") return spans def _runs(declared: dict) -> list[Group]: """Consecutive runs of ``state[].group`` -> Groups. A deliberate stdlib restatement of ``pl_imitation_recorder.state_schema``'s derivation: this module runs in the training venv, which has no ROS workspace and no ``pl2_*`` packages on its path (the same constraint that puts a copy of the state layout in ``policy_state_layout.py``). ``test_dataset_spec_profile.py`` fails the build if the two derivations disagree — copy and gate, not copy and hope. """ out: list[Group] = [] for index, entry in enumerate(declared["state"]): if out and out[-1].name == entry["group"]: out[-1] = Group(out[-1].name, out[-1].start, index + 1) else: out.append(Group(entry["group"], index, index + 1)) return out def groups(names: list[str]) -> list[Group]: """Split the state vector into GR00T modality groups by NAME. The fallback for datasets recorded before the profile travelled with them. The layout this asserts — right arm block, right gripper, left arm block, left gripper — is the bimanual schema the recorder wrote at the time, and it is checked rather than assumed: a schema that interleaves the arms would otherwise produce silently wrong group boundaries, and wrong normalisation groups do not raise, they drive. Prefer ``groups_of``, which reads the boundaries the recorder declared instead of inferring them, and so is not limited to this one shape. """ def index_of(key: str) -> int: try: return names.index(key) except ValueError as exc: raise ValueError( f"expected a '{key}' component in observation.state to derive group " f"boundaries; got {names}. If the schema changed, this function must " f"change with it — do not hardcode the old indices.") from exc right_g = index_of("right_gripper.pos") left_g = index_of("left_gripper.pos") if not 0 < right_g < left_g == len(names) - 1: raise ValueError( f"unexpected state layout: right_gripper.pos at {right_g}, left_gripper.pos at " f"{left_g}, vector length {len(names)}. This module derives four contiguous " f"groups from that shape; the dataset does not have it.") return [ Group("right_arm", 0, right_g), Group("right_gripper", right_g, right_g + 1), Group("left_arm", right_g + 1, left_g), Group("left_gripper", left_g, left_g + 1), ] def episodes_table(dataset_root: Path): """``meta/episodes`` as one DataFrame, chunks concatenated.""" import pandas as pd # noqa: PLC0415 - training-env only files = sorted(Path(dataset_root).glob("meta/episodes/**/*.parquet")) if not files: raise FileNotFoundError(f"no episode metadata under {dataset_root}/meta/episodes") return pd.concat([pd.read_parquet(f) for f in files], ignore_index=True) @lru_cache(maxsize=None) def _video_duration(path: str) -> float | None: """Decoded duration in seconds, or None when ffprobe cannot read the file. None is itself a finding: a video that will not probe is not one to train on, and the caller treats it as truncated. """ try: out = subprocess.run( ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path], capture_output=True, text=True, timeout=60, check=False) except (OSError, subprocess.TimeoutExpired): return None text = out.stdout.strip() try: return float(text) except ValueError: return None def intact_episodes(dataset_root: Path, info: dict | None = None) -> tuple[list[int], dict[int, str]]: """``(intact_episode_indices, {episode: reason})`` for the ones dropped. An episode is dropped when any of its camera streams ends before the metadata says the episode does. The reason string is returned so the caller can log exactly what was excluded — a filter that silently removes a third of a dataset is indistinguishable from a dataset that was always small. """ root = Path(dataset_root) info = info or load_info(root) table = episodes_table(root) video_template = info.get("video_path") if not video_template: raise ValueError(f"{root}/meta/info.json declares no video_path template") roles = camera_roles(info) intact: list[int] = [] dropped: dict[int, str] = {} fps = float(info.get("fps") or 0) or 30.0 for row in table.to_dict("records"): episode = int(row["episode_index"]) problems = [] for role in roles: key = f"{_IMAGE_PREFIX}{role}" chunk_col, file_col = f"videos/{key}/chunk_index", f"videos/{key}/file_index" start_col = f"videos/{key}/from_timestamp" if chunk_col not in row or start_col not in row: # Metadata predates per-video spans; nothing to check against. continue # The moment the last frame the loader will actually READ sits at: # from_timestamp plus the episode's own frame count. Deliberately not # to_timestamp — an episode's allotted span routinely runs past its # data (ep4 here has 196 frames of unread tail), and measuring # against the span reports that dead air as a truncated recording. needed = float(row[start_col]) + float(row["length"]) / fps path = root / video_template.format( video_key=key, chunk_index=int(row[chunk_col]), file_index=int(row[file_col])) duration = _video_duration(str(path)) if duration is None: problems.append(f"{role}: unreadable ({path.name})") elif needed > duration + DURATION_TOLERANCE_S: problems.append( f"{role}: reads to {needed:.2f}s, video is {duration:.2f}s " f"(short {needed - duration:.2f}s)") if problems: dropped[episode] = "; ".join(problems) else: intact.append(episode) return intact, dropped # --------------------------------------------------------------------------- # Episode validity (the recorder's per-episode verdict sidecar) # --------------------------------------------------------------------------- #: The recorder's verdict sidecar, appended once per saved episode. Same #: constant as ``lerobot_ros2.recorder.SIDECAR_NAME`` — restated stdlib-side #: because this module runs in the training venv, where no ROS workspace is #: on the path (the ``_runs`` precedent). VALIDITY_SIDECAR = "pl_episodes.jsonl" @dataclass(frozen=True) class ValiditySummary: """What the recorder judged, episode by episode. ``judged`` counts sidecar records; a dataset recorded before the sidecar existed has 0 and is treated as all-valid — refusing it would strand real data over a check that cannot be performed (the resume-check precedent). """ judged: int invalid: dict[int, str] # episode -> reasons, the training filter's input flagged: dict[int, int] # episode -> flagged frame count (warn, not drop) #: episode -> the frames that made it invalid; empty when the whole episode is #: (an end-gate failure), so no cut can save it invalid_frames: dict[int, list[int]] = field(default_factory=dict) def validity_summary(dataset_root: Path) -> ValiditySummary: """Parse the verdict sidecar; a missing or corrupt line never raises. Re-recorded indices appear multiple times; the LAST record wins, matching what is actually stored in the dataset at that index. """ path = Path(dataset_root) / VALIDITY_SIDECAR if not path.is_file(): return ValiditySummary(judged=0, invalid={}, flagged={}) latest: dict[int, dict] = {} for line in path.read_text(encoding="utf-8").splitlines(): try: record = json.loads(line) latest[int(record["episode_index"])] = record["validity"] except (ValueError, KeyError, TypeError): continue # one damaged line must not blank the whole verdict invalid = {ep: "; ".join(v.get("reasons", [])[:3]) or "invalid" for ep, v in latest.items() if not v.get("valid", True)} flagged = {ep: len(v.get("flagged_frames", [])) for ep, v in latest.items() if v.get("flagged_frames")} frames = {ep: [] if latest[ep].get("episode_invalid") else list(latest[ep].get("invalid_frames", [])) for ep in invalid} return ValiditySummary(judged=len(latest), invalid=invalid, flagged=flagged, invalid_frames=frames) # --------------------------------------------------------------------------- # Episode quality (computed from the recorded action chain, offline) # --------------------------------------------------------------------------- @dataclass(frozen=True) class EpisodeQuality: """Per-episode quality numbers, per state group. ``tracking_err`` — mean |action[t] − state[t+1]| per group: how far the arm trailed what it was told, in the group's own unit. The online judge deliberately never compares values (its two streams latch at different times); offline the timeline is aligned, so the comparison is honest here. ``gate_gap`` — mean |action[t] − executed[t]| per group: how much the safety gate reshaped the commands. The executed column carries its own slot names and its own layout, so it is reordered into the action layout first. Empty for a dataset without an executed column, and for one whose executed slots cannot be matched to the groups — an unpairable column yields no number rather than a wrong one. """ episode: int tracking_err: dict[str, float] gate_gap: dict[str, float] def executed_permutation(info: dict, spans: list[Group]) -> list[int] | None: """action slot -> executed slot, or None when the two cannot be matched. The executed column is laid out in the schema's action order, which the recorder keeps deliberately apart from the state/action layout — that one is the trained models' contract. Both columns name their own slots, so the pairing is recoverable, but only BY NAME: sharing the index subtracts one joint from another and reports a gate that reshaped nothing as a gate that reshaped everything. Executed names are ``