File size: 18,454 Bytes
b26bdfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Phase 2 launcher: one registry entry per run (Parts A–C), exact commands, one folder per run.

  python3 experiments/lerobot/run.py --list
  python3 experiments/lerobot/run.py A3 --dry-run          # print the exact commands
  python3 experiments/lerobot/run.py A3 [--steps 10000] [--trials 10] [--suites libero_spatial,libero_object]
  python3 experiments/lerobot/run.py A3 --smoke             # 20 train steps + 1 episode: plumbing check only

Results: experiments/results/phase2/<RUN>_<UTC>/{run.json, train.log, train/, eval_<suite>/eval_info.json}
Reduced protocol (default, chosen 2026-11-25): train on all 40 LIBERO tasks, 10k steps, evaluate libero_spatial +
libero_object with 10 trials per task. Scale --steps/--trials/--suites up for the full protocol.
"""
import argparse
import json
import os
import shutil
import subprocess
import sys
import time
from datetime import UTC, datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
HERE = Path(__file__).resolve().parent
PY = Path(os.environ.get("COURSE_PY", ROOT / "envs/lerobot/.venv/bin/python"))  # Modal: the image's python
A = HERE / "assets"
# smolvla_base was pre-trained with cameras camera1..3; LIBERO provides image (agentview) + image2 (wrist).
# Same map at train and eval time; SmolVLA skips the absent camera3. (C5 trains from scratch: no rename needed.)
RENAME = '--rename_map={"observation.images.image": "observation.images.camera1", "observation.images.image2": "observation.images.camera2"}'
SMOL_BATCH = 16  # largest that fits full fine-tuning (C4) on 16 GB; kept equal for every SmolVLA run
SMOL = ["--policy.type=smolvla", "--policy.pretrained_path=lerobot/smolvla_base", f"--batch_size={SMOL_BATCH}", RENAME]

GOAL_EPISODES = "--dataset.episodes=" + json.dumps(json.loads((A / "libero_goal_episodes.json").read_text())).replace(" ", "")
SUITES = {"G0": "libero_goal,libero_spatial", "G1": "libero_goal,libero_spatial"}  # default otherwise: --suites

# Actions executed per prediction at eval time, fixed for every run (B8 uses its own 26->20 rule). LeRobot's default
# executes the whole 50-action chunk open-loop; HuggingFaceVLA/smolvla_libero used 1 (re-plan every step). Published
# SmolVLA LIBERO numbers are sensitive to this, so it is recorded in run.json and kept equal across runs.
EXEC_STEPS = 10

# id: (title, part, wrapper args, extra lerobot-train args, eval wrapper args, what it teaches)
RUNS = {
    "A1": ("ACT (no language)", "A", [], ["--policy.type=act", "--batch_size=32"], [],
           "Action chunking + CVAE from scratch. No language input, so with 40 tasks it cannot know WHICH task."),
    "A2": ("Diffusion Policy (no language)", "A", [], ["--policy.type=diffusion", "--batch_size=32"], [],
           "DDPM denoising of action sequences from scratch; contrast with flow matching."),
    "A3": ("SmolVLA fine-tune (= B0 = C1)", "A", [], SMOL, [],
           "Small VLA: frozen SmolVLM2 + trained flow-matching expert; language-conditioned."),
    "B1": ("+ correlated noise", "B", ["--corr-noise", str(A / "libero_chunk_L.pt")], SMOL,
           ["--corr-noise", str(A / "libero_chunk_L.pt")], "Noise shaped like real action chunks (β=0.5)."),
    "B2": ("task ids instead of language", "B", ["--task-ids", str(A / "libero_task_ids.json")], SMOL,
           ["--task-ids", str(A / "libero_task_ids.json")], "Does the language path matter, or only task identity?"),
    "B3": ("+ stage token, stage head, voting tracker", "B", ["--stage", str(A / "libero_task_ids.json")], SMOL,
           ["--stage", str(A / "libero_task_ids.json")],
           "System 2: 5 equal-time stages per demo, a stage head on the VLM, 2-of-3 voting at run time."),
    "B4": ("+ FAST auxiliary loss (on C3: LM trainable)", "B", ["--fast-aux", str(A / "fast_tokenizer")],
           SMOL + ["--policy.freeze_vision_encoder=true", "--policy.train_expert_only=false"], [],
           "Teach the VLM to predict tokenised action chunks (weight 0.1). Compare with C3, not A3."),
    "B5": ("+ multi-sample flow matching K=8", "B", ["--multisample", "8"], SMOL, [],
           "8 noise/time draws per VLM pass: lower-variance gradients at small extra cost."),
    "B6": ("+ mixed-layer KV", "B", ["--kv-mix"], SMOL, ["--kv-mix"],
           "Expert attends to learned mixes of all VLM layers, not one layer each (identity init)."),
    "B7": ("+ correlated inpainting (eval only, reuses B1)", "B", None, None,
           ["--corr-noise", str(A / "libero_chunk_L.pt"), "--inpaint", str(A / "libero_chunk_L.pt")],
           "Pin the 4 actions the previous chunk planned next; correct the rest through Σ. Compare with B1."),
    "B8": ("+ action compression 26->20 (eval only, reuses A3)", "B", None, None, ["--compress", "26", "20"],
           "Execute 26 predicted actions in 20 steps: faster episodes; does success drop?"),
    "B9": ("+ gripper retry rule (eval only, reuses A3)", "B", None, None, ["--gripper-retry"],
           "LIBERO analogue of the correction rules: reopen after a grasp closed on nothing, then retry."),
    # Everything that composes on a frozen-VLM SmolVLA, the closest this course gets to the full PiBehavior recipe
    # (which replaced language with task embeddings, hence B2). Left out: B4 (needs the LM trainable and its own
    # forward; not yet merged with B3's) and B8 (a speed trick, not accuracy).
    "D1": ("PiBehavior-lite combined: B1+B2+B3+B5+B6 (train), B7+B9 (eval)", "D",
           ["--corr-noise", str(A / "libero_chunk_L.pt"), "--task-ids", str(A / "libero_task_ids.json"),
            "--multisample", "8", "--kv-mix", "--stage", str(A / "libero_task_ids.json")], SMOL,
           ["--corr-noise", str(A / "libero_chunk_L.pt"), "--task-ids", str(A / "libero_task_ids.json"),
            "--kv-mix", "--inpaint", str(A / "libero_chunk_L.pt"),
            "--stage", str(A / "libero_task_ids.json"), "--gripper-retry"],
           "All composable additions at once, as the winning entry used them. Compare with A3."),
    # Part G: GeCO reproduction (NeurIPS 2026, arXiv 2603.17834, Table 5). Both trained on LIBERO-Goal only (dataset
    # tasks 10-19); evaluated on libero_goal (in distribution) and libero_spatial (out of distribution).
    "G0": ("Goal-only SmolVLA, flow-matching-loss OOD score (GeCO baseline)", "G", [], SMOL + [GOAL_EPISODES],
           ["--fm-score"], "Baseline detector: one-sample flow-matching loss of the policy's own chunk."),
    "G1": ("Goal-only SmolVLA trained with GeCO, residual-norm OOD score", "G", ["--geco"], SMOL + [GOAL_EPISODES],
           ["--geco"], "Time-unconditional flow matching: expert actions are zeros of the field; ‖f‖ flags OOD."),
    "C2": ("train vision encoder, freeze LM", "C", ["--variant", "vision_only"], SMOL, [],
           "Do the robot's 'eyes' need adapting?"),
    "C3": ("train LM, freeze vision", "C", [], SMOL + ["--policy.freeze_vision_encoder=true",
                                                          "--policy.train_expert_only=false"], [],
           "Does the 'reasoning' part need adapting?"),
    "C4": ("train everything", "C", [], SMOL + ["--policy.freeze_vision_encoder=false",
                                                   "--policy.train_expert_only=false"], [],
           "Full fine-tune: most capacity, most risk of forgetting/overfitting."),
    "C5": ("no internet pre-training (VLM random init)", "C", [],
           # batch 8: from-scratch C5 at batch 16 exhausted 16 GB and spilled to shared memory (~94 s/step) in the
           # 2026-11-26 smoke check. Compare with C1-C4 per sample seen, not per step.
           ["--policy.type=smolvla", "--policy.load_vlm_weights=false", "--batch_size=8",
            "--policy.freeze_vision_encoder=false", "--policy.train_expert_only=false"], [],
           "What does web-scale pre-training buy? Same architecture from scratch."),
}


def ensure_libero_config():
    """LeRobot's LIBERO package prompts interactively on first import unless config.yaml exists. Write the defaults."""
    cfg_dir = ROOT / "envs/lerobot/libero_config"
    if (cfg_dir / "config.yaml").exists():
        return
    pkg = subprocess.run([str(PY), "-c", "import importlib.util,os;print(os.path.dirname(importlib.util.find_spec('libero').origin))"],
                         capture_output=True, text=True).stdout.strip().splitlines()[-1] + "/libero"
    cfg_dir.mkdir(parents=True, exist_ok=True)
    (cfg_dir / "config.yaml").write_text("\n".join(f"{k}: {pkg}/{v}" for k, v in [
        ("assets", "assets"), ("bddl_files", "bddl_files"), ("benchmark_root", ""), ("datasets", "../datasets"),
        ("init_states", "init_files")]) + "\n")


