Robotics
LeRobot
gr00t
act
pi05
training
bimanual
pl2m-training / scripts /dataset_spec.py
minssuung's picture
Add PL-2 M training code
acba5e6 verified
Raw History Blame Contribute Delete
24.3 kB
#!/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 ``<label key>.<joint>``, contiguous per label, and each
label lists its joints in the group's order. So the whole mapping reduces
to matching runs to groups, and a run belongs to the group whose name
shares the most tokens with the label key. Anything short of one
unambiguous bijection returns None β€” a wrong gap reads exactly like the
fault this metric exists to find.
"""
names = (info.get("features", {}).get("executed_action", {}) or {}).get("names")
if not names or not spans:
return None
runs: list[tuple[str, list[int]]] = []
for i, name in enumerate(names):
key = name.rsplit(".", 1)[0]
if runs and runs[-1][0] == key:
runs[-1][1].append(i)
else:
runs.append((key, [i]))
def tokens(text: str) -> set[str]:
return {t for t in text.replace(".", "_").split("_") if t}
perm = [-1] * len(names)
taken: set[int] = set()
for span in spans:
want = span.end - span.start
# Most shared tokens wins; ties go to the tighter key, so a group
# named for an arm does not match that arm's gripper label as well as
# its own (both carry the side, the gripper label carries one word
# more). Integer scores β€” no float ties to reason about.
scored = []
for r, (key, idx) in enumerate(runs):
if r in taken or len(idx) != want:
continue
kt, gt = tokens(key), tokens(span.name)
scored.append(((len(kt & gt), -len(kt | gt)), r))
best = max((sc for sc, _ in scored), default=(0, 0))
winners = [r for sc, r in scored if sc == best]
if best[0] == 0 or len(winners) != 1:
logger.info("executed_action slots do not match group %r one to one "
"β€” gate_gap omitted", span.name)
return None
taken.add(winners[0])
for offset, slot in enumerate(runs[winners[0]][1]):
perm[span.start + offset] = slot
if sorted(perm) != list(range(len(names))):
logger.info("executed_action slots did not cover every action slot "
"β€” gate_gap omitted")
return None
return perm
def episode_quality(dataset_root: Path,
info: dict | None = None) -> list[EpisodeQuality]:
"""Quality numbers for every episode, from the data parquets.
Reads ``action`` against the NEXT frame's ``observation.state`` (the
earliest the command could show up in a measurement), grouped by the
dataset's own group boundaries.
"""
import glob as _glob
import numpy as np
import pandas as pd
root = Path(dataset_root)
info = info or load_info(root)
spans = groups_of(root, info)
paths = sorted(_glob.glob(str(root / "data" / "**" / "*.parquet"),
recursive=True))
if not paths:
raise ValueError(f"{root} has no data parquets to score")
frames = pd.concat((pd.read_parquet(p) for p in paths), ignore_index=True)
has_executed = "executed_action" in frames.columns
executed_slots = (executed_permutation(info, spans)
if has_executed else None)
out: list[EpisodeQuality] = []
for episode, rows in frames.groupby("episode_index", sort=True):
rows = rows.sort_values("frame_index")
state = np.stack(rows["observation.state"].to_numpy())
action = np.stack(rows["action"].to_numpy())
tracking = {
g.name: float(np.mean(np.abs(
action[:-1, g.start:g.end] - state[1:, g.start:g.end])))
for g in spans
} if len(rows) > 1 else {g.name: 0.0 for g in spans}
gap: dict[str, float] = {}
if has_executed and executed_slots is not None:
# Reordered into the action layout first β€” the two columns are
# named separately on purpose and only agree slot for slot here.
executed = np.stack(
rows["executed_action"].to_numpy())[:, executed_slots]
gap = {
g.name: float(np.mean(np.abs(
action[:, g.start:g.end] - executed[:, g.start:g.end])))
for g in spans
}
out.append(EpisodeQuality(episode=int(episode),
tracking_err=tracking, gate_gap=gap))
return out
# ---------------------------------------------------------------------------
# Held-out split (deterministic, stratified by task)
# ---------------------------------------------------------------------------
#: The recorder's task registry sidecar (historical filename β€” it stores the
#: declared tasks and the episode->task mapping, no group tree).
TASK_REGISTRY = "task_groups.json"
def episode_tasks(dataset_root: Path) -> dict[int, str]:
"""``{episode: task}`` from the registry sidecar; absent/corrupt -> {}."""
path = Path(dataset_root) / TASK_REGISTRY
if not path.is_file():
return {}
try:
mapping = json.loads(path.read_text(encoding="utf-8"))["episode_tasks"]
return {int(k): str(v) for k, v in mapping.items()}
except (ValueError, KeyError, TypeError, OSError):
return {}
def holdout_split(episodes: list[int], *, fraction: float, seed: int,
tasks: dict[int, str] | None = None
) -> tuple[list[int], list[int]]:
"""``(train, held)`` β€” deterministic and stratified per task.
Episode-level, never frame-level: adjacent frames of one episode are
near-duplicates, so a frame split leaks the training set into the
validation set and validates nothing.
Per task: ``round(fraction * n)`` episodes, floored at 1 when the task
has at least two (a validation set that skips a whole task cannot see
that task regress) and 0 when it has only one (never strand a task's
only training episode). Same seed + same episode set = same split, on
any machine β€” the split is part of the run's identity, not a dice roll.
"""
if not 0.0 < fraction < 1.0:
raise ValueError(f"holdout fraction must be in (0, 1), got {fraction}")
import random
rng = random.Random(seed)
tasks = tasks or {}
by_task: dict[str, list[int]] = {}
for ep in sorted(episodes):
by_task.setdefault(tasks.get(ep, ""), []).append(ep)
held: list[int] = []
for _, eps in sorted(by_task.items()):
if len(eps) < 2:
continue
k = min(len(eps) - 1, max(1, round(fraction * len(eps))))
held.extend(rng.sample(eps, k))
held = sorted(held)
train = [e for e in sorted(episodes) if e not in set(held)]
return train, held
def rollout_verdicts(dataset_root: Path) -> dict[int, dict]:
"""``{episode: verdict record}`` β€” the operator's rollout tags.
Each record carries ``outcome`` (the fixed vocabulary), ``note`` and,
for rollout-mode recordings, ``checkpoint``. The LAST tag per episode
wins (an operator may re-judge). Records without a ``verdict`` key are
the judge's validity records and skipped; damaged lines never raise.
Stdlib restatement of ``pl_imitation_recorder.recorder.verdict``'s
reader β€” this module runs in the training venv with no ROS workspace on
the path (the ``_runs`` precedent); the recorder-side test gates the two
against each other.
"""
path = Path(dataset_root) / VALIDITY_SIDECAR
if not path.is_file():
return {}
out: dict[int, dict] = {}
for line in path.read_text(encoding="utf-8").splitlines():
try:
record = json.loads(line)
out[int(record["episode_index"])] = dict(record["verdict"])
except (ValueError, KeyError, TypeError):
continue
return out