Robotics
LeRobot
gr00t
act
pi05
training
bimanual
File size: 7,700 Bytes
acba5e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#!/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:

* ``<dataset>/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