#!/usr/bin/env python3 """Generate the two modality artifacts GR00T fine-tuning needs, from the dataset. GR00T wants the same information twice, in two formats: * ``/meta/modality.json`` — how the flat 16-wide state/action vector splits into named groups, and which video keys map to which role. Read at conversion and load time. * a Python module passed as ``--modality-config-path`` — the same split again, expressed as ``ModalityConfig`` objects, plus the action semantics (absolute/joint-space) and how many chunk steps to supervise. Both used to be written by hand, and the second one carried the group boundaries as literals. Generating both from ``dataset_spec`` means they cannot disagree with each other or with the data — the failure mode being avoided is not a crash but a silent mis-normalisation, where the model trains against group boundaries that do not match the vector it is fed. The generated Python module is a build artifact: written to a work directory, overwritten every run, never committed. """ from __future__ import annotations import json import logging from collections.abc import Sequence from pathlib import Path import dataset_spec logger = logging.getLogger(__name__) _GENERATED_HEADER = '''\ # GENERATED by scripts/groot_modality.py — DO NOT EDIT. # # Regenerated on every training run from the dataset's own meta/info.json. # Editing this file is pointless (it is overwritten) and dangerous (the edit # would not survive into the next run, so a fix applied here silently reverts). # Change scripts/training_config.py or the dataset instead. # # Source dataset : {dataset} # State layout : {layout} # Chunk horizon : {horizon} supervised steps # Action rep : {reps} ''' def modality_dict(dataset_root: Path, info: dict | None = None) -> dict: """The ``meta/modality.json`` content for one dataset.""" info = info or dataset_spec.load_info(dataset_root) groups = {g.name: g.as_dict() for g in dataset_spec.groups_of(dataset_root, info)} return { # state and action share the group structure: the recorder writes the # same 16-wide layout to both. "state": groups, "action": groups, "video": { role: {"original_key": f"observation.images.{role}"} for role in dataset_spec.camera_roles(info) }, "annotation": {"human.task_description": {"original_key": "task_index"}}, } def write_modality_json(dataset_root: Path, info: dict | None = None) -> Path: """Write ``meta/modality.json`` into the dataset. Idempotent.""" out = Path(dataset_root) / "meta" / "modality.json" out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(modality_dict(dataset_root, info), indent=2)) logger.info("wrote %s", out) return out def action_reps(group_names: Sequence[str], relative_groups: Sequence[str]) -> dict: """Map each action group to the representation it is supervised in. Absolute unless the group is named in ``relative_groups``. A name that matches no group is an error rather than a no-op: a misspelled group would train everything absolute, which looks exactly like a knob that had no effect, and the operator would be reading loss curves to find a typo. """ unknown = sorted(set(relative_groups) - set(group_names)) if unknown: raise ValueError( f"relative_groups names {unknown}, which this dataset has no action group for. " f"Its groups are {sorted(group_names)}.") relative = set(relative_groups) return {name: "RELATIVE" if name in relative else "ABSOLUTE" for name in group_names} def embodiment_config_source( dataset_root: Path, *, chunk_horizon: int, embodiment_tag: str, relative_groups: Sequence[str] = (), info: dict | None = None, ) -> str: """Python source for the ``--modality-config-path`` module. Groups named in ``relative_groups`` are supervised as state-relative deltas — Isaac subtracts the last observed state, ``action - state[-1]`` — and every other group stays an ABSOLUTE joint-space target. Absolute is the default because it is what makes RTC chunk-seam inpainting coherent: a frozen delta is not a frozen position, so freezing a seam in relative space decodes to a position jump of roughly the state change across the seam. The choice is per group rather than one switch because the grippers are the reason it has to be. A gripper is commanded as a near-binary open/close, so its action-minus-state is mostly zero with occasional spikes and normalises badly. Isaac's own shipped embodiment configs make the same split — arms RELATIVE, hands and grippers ABSOLUTE. Serving consequence, since it is not visible from here: a checkpoint with any relative group must be served decode-to-absolute (``relative_blend``), NOT with native RTC. lerobot disables its native RTC prefix for relative-action policies, and it decides that from its own ``GrootConfig.use_relative_actions`` — a field a raw Isaac checkpoint does not carry — so on this checkpoint shape the guard does not fire by itself. """ info = info or dataset_spec.load_info(dataset_root) groups = dataset_spec.groups_of(dataset_root, info) group_names = [g.name for g in groups] roles = dataset_spec.camera_roles(info) layout = ", ".join(f"{g.name}[{g.start}:{g.end}]" for g in groups) reps = action_reps(group_names, relative_groups) action_configs = "\n".join( f" ActionConfig( # {name}\n" f" rep=ActionRepresentation.{reps[name]},\n" f" type=ActionType.NON_EEF,\n" f" format=ActionFormat.DEFAULT,\n" f" )," for name in group_names ) return ( _GENERATED_HEADER.format( dataset=dataset_root, layout=layout, horizon=chunk_horizon, reps=", ".join(f"{name}={rep}" for name, rep in reps.items())) + f''' from gr00t.configs.data.embodiment_configs import register_modality_config from gr00t.data.embodiment_tags import EmbodimentTag from gr00t.data.types import ( ActionConfig, ActionFormat, ActionRepresentation, ActionType, ModalityConfig, ) openarm_bimanual_config = {{ "video": ModalityConfig( delta_indices=[0], modality_keys={roles!r}, ), "state": ModalityConfig( delta_indices=[0], modality_keys={group_names!r}, ), "action": ModalityConfig( delta_indices=list(range(0, {chunk_horizon})), modality_keys={group_names!r}, action_configs=[ {action_configs} ], ), "language": ModalityConfig( delta_indices=[0], modality_keys=["annotation.human.task_description"], ), }} register_modality_config( openarm_bimanual_config, embodiment_tag=EmbodimentTag.{embodiment_tag} ) ''' ) def write_embodiment_config( dataset_root: Path, out_path: Path, *, chunk_horizon: int, embodiment_tag: str, relative_groups: Sequence[str] = (), info: dict | None = None, ) -> Path: """Write the generated embodiment config module.""" source = embodiment_config_source( dataset_root, chunk_horizon=chunk_horizon, embodiment_tag=embodiment_tag, relative_groups=relative_groups, info=info) out_path = Path(out_path) out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_text(source) logger.info("wrote %s (horizon=%d, relative=%s)", out_path, chunk_horizon, list(relative_groups) or "none") return out_path