Ravenh97 commited on
Commit
ed60abd
·
verified ·
1 Parent(s): 6b7846f

fridge_m setup: chunked_runner + run_gen_chunk + check_mismatch + push_watchdog

Browse files
fridge_m/_setup/scripts/add_gen_config.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Patch openpi's training/config.py to add pi05_droid_renderscale_fridge_m_h32_gen.
2
+
3
+ The new TrainConfig mirrors pi05_droid_renderscale_fridge_m_h32 (sim) but with
4
+ repo_id="fridge_m_gen". Idempotent — does nothing if the gen config already
5
+ exists. Backs the original up to config.py.before_fridge_m_gen.bak.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import shutil
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ CONFIG_PY = Path("/svl/u/ravenh/renderscale/openpi/src/openpi/training/config.py")
14
+
15
+ NEW_CONFIG = ''' TrainConfig(
16
+ # fridge_m (ithor_minimal_fridge_m) GEN run, combined from viscam3
17
+ # chunks 001-009 + viscam5 chunks 099-104. Sim h5 reused for actions
18
+ # (gen mp4s replace exo/wrist rgb). Set HF_LEROBOT_HOME=/scr/ravenh/fridge_m/lerobot_cache
19
+ # (or wherever you converted the dataset to) before launching train.py.
20
+ name="pi05_droid_renderscale_fridge_m_h32_gen",
21
+ project_name="renderscale-pi05",
22
+ model=pi0_config.Pi0Config(
23
+ pi05=True,
24
+ action_dim=32,
25
+ action_horizon=32,
26
+ paligemma_variant="gemma_2b_lora",
27
+ action_expert_variant="gemma_300m_lora",
28
+ ),
29
+ data=LeRobotMolmospacesDroidDataConfig(
30
+ repo_id="fridge_m_gen",
31
+ base_config=DataConfig(prompt_from_task=True),
32
+ ),
33
+ weight_loader=weight_loaders.CheckpointWeightLoader("gs://openpi-assets/checkpoints/pi05_droid/params"),
34
+ num_train_steps=40_000,
35
+ batch_size=16,
36
+ num_workers=4,
37
+ freeze_filter=pi0_config.Pi0Config(
38
+ pi05=True,
39
+ paligemma_variant="gemma_2b_lora",
40
+ action_expert_variant="gemma_300m_lora",
41
+ ).get_freeze_filter(),
42
+ ema_decay=None,
43
+ ),
44
+ '''
45
+
46
+ SENTINEL_GEN_NAME = 'name="pi05_droid_renderscale_fridge_m_h32_gen"'
47
+ SENTINEL_SIM_NAME = 'name="pi05_droid_renderscale_fridge_m_h32"'
48
+
49
+
50
+ def main():
51
+ src = CONFIG_PY.read_text()
52
+ if SENTINEL_GEN_NAME in src:
53
+ print(f"[add_gen_config] {SENTINEL_GEN_NAME} already present; skipping")
54
+ return
55
+ if SENTINEL_SIM_NAME not in src:
56
+ print(f"[add_gen_config] FATAL: sim sentinel not found in {CONFIG_PY}", file=sys.stderr)
57
+ sys.exit(2)
58
+
59
+ # Find the start of the sim TrainConfig and the matching closing " ),\n".
60
+ sim_idx = src.index(SENTINEL_SIM_NAME)
61
+ # Walk forward from sim_idx to find the closing " ),\n" — it's the FIRST
62
+ # line that is exactly " )," followed by newline at column 4 indent at
63
+ # the same level as the TrainConfig opener. The TrainConfig body is indented
64
+ # one level deeper (8 spaces); the closer is at 4 spaces (" ),").
65
+ tail = src[sim_idx:]
66
+ close_marker = "\n ),\n"
67
+ rel = tail.find(close_marker)
68
+ if rel < 0:
69
+ print("[add_gen_config] FATAL: could not find sim TrainConfig closing", file=sys.stderr)
70
+ sys.exit(2)
71
+ insert_at = sim_idx + rel + len(close_marker)
72
+
73
+ backup = CONFIG_PY.with_suffix(".py.before_fridge_m_gen.bak")
74
+ if not backup.exists():
75
+ shutil.copyfile(CONFIG_PY, backup)
76
+ print(f"[add_gen_config] backed up to {backup}")
77
+
78
+ new_src = src[:insert_at] + NEW_CONFIG + src[insert_at:]
79
+ CONFIG_PY.write_text(new_src)
80
+ print(f"[add_gen_config] inserted gen TrainConfig at byte offset {insert_at}")
81
+
82
+ # Sanity-check: re-find both names
83
+ after = CONFIG_PY.read_text()
84
+ assert SENTINEL_SIM_NAME in after, "sim disappeared after patch"
85
+ assert SENTINEL_GEN_NAME in after, "gen not inserted"
86
+ # Quick python parse check
87
+ import ast
88
+ try:
89
+ ast.parse(after)
90
+ print("[add_gen_config] syntax OK after patch")
91
+ except SyntaxError as e:
92
+ # Restore backup on syntax break
93
+ shutil.copyfile(backup, CONFIG_PY)
94
+ print(f"[add_gen_config] FATAL: patch broke syntax: {e}; restored backup")
95
+ sys.exit(2)
96
+
97
+
98
+ if __name__ == "__main__":
99
+ main()
fridge_m/_setup/scripts/drop_orphan_mp4s.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-shard, keep only the first N exo/wrist mp4s where N = len(valid h5
2
+ trajs). Any extras (post-SIGTERM partials) get deleted. Idempotent.
3
+
4
+ Usage:
5
+ python drop_orphan_mp4s.py --sim_dir /scr/ravenh/fridge_m/sim_chunks/chunk_009
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import re
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ import h5py
15
+
16
+
17
+ _EXO_RE = re.compile(r"^episode_(\d{8})_exo_camera_1_robot_rgb(?P<suffix>_batch_(\d+)_of_(\d+)(?:_[A-Za-z0-9_]+)?)\.mp4$")
18
+
19
+
20
+ def main():
21
+ p = argparse.ArgumentParser()
22
+ p.add_argument("--sim_dir", required=True)
23
+ args = p.parse_args()
24
+ sim_dir = Path(args.sim_dir)
25
+ if not sim_dir.exists():
26
+ print(f"no such dir: {sim_dir}", file=sys.stderr); sys.exit(1)
27
+
28
+ # Group exo mp4s by shard suffix.
29
+ by_shard: dict[str, list[tuple[int, Path]]] = {}
30
+ for f in sim_dir.iterdir():
31
+ if not f.is_file():
32
+ continue
33
+ m = _EXO_RE.match(f.name)
34
+ if not m:
35
+ continue
36
+ ep = int(m.group(1))
37
+ suffix = m.group("suffix")
38
+ by_shard.setdefault(suffix, []).append((ep, f))
39
+
40
+ if not by_shard:
41
+ print(f"no exo mp4s in {sim_dir}")
42
+ return
43
+
44
+ total_dropped = 0
45
+ for suffix, items in by_shard.items():
46
+ items.sort()
47
+ h5_name = f"trajectories_{suffix.lstrip('_')}.h5"
48
+ h5_path = sim_dir / h5_name
49
+ if not h5_path.exists():
50
+ print(f" shard {suffix}: NO h5 ({h5_path.name}); dropping ALL {len(items)} mp4s")
51
+ for ep, fp in items:
52
+ # also drop sibling cams
53
+ for cam_suffix in ("_exo_camera_1_robot_rgb", "_exo_camera_1_seg",
54
+ "_exo_camera_1",
55
+ "_wrist_camera_robot_rgb", "_wrist_camera_seg",
56
+ "_wrist_camera"):
57
+ sib = sim_dir / f"episode_{ep:08d}{cam_suffix}{suffix}.mp4"
58
+ if sib.exists():
59
+ sib.unlink()
60
+ total_dropped += 1
61
+ continue
62
+ with h5py.File(h5_path, "r") as f:
63
+ valid = []
64
+ for k in f.keys():
65
+ if not k.startswith("traj_"):
66
+ continue
67
+ grp = f[k]
68
+ if "obs/agent/qpos" in grp and grp["obs/agent/qpos"].shape[0] > 0:
69
+ valid.append(int(k.split("_", 1)[1]))
70
+ n_valid = len(valid)
71
+ n_mp4 = len(items)
72
+ keep = items[:n_valid]
73
+ drop = items[n_valid:]
74
+ print(f" shard {suffix}: h5_valid={n_valid} exo_mp4s={n_mp4} keep={len(keep)} drop={len(drop)}")
75
+ for ep, fp in drop:
76
+ for cam_suffix in ("_exo_camera_1_robot_rgb", "_exo_camera_1_seg",
77
+ "_exo_camera_1",
78
+ "_wrist_camera_robot_rgb", "_wrist_camera_seg",
79
+ "_wrist_camera"):
80
+ sib = sim_dir / f"episode_{ep:08d}{cam_suffix}{suffix}.mp4"
81
+ if sib.exists():
82
+ sib.unlink()
83
+ total_dropped += 1
84
+ print(f"dropped {total_dropped} orphan files total")
85
+
86
+
87
+ if __name__ == "__main__":
88
+ main()
fridge_m/_setup/scripts/lerobot_sim_convert_push.sh ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Waits for `chunk 9 sim done` in the ext-sf log, then converts all 9 sim
3
+ # chunks into a single LeRobot dataset and uploads to
4
+ # Ravenh97/lerobot_data:fridge_m_sim/. CPU-only — runs in parallel with chunks
5
+ # 8/9 video gen on the GPUs.
6
+ #
7
+ # Per-chunk conversion via --append (chunk 1 uses --overwrite to create fresh),
8
+ # which avoids the episode-id collision that would happen if we symlinked all
9
+ # chunks' mp4s into one flat dir.
10
+ #
11
+ # Output local: $HF_LEROBOT_HOME/<LOCAL_REPO>/ (we point HF_LEROBOT_HOME at
12
+ # /scr so writes don't hit NFS).
13
+ #
14
+ # Target HF: Ravenh97/lerobot_data path_in_repo=fridge_m_sim/
15
+
16
+ set -uo pipefail
17
+
18
+ EXT_SF_LOG=${EXT_SF_LOG:-/scr/ravenh/fridge_m/logs/extend_chunks_89_simfirst.log}
19
+ LEROBOT_HOME=${LEROBOT_HOME:-/scr/ravenh/fridge_m/lerobot_cache}
20
+ LOCAL_REPO=${LOCAL_REPO:-fridge_m_sim_local}
21
+ TARGET_REPO=${TARGET_REPO:-Ravenh97/lerobot_data}
22
+ TARGET_PATH=${TARGET_PATH:-fridge_m_sim}
23
+ SIM_CHUNKS=/scr/ravenh/fridge_m/sim_chunks
24
+ CONVERTER=/svl/u/ravenh/renderscale/openpi/examples/molmospaces/convert_molmodata_to_lerobot.py
25
+ OPENPI_VENV=/svl/u/ravenh/renderscale/openpi/.venv
26
+ LOGS=/scr/ravenh/fridge_m/logs
27
+
28
+ mkdir -p "$LEROBOT_HOME" "$LOGS"
29
+ export HF_LEROBOT_HOME="$LEROBOT_HOME"
30
+
31
+ echo "[lerobot-sim] waiting for 'chunk 9 sim done' in $EXT_SF_LOG ..."
32
+ # Wait until the marker appears.
33
+ until grep -q 'chunk 9 sim done' "$EXT_SF_LOG" 2>/dev/null; do sleep 30; done
34
+ echo "[lerobot-sim] chunk 9 sim done detected at $(date -Iseconds)"
35
+
36
+ # Activate the openpi venv (has h5py / lerobot / tyro / cv2).
37
+ source "$OPENPI_VENV/bin/activate" 2>/dev/null || {
38
+ echo "[lerobot-sim] FATAL: failed to activate openpi venv at $OPENPI_VENV"
39
+ exit 2
40
+ }
41
+ echo "[lerobot-sim] python: $(which python)"
42
+ python -c "import lerobot, h5py, cv2; print(' lerobot=', lerobot.__version__)" 2>&1 | head -5
43
+
44
+ # Sanity: confirm we can see all 9 chunks
45
+ for n in 1 2 3 4 5 6 7 8 9; do
46
+ d="$SIM_CHUNKS/chunk_$(printf '%03d' $n)"
47
+ if [ ! -d "$d" ]; then
48
+ echo "[lerobot-sim] FATAL: missing $d"
49
+ exit 2
50
+ fi
51
+ cnt=$(ls "$d"/episode_*_exo_camera_1_robot_rgb*.mp4 2>/dev/null | wc -l)
52
+ echo "[lerobot-sim] chunk $n -> $d ($cnt trajs)"
53
+ done
54
+
55
+ # Wipe any prior local dataset for this run
56
+ if [ -d "$LEROBOT_HOME/$LOCAL_REPO" ]; then
57
+ echo "[lerobot-sim] removing prior $LEROBOT_HOME/$LOCAL_REPO"
58
+ rm -rf "$LEROBOT_HOME/$LOCAL_REPO"
59
+ fi
60
+
61
+ # Convert chunk 1 with --overwrite (creates the dataset)
62
+ echo "[lerobot-sim] converting chunk 1 (--overwrite) at $(date -Iseconds)"
63
+ python "$CONVERTER" \
64
+ --data_dir "$SIM_CHUNKS/chunk_001" \
65
+ --repo_id "$LOCAL_REPO" \
66
+ --overwrite 2>&1 | tee "$LOGS/lerobot_sim_chunk_001.log"
67
+
68
+ # Convert chunks 2..9 with --append
69
+ for n in 2 3 4 5 6 7 8 9; do
70
+ echo "[lerobot-sim] converting chunk $n (--append) at $(date -Iseconds)"
71
+ python "$CONVERTER" \
72
+ --data_dir "$SIM_CHUNKS/chunk_$(printf '%03d' $n)" \
73
+ --repo_id "$LOCAL_REPO" \
74
+ --append 2>&1 | tee "$LOGS/lerobot_sim_chunk_$(printf '%03d' $n).log"
75
+ done
76
+
77
+ echo "[lerobot-sim] all chunks converted; computing size..."
78
+ du -sh "$LEROBOT_HOME/$LOCAL_REPO"
79
+
80
+ # Upload to HF
81
+ echo "[lerobot-sim] uploading to $TARGET_REPO:$TARGET_PATH at $(date -Iseconds)"
82
+ python -u -c "
83
+ import huggingface_hub.constants as cc
84
+ cc.DEFAULT_REQUEST_TIMEOUT = 600
85
+ from huggingface_hub import HfApi
86
+ import time
87
+ api = HfApi()
88
+ api.create_repo('$TARGET_REPO', repo_type='dataset', exist_ok=True)
89
+ t0 = time.time()
90
+ api.upload_folder(
91
+ folder_path='$LEROBOT_HOME/$LOCAL_REPO',
92
+ repo_id='$TARGET_REPO',
93
+ repo_type='dataset',
94
+ path_in_repo='$TARGET_PATH',
95
+ commit_message='fridge_m sim lerobot conversion (chunks 1-9, ~450 trajs)',
96
+ )
97
+ print(f'upload done in {time.time()-t0:.1f}s')
98
+ " 2>&1 | tee -a "$LOGS/lerobot_sim_upload.log"
99
+
100
+ echo "[lerobot-sim] DONE at $(date -Iseconds)"
fridge_m/_setup/scripts/post_gen_lerobot_pipeline.sh ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Run after the chunks 8/9 ext-sf pipeline finishes (gen 8 + gen 9 + final flush).
3
+ #
4
+ # 1. Download viscam5's sim h5s + gen mp4s (chunks 099-104) from HF.
5
+ # 2. Stage all chunks (mine 001-009 + viscam5 099-104) into per-chunk dirs with
6
+ # gen mp4s renamed to drop "generated_" prefix (what the converter expects).
7
+ # 3. Run convert_molmodata_generated_to_lerobot.py per chunk (--overwrite then
8
+ # --append) into local repo "fridge_m_gen".
9
+ # 4. Upload the lerobot dataset to Ravenh97/lerobot_data:fridge_m_gen/.
10
+ # 5. Add the pi05_droid_renderscale_fridge_m_h32_gen TrainConfig to openpi's
11
+ # config.py (mirrors the existing fridge_m_h32 sim config).
12
+ # 6. Run scripts/compute_norm_stats.py for that config.
13
+ # 7. Push the resulting norm_stats.json to HF (alongside the lerobot dataset).
14
+
15
+ set -uo pipefail
16
+
17
+ EXT_SF_PID=${EXT_SF_PID:-1695075}
18
+ ROOT=/scr/ravenh/fridge_m
19
+ SCRIPTS=$ROOT/scripts
20
+ LOGS=$ROOT/logs
21
+ SIM_CHUNKS=$ROOT/sim_chunks # my sim chunks (001..009)
22
+ GEN_CHUNKS=$ROOT/gen_chunks # my gen chunks (001..009)
23
+ VISCAM5_DL=$ROOT/viscam5_dl # downloaded viscam5 chunks
24
+ STAGING=$ROOT/lerobot_staging # per-chunk staged dirs for converter
25
+ LEROBOT_HOME=$ROOT/lerobot_cache # local HF_LEROBOT_HOME (avoids NFS)
26
+ LOCAL_REPO=fridge_m_gen # local LeRobotDataset repo id
27
+ TARGET_REPO=Ravenh97/lerobot_data
28
+ TARGET_PATH=fridge_m_gen
29
+ CONVERTER=/svl/u/ravenh/renderscale/openpi/examples/molmospaces/convert_molmodata_generated_to_lerobot.py
30
+ OPENPI=/svl/u/ravenh/renderscale/openpi
31
+ OPENPI_VENV=$OPENPI/.venv
32
+ CONFIG_NAME=pi05_droid_renderscale_fridge_m_h32_gen
33
+
34
+ mkdir -p "$VISCAM5_DL" "$STAGING" "$LEROBOT_HOME" "$LOGS"
35
+ export HF_LEROBOT_HOME="$LEROBOT_HOME"
36
+
37
+ # Activate openpi venv (has h5py / lerobot / tyro / cv2 / huggingface_hub).
38
+ source "$OPENPI_VENV/bin/activate" 2>/dev/null || { echo "[post-gen] FATAL: no openpi venv"; exit 2; }
39
+ echo "[post-gen] python: $(which python)"
40
+ python -c "import lerobot, h5py, cv2, openpi; print(' lerobot=', lerobot.__version__)" 2>&1 | head -3 || echo "[post-gen] WARN: openpi imports failed (will retry)"
41
+
42
+ # ---- Phase 1: wait for ext-sf to fully exit ----
43
+ echo "[post-gen] waiting for ext-sf pid=$EXT_SF_PID ..."
44
+ while kill -0 "$EXT_SF_PID" 2>/dev/null; do sleep 60; done
45
+ echo "[post-gen] ext-sf exited at $(date -Iseconds)"
46
+
47
+ # ---- Phase 2: download viscam5 chunks ----
48
+ echo "[post-gen] downloading viscam5 chunks 099-104 from HF ..."
49
+ python - <<'PY'
50
+ import os, time
51
+ from pathlib import Path
52
+ import huggingface_hub.constants as cc
53
+ cc.DEFAULT_REQUEST_TIMEOUT = 600
54
+ from huggingface_hub import snapshot_download
55
+
56
+ V5 = Path("/scr/ravenh/fridge_m/viscam5_dl")
57
+ V5.mkdir(parents=True, exist_ok=True)
58
+
59
+ CHUNKS = [99, 100, 101, 102, 103, 104]
60
+
61
+ # Download sim h5 + key mp4s per chunk; skip irrelevant cams (seg/depth/etc).
62
+ for c in CHUNKS:
63
+ sub = f"chunk_{c:03d}"
64
+ print(f" sim {sub} ...", flush=True)
65
+ t0 = time.time()
66
+ snapshot_download(
67
+ repo_id="Ravenh97/sim_data",
68
+ repo_type="dataset",
69
+ local_dir=str(V5),
70
+ allow_patterns=[
71
+ f"fridge_m/sim_chunks/{sub}/trajectories_batch_*.h5",
72
+ ],
73
+ )
74
+ print(f" h5 OK in {time.time()-t0:.1f}s", flush=True)
75
+
76
+ for c in CHUNKS:
77
+ sub = f"chunk_{c:03d}"
78
+ print(f" gen {sub} ...", flush=True)
79
+ t0 = time.time()
80
+ snapshot_download(
81
+ repo_id="Ravenh97/generated_video",
82
+ repo_type="dataset",
83
+ local_dir=str(V5),
84
+ allow_patterns=[
85
+ f"fridge_m/gen_chunks/{sub}/generated_episode_*_exo_camera_1_batch_*.mp4",
86
+ f"fridge_m/gen_chunks/{sub}/generated_episode_*_wrist_camera_batch_*.mp4",
87
+ ],
88
+ )
89
+ print(f" mp4 OK in {time.time()-t0:.1f}s", flush=True)
90
+ print("download done")
91
+ PY
92
+ echo "[post-gen] viscam5 download done at $(date -Iseconds)"
93
+
94
+ # ---- Phase 3: stage each chunk with renamed gen mp4s ----
95
+ echo "[post-gen] staging per-chunk dirs at $(date -Iseconds)"
96
+ stage_chunk() {
97
+ local label=$1 # e.g. "mine_001" or "v5_099"
98
+ local sim_dir=$2 # absolute path containing trajectories_batch_*.h5
99
+ local gen_dir=$3 # absolute path containing generated_episode_*.mp4
100
+ local out="$STAGING/$label"
101
+ rm -rf "$out"
102
+ mkdir -p "$out"
103
+ # Symlink h5 shards
104
+ for h5 in "$sim_dir"/trajectories_batch_*.h5; do
105
+ [ -f "$h5" ] || continue
106
+ ln -s "$h5" "$out/$(basename "$h5")"
107
+ done
108
+ # Symlink gen mp4s with renamed (drop "generated_" prefix)
109
+ for mp4 in "$gen_dir"/generated_episode_*_exo_camera_1_batch_*.mp4 \
110
+ "$gen_dir"/generated_episode_*_wrist_camera_batch_*.mp4; do
111
+ [ -f "$mp4" ] || continue
112
+ new_name=$(basename "$mp4" | sed 's/^generated_//')
113
+ ln -s "$mp4" "$out/$new_name"
114
+ done
115
+ local nh5=$(ls "$out"/trajectories_batch_*.h5 2>/dev/null | wc -l)
116
+ local nexo=$(ls "$out"/episode_*_exo_camera_1_batch_*.mp4 2>/dev/null | wc -l)
117
+ local nwri=$(ls "$out"/episode_*_wrist_camera_batch_*.mp4 2>/dev/null | wc -l)
118
+ echo " $label: h5=$nh5 exo=$nexo wrist=$nwri"
119
+ }
120
+
121
+ # Mine: chunks 001..009
122
+ for n in 1 2 3 4 5 6 7 8 9; do
123
+ s=$(printf '%03d' $n)
124
+ stage_chunk "mine_$s" "$SIM_CHUNKS/chunk_$s" "$GEN_CHUNKS/chunk_$s"
125
+ done
126
+
127
+ # viscam5: chunks 099..104
128
+ for n in 99 100 101 102 103 104; do
129
+ s=$(printf '%03d' $n)
130
+ stage_chunk "v5_$s" \
131
+ "$VISCAM5_DL/fridge_m/sim_chunks/chunk_$s" \
132
+ "$VISCAM5_DL/fridge_m/gen_chunks/chunk_$s"
133
+ done
134
+
135
+ # ---- Phase 4: run converter per stage ----
136
+ echo "[post-gen] removing prior local lerobot $LEROBOT_HOME/$LOCAL_REPO"
137
+ rm -rf "$LEROBOT_HOME/$LOCAL_REPO"
138
+
139
+ # Track which chunks succeed / fail. First successful uses --overwrite; the rest
140
+ # use --append. On failure (e.g., bad h5 / missing mp4), log + continue.
141
+ declare -a SUCCEEDED_CHUNKS=()
142
+ declare -a FAILED_CHUNKS=()
143
+ need_overwrite=1
144
+ for stage in "$STAGING"/mine_001 "$STAGING"/mine_002 "$STAGING"/mine_003 \
145
+ "$STAGING"/mine_004 "$STAGING"/mine_005 "$STAGING"/mine_006 \
146
+ "$STAGING"/mine_007 "$STAGING"/mine_008 "$STAGING"/mine_009 \
147
+ "$STAGING"/v5_099 "$STAGING"/v5_100 "$STAGING"/v5_101 \
148
+ "$STAGING"/v5_102 "$STAGING"/v5_103 "$STAGING"/v5_104; do
149
+ base=$(basename "$stage")
150
+ if [ ! -d "$stage" ]; then
151
+ echo "[post-gen] skipping $base: no staging dir"
152
+ FAILED_CHUNKS+=("$base:no_stage")
153
+ continue
154
+ fi
155
+ if [ "$need_overwrite" = "1" ]; then
156
+ mode_flag=--overwrite
157
+ else
158
+ mode_flag=--append
159
+ fi
160
+ echo "[post-gen] converting $base $mode_flag at $(date -Iseconds)"
161
+ # Don't pipe through tee — that masks the converter's exit code. Redirect to log directly.
162
+ if python "$CONVERTER" --data_dir "$stage" --repo_id "$LOCAL_REPO" "$mode_flag" \
163
+ > "$LOGS/lerobot_gen_${base}.log" 2>&1; then
164
+ echo "[post-gen] OK $base"
165
+ SUCCEEDED_CHUNKS+=("$base")
166
+ need_overwrite=0
167
+ else
168
+ rc=$?
169
+ echo "[post-gen] FAIL $base (rc=$rc) -- continuing"
170
+ tail -20 "$LOGS/lerobot_gen_${base}.log" | sed 's/^/ /'
171
+ FAILED_CHUNKS+=("$base:rc=$rc")
172
+ # If the first chunk failed (no dataset created), the NEXT attempt must
173
+ # still use --overwrite to create it.
174
+ # need_overwrite stays 1 in that case.
175
+ fi
176
+ done
177
+
178
+ echo "[post-gen] conversion summary:"
179
+ echo " succeeded (${#SUCCEEDED_CHUNKS[@]}): ${SUCCEEDED_CHUNKS[*]:-none}"
180
+ echo " failed (${#FAILED_CHUNKS[@]}): ${FAILED_CHUNKS[*]:-none}"
181
+ if [ ${#SUCCEEDED_CHUNKS[@]} -eq 0 ]; then
182
+ echo "[post-gen] FATAL: no chunks converted successfully; aborting before upload"
183
+ exit 2
184
+ fi
185
+
186
+ echo "[post-gen] conversion done at $(date -Iseconds); local size:"
187
+ du -sh "$LEROBOT_HOME/$LOCAL_REPO"
188
+
189
+ # ---- Phase 5: upload lerobot to HF ----
190
+ echo "[post-gen] uploading lerobot to $TARGET_REPO:$TARGET_PATH at $(date -Iseconds)"
191
+ python - <<PY
192
+ import huggingface_hub.constants as cc
193
+ cc.DEFAULT_REQUEST_TIMEOUT = 600
194
+ from huggingface_hub import HfApi
195
+ import time
196
+ api = HfApi()
197
+ api.create_repo("$TARGET_REPO", repo_type="dataset", exist_ok=True)
198
+ t0 = time.time()
199
+ api.upload_folder(
200
+ folder_path="$LEROBOT_HOME/$LOCAL_REPO",
201
+ repo_id="$TARGET_REPO",
202
+ repo_type="dataset",
203
+ path_in_repo="$TARGET_PATH",
204
+ commit_message="fridge_m gen lerobot (mine chunks 1-9 + viscam5 99-104)",
205
+ )
206
+ print(f"lerobot upload done in {time.time()-t0:.1f}s")
207
+ PY
208
+
209
+ # ---- Phase 6: add gen TrainConfig to openpi config.py ----
210
+ echo "[post-gen] patching openpi config.py at $(date -Iseconds)"
211
+ python "$SCRIPTS/add_gen_config.py" || { echo "[post-gen] FATAL: config patch failed"; exit 2; }
212
+
213
+ # ---- Phase 7: symlink sim norm stats over (sim+gen share h5 → same actions
214
+ # → identical norm stats). Mirrors the fridge_7_gen pattern.
215
+ SIM_NORM=$OPENPI/assets/pi05_droid_renderscale_fridge_m_h32/fridge_m_sim/norm_stats.json
216
+ GEN_NORM_DIR=$OPENPI/assets/$CONFIG_NAME/fridge_m_gen
217
+ GEN_NORM=$GEN_NORM_DIR/norm_stats.json
218
+ echo "[post-gen] linking sim norm_stats -> gen at $(date -Iseconds)"
219
+ if [ ! -f "$SIM_NORM" ]; then
220
+ echo "[post-gen] FATAL: sim norm_stats missing at $SIM_NORM"
221
+ exit 2
222
+ fi
223
+ mkdir -p "$GEN_NORM_DIR"
224
+ ln -sf "$SIM_NORM" "$GEN_NORM"
225
+ ls -la "$GEN_NORM"
226
+
227
+ # ---- Phase 8: push norm stats to HF ----
228
+ echo "[post-gen] uploading norm stats to $TARGET_REPO:$TARGET_PATH/_assets/ at $(date -Iseconds)"
229
+ python - <<PY
230
+ import huggingface_hub.constants as cc
231
+ cc.DEFAULT_REQUEST_TIMEOUT = 300
232
+ from huggingface_hub import HfApi
233
+ import time
234
+ api = HfApi()
235
+ t0 = time.time()
236
+ # Upload the dereferenced file (symlink target's content) — HF Hub stores the
237
+ # bytes, not the symlink, so the consumer just sees a regular file.
238
+ api.upload_file(
239
+ path_or_fileobj="$GEN_NORM",
240
+ path_in_repo="$TARGET_PATH/_assets/$CONFIG_NAME/fridge_m_gen/norm_stats.json",
241
+ repo_id="$TARGET_REPO",
242
+ repo_type="dataset",
243
+ commit_message="fridge_m gen norm_stats (copy of fridge_m_sim — sim+gen share actions)",
244
+ )
245
+ print(f"norm stats upload done in {time.time()-t0:.1f}s")
246
+ PY
247
+
248
+ echo "[post-gen] DONE at $(date -Iseconds)"