single_pickplace / scripts /patch_openpi_config.py
simpk's picture
Update runbook and tooling
c675012 verified
Raw History Blame Contribute Delete
12.8 kB
"""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())