File size: 12,774 Bytes
d53876e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c675012
d53876e
 
 
 
 
c675012
7caec3d
 
d53876e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7caec3d
 
 
 
 
 
 
d53876e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c675012
 
 
 
 
d53876e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c675012
d53876e
 
 
 
 
 
 
 
 
 
 
 
 
 
c675012
 
 
d53876e
 
 
 
 
c675012
 
 
d53876e
 
 
 
 
 
 
 
 
 
 
 
7caec3d
d53876e
 
7caec3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d53876e
 
 
 
 
 
 
 
 
 
 
 
7caec3d
d53876e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c675012
 
 
d53876e
 
 
 
 
 
 
 
 
 
 
 
7caec3d
d53876e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7caec3d
 
 
d53876e
 
c675012
d53876e
 
 
 
 
 
 
 
 
 
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"""Apply the G1 Dex3 pick-and-place configs to an openpi checkout, idempotently.

    uv run python scripts/patch_openpi_config.py \
        --openpi /home/ubuntu/openpi --repo-id <YOUR_HF_USER>/<DATASET_NAME>

Replaces the manual copy-paste of `openpi_config_block.py`. Does three things:

1. copies `g1_dex3_policy.py` into `src/openpi/policies/`
2. adds the two imports to `src/openpi/training/config.py`
3. inserts `LeRobotG1Dex3DataConfig` and the two `TrainConfig` entries

Safe to rerun: each edit is skipped if already present. `config.py` is backed up once to
`config.py.orig` before the first modification.
"""
import argparse
import ast
import os
import pathlib
import shutil
import subprocess
import sys

PATCH_VERSION = 3
MARKER = "# G1DEX3-PATCH-VERSION:"

IMPORTS = """import openpi.shared.nnx_utils as nnx_utils
from openpi.policies import g1_dex3_policy
"""

DATA_CONFIG = '''
@dataclasses.dataclass(frozen=True)
class LeRobotG1Dex3DataConfig(DataConfigFactory):
    """G1 + Dex3 upper-body pick-and-place. 43-dim whole-body -> 28 trained dims."""

    @override
    def create(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig:
        repack = _transforms.Group(
            inputs=[
                _transforms.RepackTransform(
                    {
                        "images": {
                            "base_0_rgb": "observation.images.ego_view",
                            "left_wrist_0_rgb": "observation.images.ego_left",
                            "right_wrist_0_rgb": "observation.images.ego_right",
                        },
                        "state": "observation.state",
                        "actions": "action",
                        "prompt": "prompt",
                    }
                )
            ]
        )

        data_transforms = _transforms.Group(
            inputs=[g1_dex3_policy.G1Dex3Inputs(action_dim=model_config.action_dim)],
            outputs=[g1_dex3_policy.G1Dex3Outputs()],
        )

        # The 28 upper-body dims are ordered [L_arm 7, L_hand 7, R_arm 7, R_hand 7].
        # Delta on the arms, absolute on the hands -> interleaved. make_bool_mask(14, -14)
        # would leave the RIGHT arm (the one doing the task) on absolute actions.
        delta_mask = _transforms.make_bool_mask(7, -7, 7, -7)
        data_transforms = data_transforms.push(
            inputs=[_transforms.DeltaActions(delta_mask)],
            outputs=[_transforms.AbsoluteActions(delta_mask)],
        )

        return dataclasses.replace(
            self.create_base_config(assets_dirs, model_config),
            repack_transforms=repack,
            data_transforms=data_transforms,
            model_transforms=ModelTransformFactory()(model_config),
            # This dataset's action column is `action` (singular). action_sequence_keys is fed
            # straight into LeRobotDataset's delta_timestamps -- i.e. it queries the raw hf_dataset
            # column BEFORE the repack renames action -> actions. The DataConfig default is
            # ("actions",), which raises
            #   KeyError: Column actions not in the dataset
            # deep inside the dataloader worker. LeRobotAlohaDataConfig overrides it the same way.
            action_sequence_keys=("action",),
        )

'''