def prune_checkpoints(ckdir: Path):
    """Delete checkpoints older than the one `last` points to (each SmolVLA checkpoint is ~1.6 GB).

    Only older ones: a newer directory is a checkpoint LeRobot is still writing (it moves `last` after the save),
    and deleting it mid-save crashed training with a safetensors "No such file or directory" error."""
    last = ckdir / "last"
    if not last.is_symlink():
        return
    keep = int(last.resolve().name)
    for d in ckdir.iterdir():
        if d.is_dir() and not d.is_symlink() and d.name.isdigit() and int(d.name) < keep:
            shutil.rmtree(d, ignore_errors=True)


def execute(run, meta, cmds, wargs, max_retries, resume_train=False, only=None):
    # LIBERO asks an interactive question on first import unless a config exists; assets download on first use.
    gl = os.environ.get("MUJOCO_GL")
    env = dict(os.environ, MUJOCO_GL=gl if gl in ("egl", "osmesa") else "glx",
               DISPLAY=os.environ.get("DISPLAY", ":0"), LIBERO_CONFIG_PATH=str(ROOT / "envs/lerobot/libero_config"))
    for name, c in cmds:
        if only and name not in only:
            continue  # Modal: training and each suite's eval run in separate containers
        if meta.get("returncodes", {}).get(name) == 0:
            continue  # finished in an earlier launch
        attempt, rc = 0, None
        last = run / "train/checkpoints/last/pretrained_model/train_config.json"
        if name == "train" and resume_train and last.exists():
            attempt, c = meta.get("attempts", {}).get(name, 1), [str(PY), str(HERE / "train_variant.py"), *wargs,
                                                                  "--", f"--config_path={last}", "--resume=true"]
            max_retries += attempt
        elif name != "train":
            shutil.rmtree(run / name, ignore_errors=True)  # a partial eval from an earlier launch
        while True:
            with open(run / f"{name}.log", "a") as log:
                if attempt:
                    log.write(f"\n===== retry {attempt} at {datetime.now(UTC):%Y-%m-%dT%H:%M:%SZ}: {' '.join(c)}\n")
                    log.flush()
                proc = subprocess.Popen(c, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, env=env)
                while (rc := proc.poll()) is None:
                    time.sleep(60)
                    if name == "train":
                        prune_checkpoints(run / "train/checkpoints")
            meta.setdefault("attempts", {})[name] = attempt + 1
            if not rc or attempt >= max_retries:
                break
            attempt += 1
            time.sleep(90)  # let the GPU recover after a device fault
            if name == "train":
                last = run / "train/checkpoints/last/pretrained_model/train_config.json"
                if last.exists():  # resume from the newest checkpoint (LeRobot restores optimiser + step)
                    c = [str(PY), str(HERE / "train_variant.py"), *wargs, "--", f"--config_path={last}",
                         "--resume=true"]
                else:  # crashed before the first checkpoint: start over in a clean directory
                    shutil.rmtree(run / "train", ignore_errors=True)
            else:
                shutil.rmtree(run / name, ignore_errors=True)
        if name == "train":
            prune_checkpoints(run / "train/checkpoints")
        meta.setdefault("returncodes", {})[name] = rc
        (run / "run.json").write_text(json.dumps(meta, indent=2))
        if rc:
            sys.exit(f"{name} failed (rc={rc}) after {attempt + 1} attempts; see {run / f'{name}.log'}")