TRAIN_CONFIGS = '''    #
    # G1 Dex3 pick-and-place (pi0.5).
    #
    TrainConfig(
        name="pi05_g1_pickplace",
        # max_token_len is deliberately unset. For pi05, discrete_state_input defaults to True
        # and embed_suffix() skips the continuous state token, so the ONLY proprioception path
        # is the discretised state string in the prompt -- measured 120-142 tokens here. The pi0
        # default of 48 would truncate after 9 of 32 state values, keeping the left arm and
        # dropping the entire right arm and hand. Unset => the pi05 default of 200.
        model=pi0_config.Pi0Config(pi05=True, action_dim=32, action_horizon=50),
        data=LeRobotG1Dex3DataConfig(
            repo_id="{REPO_ID}",
            base_config=DataConfig(prompt_from_task=True),
        ),
        weight_loader=weight_loaders.CheckpointWeightLoader("gs://openpi-assets/checkpoints/pi05_base/params"),
        lr_schedule=_optimizer.CosineDecaySchedule(
            warmup_steps=1_000, peak_lr=5e-5, decay_steps=1_000_000, decay_lr=5e-5
        ),
        optimizer=_optimizer.AdamW(clip_gradient_norm=1.0),
        ema_decay=0.999,
        wandb_enabled=False,
        # openpi defaults num_workers to 2. Every sample decodes 3 random-access h264 frames, so
        # 2 workers deliver a batch of 32 roughly every 6.7 s -- against ~1.5 s of A100 compute,
        # that leaves the GPU ~78% idle and turns a 12 h run into 56 h. Also throttles
        # compute_norm_stats.py, which decodes all three videos per sample only to discard them.
        num_workers={NUM_WORKERS},
        num_train_steps=30_000,
        batch_size=32,
        save_interval=2_500,
        keep_period=2_500,
        log_interval=50,
        seed=0,
    ),
    # GR00T-matched: trains the action expert + all projections, freezes the PaliGemma language
    # model AND the SigLIP vision tower. get_freeze_filter() only ever freezes ".*llm.*", and the
    # tree is PaliGemma = nnx.Dict(llm=..., img=...), so a "gemma_2b_lora" variant would leave the
    # vision tower fully trainable -- hence the explicit filter.
    TrainConfig(
        name="pi05_g1_pickplace_frozen_vlm",
        model=pi0_config.Pi0Config(pi05=True, action_dim=32, action_horizon=50),
        data=LeRobotG1Dex3DataConfig(
            repo_id="{REPO_ID}",
            base_config=DataConfig(prompt_from_task=True),
        ),
        weight_loader=weight_loaders.CheckpointWeightLoader("gs://openpi-assets/checkpoints/pi05_base/params"),
        freeze_filter=nnx.All(
            nnx_utils.PathRegex(".*(llm|img).*"),
            nnx.Not(nnx_utils.PathRegex(".*llm.*_1.*")),
        ),
        ema_decay=None,
        lr_schedule=_optimizer.CosineDecaySchedule(
            warmup_steps=1_000, peak_lr=5e-5, decay_steps=1_000_000, decay_lr=5e-5
        ),
        optimizer=_optimizer.AdamW(clip_gradient_norm=1.0),
        wandb_enabled=False,
        num_workers={NUM_WORKERS},
        num_train_steps=30_000,
        batch_size=32,
        save_interval=2_500,
        keep_period=2_500,
        log_interval=50,
        seed=0,
    ),
'''


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--openpi", required=True, help="path to the openpi checkout")
    ap.add_argument("--repo-id", required=True, help="HF dataset repo id, e.g. simpk/single_pickplace")
    ap.add_argument("--num-workers", type=int, default=None,
                    help="dataloader workers. Default: max(2, nproc - 2). openpi's default of 2 "
                         "starves the GPU -- each sample needs 3 random-access h264 decodes.")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--no-verify", action="store_true",
                    help="skip the get_config() check (use if the openpi env is not synced yet)")
    a = ap.parse_args()

    if a.num_workers is None:
        a.num_workers = max(2, (os.cpu_count() or 4) - 2)

    here = pathlib.Path(__file__).resolve().parent.parent
    openpi = pathlib.Path(a.openpi).expanduser().resolve()
    cfg = openpi / "src/openpi/training/config.py"
    pol_dst = openpi / "src/openpi/policies/g1_dex3_policy.py"
    pol_src = here / "g1_dex3_policy.py"

    for p, what in ((cfg, "config.py"), (pol_src, "g1_dex3_policy.py")):
        if not p.exists():
            print(f"FAIL: {what} not found at {p}")
            return 1

    src = cfg.read_text()
    backup = cfg.with_suffix(".py.orig")
    actions = []

    # If an older revision of this patch is already in place, revert to the pristine backup and
    # re-apply from scratch. Editing in place would need a diff for every past version.
    found = None
    for line in src.splitlines():
        if line.startswith(MARKER):
            found = int(line.split(":")[1].strip())
            break
    if found is None and "class LeRobotG1Dex3DataConfig" in src:
        found = 1  # pre-marker revision of this patch
    if found is not None and found < PATCH_VERSION:
        if not backup.exists():
            print(f"FAIL: config.py carries patch v{found} but {backup.name} is missing.")
            print("      Restore config.py from git (`git checkout -- src/openpi/training/config.py`) and rerun.")
            return 1
        print(f"found patch v{found}, upgrading to v{PATCH_VERSION}: reverting to {backup.name} first")
        src = backup.read_text()
        actions.append(f"revert to pristine config.py and re-apply at v{PATCH_VERSION}")
    elif found == PATCH_VERSION:
        pass  # up to date; the checks below will all no-op

    # 1. the policy module
    need_policy = (not pol_dst.exists()) or pol_dst.read_text() != pol_src.read_text()
    if need_policy:
        actions.append(f"copy g1_dex3_policy.py -> {pol_dst.relative_to(openpi)}")

    # 2. imports, appended to the existing openpi import block
    new = src
    if "from openpi.policies import g1_dex3_policy" not in new:
        anchor = "import openpi.transforms as _transforms\n"
        if anchor not in new:
            print("FAIL: could not find the import anchor in config.py")
            return 1
        new = new.replace(anchor, anchor + f"{MARKER} {PATCH_VERSION}\n" + IMPORTS, 1)
        actions.append("add imports (nnx_utils, g1_dex3_policy)")

    # 3. the data config class, immediately before TrainConfig
    if "class LeRobotG1Dex3DataConfig" not in new:
        anchor = "@dataclasses.dataclass(frozen=True)\nclass TrainConfig:"
        if anchor not in new:
            print("FAIL: could not find the TrainConfig anchor in config.py")
            return 1
        new = new.replace(anchor, DATA_CONFIG.lstrip("\n") + "\n" + anchor, 1)
        actions.append("insert LeRobotG1Dex3DataConfig")

    # 4. the two TrainConfig entries, at the head of _CONFIGS
    if 'name="pi05_g1_pickplace"' not in new:
        anchor = "_CONFIGS = [\n"
        if anchor not in new:
            print("FAIL: could not find the _CONFIGS anchor in config.py")
            return 1
        block = TRAIN_CONFIGS.replace("{REPO_ID}", a.repo_id).replace("{NUM_WORKERS}", str(a.num_workers))
        new = new.replace(anchor, anchor + block, 1)
        actions.append(f'insert TrainConfigs (repo_id="{a.repo_id}", num_workers={a.num_workers})')

    if not actions:
        print("Already patched -- nothing to do.")
    else:
        print("planned:")
        for x in actions:
            print("  -", x)

    if a.dry_run:
        print("\n--dry-run: nothing written.")
        return 0

    if new != cfg.read_text():
        try:
            ast.parse(new)
        except SyntaxError as e:
            print(f"FAIL: patched config.py would not parse: {e}")
            return 1
        if not backup.exists():
            shutil.copy2(cfg, backup)
            print(f"backed up -> {backup.relative_to(openpi)}")
        cfg.write_text(new)
    if need_policy:
        shutil.copy2(pol_src, pol_dst)

    if a.no_verify:
        print("\npatched. Skipping verification (--no-verify). Check it yourself with:")
        print("  uv run python -c \"from openpi.training import config; "
              "print(config.get_config('pi05_g1_pickplace').name)\"")
        return 0

    # verify for real, in the openpi environment
    print("\nverifying...")
    code = (
        "from openpi.training import config\n"
        "for n in ('pi05_g1_pickplace', 'pi05_g1_pickplace_frozen_vlm'):\n"
        "    c = config.get_config(n); m = c.model\n"
        "    assert m.max_token_len >= 200, f'{n}: max_token_len={m.max_token_len} too small'\n"
        "    assert m.discrete_state_input, f'{n}: discrete_state_input is False'\n"
        "    assert m.action_dim == 32 and m.action_horizon == 50\n"
    "    d = c.data.create(c.assets_dirs, c.model)\n"
    "    assert tuple(d.action_sequence_keys) == ('action',), \\\n"
    "        f'{n}: action_sequence_keys={d.action_sequence_keys}, must be (\\'action\\',) for this dataset'\n"
        "    print(f'  {n}: action_dim={m.action_dim} horizon={m.action_horizon} "
        "max_token_len={m.max_token_len} discrete_state={m.discrete_state_input} "
        "batch={c.batch_size} ema={c.ema_decay} workers={c.num_workers} repo={c.data.repo_id}')\n"
        "print('OK')\n"
    )
    r = subprocess.run(["uv", "run", "python", "-c", code], cwd=openpi,
                       capture_output=True, text=True)
    print(r.stdout.strip() or r.stderr.strip()[-2000:])
    return r.returncode


if __name__ == "__main__":
    sys.exit(main())