def geco_kmax_phases(cmds, kmaxes):
    """Extra GeCO evaluations of a trained G1 folder with K_max = k iterations (the paper's App. D uses 10):
    phase eval_<suite>_k<k>, the same command with --geco-kmax k and its own output folder."""
    extra = []
    for k in kmaxes:
        for name, c in cmds:
            if name.startswith("eval_") and "--geco" in c and "_k" not in name:
                i = c.index("--geco")
                c2 = c[:i + 1] + ["--geco-kmax", str(k)] + c[i + 1:]
                c2 = [f"{x}_k{k}" if x.startswith("--output_dir=") else x for x in c2]
                extra.append((f"{name}_k{k}", c2))
    return extra


def resume_run(run, max_retries, only=None, geco_kmax=()):
    meta = json.loads((run / "run.json").read_text())
    wargs = RUNS[meta["run"]][2]
    cmds = list(meta["commands"].items())
    known = {n for n, _ in cmds}
    cmds += [(n, c) for n, c in geco_kmax_phases(cmds, geco_kmax) if n not in known]
    meta["commands"] = dict(cmds)
    meta.setdefault("relaunches", []).append(f"{datetime.now(UTC):%Y-%m-%dT%H:%M:%SZ}")
    ensure_libero_config()  # a fresh machine (a Modal eval container) has none: LIBERO would prompt and crash
    execute(run, meta, cmds, wargs, max_retries, resume_train=True, only=only)
    print("done:", run)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("run", nargs="?")
    ap.add_argument("--list", action="store_true")
    ap.add_argument("--steps", type=int, default=10_000)
    ap.add_argument("--trials", type=int, default=10, help="episodes per task")
    ap.add_argument("--suites", default=None, help="default libero_spatial,libero_object (G runs: goal,spatial)")
    ap.add_argument("--from-run", default=None, help="eval-only runs: folder of the finished run whose checkpoint "
                    "is reused (B7: a B1 run, B8: an A3 run)")
    ap.add_argument("--seed", type=int, default=1000, help="training + eval seed (LeRobot default 1000)")
    ap.add_argument("--resume-run", default=None, help="continue an existing run folder: resume training from its "
                    "last checkpoint, skip finished phases")
    ap.add_argument("--max-retries", type=int, default=8, help="resume training after a crash (WSL GPU faults)")
    ap.add_argument("--only", default=None, help="comma-separated phases to run (train, eval_<suite>); others skipped")
    ap.add_argument("--geco-kmax", default="", help="with --resume-run on a G1 folder: comma-separated K_max values; "
                    "adds phases eval_<suite>_k<K> (GeCO sampler run for K iterations instead of 10)")
    ap.add_argument("--smoke", action="store_true")
    ap.add_argument("--dry-run", action="store_true")
    a = ap.parse_args()
    if a.resume_run:
        return resume_run(Path(a.resume_run).resolve(), a.max_retries, a.only and a.only.split(","),
                          [int(k) for k in a.geco_kmax.split(",") if k])
    if a.list or not a.run:
        for k, v in RUNS.items():
            print(f"{k:3} [{v[1]}] {v[0]:48} {v[5]}")
        return
    title, part, wargs, targs, eargs, why = RUNS[a.run]
    steps, trials = (20, 1) if a.smoke else (a.steps, a.trials)
    suites = (a.suites or SUITES.get(a.run, "libero_spatial,libero_object")).split(",")
    suites = suites[:1] if a.smoke else suites
    tag = ("_smoke" if a.smoke else "") + (f"_s{a.seed}" if a.seed != 1000 else "")
    run = ROOT / "experiments/results/phase2" / f"{a.run}{tag}_{datetime.now(UTC):%Y%m%dT%H%M%SZ}"
    cmds = []
    if targs is not None:
        cmds.append(("train", [str(PY), str(HERE / "train_variant.py"), *wargs, "--",
                               "--dataset.repo_id=HuggingFaceVLA/libero", *targs, f"--steps={steps}",
                               f"--save_freq={min(1000, steps)}", "--log_freq=50", f"--seed={a.seed}",
                               f"--output_dir={run / 'train'}",
                               "--policy.push_to_hub=false", f"--job_name={a.run}"]))
        ckpt = run / "train/checkpoints/last/pretrained_model"
    else:
        if not a.from_run and not a.dry_run:
            sys.exit(f"{a.run} is eval-only and needs --from-run <run folder> (B7: B1, B8/B9: A3)")
        ckpt = Path(a.from_run or "<source run>") / "train/checkpoints/last/pretrained_model"
    uses_rename = (targs is None) or (RENAME in targs)  # B7/B8 reuse a SmolVLA checkpoint
    for s in suites:
        cmds.append((f"eval_{s}", [str(PY), str(HERE / "eval_variant.py"), *eargs, "--", f"--policy.path={ckpt}",
                                   *([RENAME] if uses_rename else []),
                                   *([] if a.run == "B8" else [f"--policy.n_action_steps={EXEC_STEPS}"]),
                                   # render at the dataset's 256x256 (LiberoEnv default is 360x360): Diffusion's
                                   # spatial-softmax encoder is size-fixed, and every policy then sees training-size images
                                   "--env.type=libero", "--env.observation_height=256", "--env.observation_width=256",
                                   f"--env.task={s}", f"--eval.n_episodes={trials}", f"--seed={a.seed}",
                                   "--eval.batch_size=1", *(["--env.task_ids=[0]"] if a.smoke else []),
                                   f"--output_dir={run / f'eval_{s}'}"]))
    if a.dry_run:
        for name, c in cmds:
            print(f"# {name}\n{' '.join(c)}\n")
        return
    run.mkdir(parents=True)
    ensure_libero_config()
    meta = {"run": a.run, "title": title, "part": part, "teaches": why, "steps": steps, "trials_per_task": trials,
            "suites": suites, "smoke": a.smoke, "seed": a.seed, "from_run": a.from_run, "eval_n_action_steps": None if a.run == "B8" else EXEC_STEPS, "commands": {n: c for n, c in cmds},
            "label": {"A": "BASELINE_MODEL", "B": "PIBEHAVIOR_LITE_ABLATION", "C": "VLA_ANATOMY",
                      "D": "PIBEHAVIOR_LITE_COMBINED", "G": "GECO_REPRO"}[part]}
    (run / "run.json").write_text(json.dumps(meta, indent=2))
    execute(run, meta, cmds, wargs, a.max_retries, only=a.only and a.only.split(","))
    print("done:", run)


if __name__ == "__main__":
    main()