Robotics
LeRobot
gr00t
act
pi05
training
bimanual
File size: 40,521 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
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
#!/usr/bin/env python3
"""Train an ACT or GR00T policy on a recorded dataset.

    ./scripts/train.py --policy act
    ./scripts/train.py --policy groot --steps 30000
    ./scripts/train.py --policy groot --dry-run     # print the plan, run nothing

WHERE THIS RUNS
---------------
Wherever the dataset and the GPU are. On the robot host that is a local
checkout of the pl_2m workspace; on a leased GPU box it is a standalone clone of
the pl_imitation repo. The tool does not orchestrate anything remote β€”
there is no upload step, no fetch step, no ssh. You put the dataset and the repo
on the machine that has the GPU and run this there, and the only difference
between the two cases is which interpreters ``training_config`` resolves.

WHAT IT REPLACES
----------------
Nine hand-written scripts that lived only on whichever GPU box was leased
(``_act_train.sh``, ``_groot_train.sh``, ``_groot_smoke.sh``, ``_conv_env.sh``,
``filter_reindex.py``, ``openarm_config.py``, ...). Each restated something that
is derivable β€” the group boundaries, the camera roles, the set of usable
episodes β€” and none of them were in version control, so the configuration died
with the container.

THE GR00T PIPELINE
------------------
Four stages, in the order that is known to work:

1. **stage** the dataset into a work copy. The v3.0 -> v2.1 converter rewrites
   in place, so the recording is never handed to it directly.
2. **filter + reindex** on the v3.0 copy, before conversion. Truncated episodes
   are dropped and the survivors renumbered contiguously. Order matters: the
   converter slices data by ``dataset_from_index``/``dataset_to_index`` and
   video by ``from``/``to_timestamp``, all of which this preserves, so filtering
   first is safe and filtering after is not.
3. **generate** ``meta/modality.json`` and the embodiment config module.
4. **convert**, then **fine-tune**.

ACT needs none of that: ``lerobot-train`` reads v3.0 directly and takes the
usable-episode set as a command-line list.
"""
from __future__ import annotations

import argparse
import json
import logging
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path

import dataset_spec
import early_stop
import groot_modality
import tb_logger
import training_config

logger = logging.getLogger("train")

ACT = "act"
GROOT = "groot"

#: Dataset facts every checkpoint must carry to be served right: the robot the
#: state was recorded on, the observation masker its frames went through, and the
#: sorting cue drawn on them.
CARRIED_META = ("robot_profile.json", "masker.json", "cue.json")


# ---------------------------------------------------------------------------
# Environment resolution
# ---------------------------------------------------------------------------

def _resolve_python(explicit: str, *candidates: Path, required: bool = True) -> Path:
    """First usable interpreter, or a clear error listing what was tried.

    A missing venv is the most common first-run failure on a fresh GPU box, and
    the useful message names every path that was checked β€” not just the last.

    ``required=False`` (what --dry-run passes) downgrades absence to a warning
    and returns the preferred path anyway, so the plan can be reviewed on a
    machine that has the dataset but not the training environments. Refusing to
    print a plan because the GPU box's venv is not on your laptop would make the
    flag useless exactly where it is most wanted.
    """
    if explicit:
        path = Path(explicit).expanduser()
        if path.is_file() or not required:
            return path
        raise FileNotFoundError(f"configured interpreter does not exist: {path}")
    for candidate in candidates:
        if candidate.is_file():
            return candidate
    tried = "\n  ".join(str(c) for c in candidates)
    if not required:
        logger.warning("no interpreter found (tried: %s) β€” showing the preferred path",
                       ", ".join(str(c) for c in candidates))
        return candidates[0]
    raise FileNotFoundError(
        f"no interpreter found. Tried:\n  {tried}\n"
        f"Set the matching *_python key in config/training.yaml, or create the venv.")


def act_entrypoint(settings, *, required: bool = True) -> Path:
    """``lerobot-train``. Prefers the lerobot checkout's own venv."""
    lerobot = Path(settings.lerobot_root).expanduser()
    return _resolve_python(
        settings.act_python,
        lerobot / ".venv" / "bin" / "lerobot-train",
        Path(sys.prefix) / "bin" / "lerobot-train",
        required=required,
    )


def _groot_launcher(settings, args) -> list:
    """The command prefix that runs the fine-tune on ``args.num_gpus`` devices.

    One GPU runs the script directly. More than one MUST go through torchrun,
    and not as a preference: HF ``Trainer`` decides how to parallelise from the
    environment, not from our flag. Without a launcher it sees more than one
    visible device, is not in distributed mode, and wraps the model in
    ``nn.DataParallel`` β€” which GR00T does not survive, because its ``device``
    property reads ``next(iter(self.parameters()))`` and a DataParallel replica
    has none. The failure is a StopIteration on the first training step, minutes
    in, after the dataset has been staged.

    torchrun puts each rank in distributed mode, where Trainer uses DDP and
    never reaches for DataParallel. Isaac expects exactly this: it reconciles
    ``--num-gpus`` against the launcher's WORLD_SIZE and refuses a mismatch,
    because that number also divides the global batch into the per-device one.
    """
    python = groot_python(settings, required=not args.dry_run)
    if args.num_gpus <= 1:
        return [python]
    torchrun = python.parent / "torchrun"
    if not torchrun.exists() and not args.dry_run:
        raise SystemExit(
            f"{torchrun} not found β€” multi-GPU training needs the torchrun that "
            f"ships beside {python.name}. Train on one GPU (--num-gpus 1) or "
            "repair that environment.")
    return [torchrun, f"--nproc_per_node={args.num_gpus}", "--standalone"]


def groot_python(settings, *, required: bool = True) -> Path:
    isaac = Path(settings.isaac_root).expanduser()
    return _resolve_python(settings.groot_python, isaac / ".venv" / "bin" / "python",
                           required=required)


def convert_python(settings, *, required: bool = True) -> Path:
    """The converter has its own environment: it pins an older lerobot than the
    one that trains, so it cannot share the training venv."""
    isaac = Path(settings.isaac_root).expanduser()
    return _resolve_python(
        settings.convert_python,
        isaac / "scripts" / "lerobot_conversion" / ".venv" / "bin" / "python",
        required=required,
    )


# ---------------------------------------------------------------------------
# Shared helpers
# ---------------------------------------------------------------------------

def _run(cmd: list[str], *, env: dict | None = None, cwd: Path | None = None,
         dry_run: bool = False, watch: str | None = None,
         detector=None, sink=None, ckpt_root: Path | None = None) -> int:
    """Run a subprocess, optionally watching its output for a loss plateau.

    Without ``detector`` the child's output goes straight to our stdout, which is
    what the conversion step and every --dry-run wants. With one, the output is
    streamed through this process so it can be parsed β€” still echoed line by
    line, so the log on disk is the same either way.
    """
    printable = " \\\n    ".join(str(c) for c in cmd)
    logger.info("running:\n    %s", printable)
    if dry_run:
        logger.info("(--dry-run: not executed)")
        return 0
    if detector is None and sink is None:
        completed = subprocess.run([str(c) for c in cmd], env=env,
                                   cwd=str(cwd) if cwd else None, check=False)
        return completed.returncode

    return _run_supervised([str(c) for c in cmd], env=env, cwd=cwd,
                           policy=watch, detector=detector, sink=sink,
                           ckpt_root=ckpt_root)


def _stamp_tasks(dataset_root: Path, ckpt_root: Path, *, dry_run: bool) -> None:
    """Write the dataset's task list into every checkpoint as ``tasks.jsonl``.

    A language-conditioned policy has to be served with the instruction it was
    trained on, and the serving host usually does not have the dataset: without
    this the node fell back to a config default ("put toys into the basket")
    for a policy trained on "v1", which does not fail β€” it just drives worse.
    One ``{"task_index", "task"}`` object per line, the format the node reads.
    """
    import pandas as pd  # noqa: PLC0415 - training-env only

    source = Path(dataset_root) / "meta" / "tasks.parquet"
    if not source.is_file():
        logger.info("%s absent β€” checkpoints will carry no task list", source)
        return
    table = pd.read_parquet(source).reset_index()
    lines = [json.dumps({"task_index": int(r["task_index"]), "task": str(r["task"])})
             for _, r in table.sort_values("task_index").iterrows()]
    targets = [d for d in sorted(Path(ckpt_root).glob("*")) if d.is_dir() and not d.is_symlink()]
    if dry_run:
        logger.info("would write tasks.jsonl (%d task(s)) into %d checkpoint dir(s)", len(lines), len(targets))
        return
    for target in targets:
        (target / "tasks.jsonl").write_text("\n".join(lines) + "\n")
    logger.info("stamped tasks.jsonl (%d task(s)) into %d checkpoint dir(s) under %s",
                len(lines), len(targets), ckpt_root)


def _stamp_robot_profile(dataset_root: Path, ckpt_root: Path, *, dry_run: bool) -> None:
    """Copy the dataset's robot profile into every checkpoint the run produced.

    A checkpoint is served long after the dataset that produced it is gone, on a
    machine configured for whatever robot happens to be in front of it. Without
    this, nothing on the serving side can tell that a policy trained on v1 β€”
    prismatic gripper, metres β€” is being driven with v2's revolute radian
    thresholds. The group boundaries are identical between the two, so the
    modality contract check passes and the mismatch never announces itself.

    Copied from the dataset, not from this machine's active profile: the
    training host need not be the rig, and usually is not.

    A dataset recorded before the profile travelled with it has nothing to copy.
    Those checkpoints stay unstamped and the serving-side check skips, which is
    the behaviour that already existed.

    The masker settings travel the same way: a policy trained on masked frames
    must be served with the same masker.
    """
    targets = [d for d in sorted(Path(ckpt_root).glob("*")) if d.is_dir() and not d.is_symlink()]
    for name in CARRIED_META:
        source = Path(dataset_root) / "meta" / name
        if not source.is_file():
            logger.info("%s absent β€” checkpoints will carry no %s", source, name)
            continue
        if dry_run:
            logger.info("would copy %s into %d checkpoint dir(s)", source, len(targets))
            continue
        for target in targets:
            shutil.copy2(source, target / name)
        logger.info("stamped %s into %d checkpoint dir(s) under %s",
                    name, len(targets), ckpt_root)


def _checkpoint_dirs(root: Path) -> dict:
    """``{dir: size_bytes}`` for every checkpoint directory under ``root``."""
    if root is None or not root.is_dir():
        return {}
    out = {}
    for child in root.iterdir():
        if not child.is_dir() or child.is_symlink():
            continue
        try:
            out[child.name] = sum(f.stat().st_size for f in child.rglob("*") if f.is_file())
        except OSError:
            continue
    return out


def _settled_new_checkpoint(root: Path, before: dict, seen: dict) -> str | None:
    """Name of a NEW checkpoint that has finished being written, else None.

    "Finished" means the directory holds weights and its total size was the same
    on two consecutive polls. Size-stability rather than a sentinel file because
    neither trainer writes one, and the file written last is an implementation
    detail of whichever save routine is in play.
    """
    current = _checkpoint_dirs(root)
    for name, size in current.items():
        if name in before:
            continue
        if not any((root / name).rglob("*.safetensors")):
            continue
        if seen.get(name) == size and size > 0:
            return name
        seen[name] = size
    return None


def _run_supervised(cmd: list[str], *, env, cwd, policy: str, detector, sink=None,
                    ckpt_root: Path | None = None, poll_s: float = 10.0) -> int:
    """Stream a training run, ending it once a post-plateau checkpoint is SAVED.

    The plateau only arms the stop. What releases it is a new checkpoint
    directory appearing on disk and holding still β€” deliberately not the
    trainer's own "Checkpoint policy after step N" log line, which lerobot emits
    BEFORE calling save_checkpoint::

        logging.info(f"Checkpoint policy after step {step}")   # logged here
        checkpoint_dir = get_step_checkpoint_dir(...)
        save_checkpoint(...)                                    # written here

    Stopping on that line killed the process between the two and destroyed the
    save it was supposed to be preserving β€” the 2026-07-27 ACT run announced
    step 500000 and left no directory for it at all.

    The pipe keeps being drained while waiting, because a child that fills its
    stdout buffer blocks forever and would never reach the save.

    ``poll_s`` gates how often the directory is examined; stability needs TWO
    polls, so a save interval shorter than ``2 * poll_s`` will never release the
    stop and the run just finishes normally. At real intervals (ACT saves every
    25000 steps, ~40 min) that is hundreds of polls of headroom.
    """
    proc = subprocess.Popen(cmd, env=env, cwd=str(cwd) if cwd else None,
                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                            text=True, bufsize=1)
    before: dict = {}
    seen: dict = {}
    last_poll = 0.0
    try:
        for line in proc.stdout:
            sys.stdout.write(line)
            sys.stdout.flush()

            if sink is not None:
                sink.observe(line)

            if detector is None:
                continue
            if not detector.plateaued:
                loss = early_stop.parse_loss(line, policy)
                if loss is not None and detector.observe(loss):
                    before = _checkpoint_dirs(ckpt_root)
                    logger.warning("EARLY STOP ARMED β€” %s", detector.reason)
                    logger.warning("waiting for the next checkpoint to be WRITTEN under %s "
                                   "(%d already there); the run continues until then",
                                   ckpt_root, len(before))
                continue

            now = time.monotonic()
            if now - last_poll < poll_s:
                continue
            last_poll = now
            fresh = _settled_new_checkpoint(ckpt_root, before, seen)
            if fresh is None:
                continue
            logger.warning("checkpoint %s finished writing β€” stopping now", fresh)
            proc.terminate()
            try:
                proc.wait(timeout=180)
            except subprocess.TimeoutExpired:
                logger.warning("did not exit in 180s β€” killing")
                proc.kill()
            break
    finally:
        if sink is not None:
            sink.close()
        if proc.poll() is None:
            proc.wait()
    # A run we stopped on purpose is a success, not the child's exit code.
    return 0 if (detector is not None and detector.plateaued) else proc.returncode


def usable_episodes(dataset_root: Path, info: dict, *, filter_truncated: bool,
                    filter_invalid: bool = True) -> list[int]:
    """Episode indices to train on, with the exclusions logged.

    A filter that silently removes episodes is indistinguishable from a dataset
    that was always smaller, so every drop is named here. Two filters compose:
    truncated video (the loader would pair actions with wrong frames) and the
    recorder's own invalid verdict (safety not armed, lease held outside the
    declared driver set β€” flaws no post-processing can repair).
    """
    table = dataset_spec.episodes_table(dataset_root)
    everything = sorted(int(e) for e in table["episode_index"])
    if not filter_truncated:
        logger.warning("filter_truncated=false β€” training on all %d episodes unchecked",
                       len(everything))
        usable = everything
    else:
        intact, dropped = dataset_spec.intact_episodes(dataset_root, info)
        if dropped:
            logger.warning("dropping %d of %d episodes as truncated:",
                           len(dropped), len(everything))
            for episode, reason in sorted(dropped.items()):
                logger.warning("  episode %d β€” %s", episode, reason)
        else:
            logger.info("all %d episodes intact", len(everything))
        usable = intact

    if filter_invalid:
        validity = dataset_spec.validity_summary(dataset_root)
        drops = {e: r for e, r in validity.invalid.items() if e in set(usable)}
        if drops:
            logger.warning("dropping %d episode(s) the recorder judged invalid:",
                           len(drops))
            for episode, reason in sorted(drops.items()):
                logger.warning("  episode %d β€” %s", episode, reason)
            usable = [e for e in usable if e not in drops]
        elif validity.judged:
            logger.info("all %d judged episodes valid", validity.judged)

    if not usable:
        raise SystemExit("every episode is filtered out; nothing to train on")
    return usable


def holdout_manifest_path(out_dir: Path) -> Path:
    """The run's holdout manifest: a SIBLING of ``out_dir``, never inside it.

    Two trainers forbid the inside: lerobot-train refuses a pre-existing
    output directory outright (``FileExistsError`` in its config validation),
    and the GR00T path rmtree-clears ``out_dir`` right before fine-tuning.
    A sibling file survives both, and a killed run still leaves the record
    of what it never trained on.
    """
    return out_dir.with_name(out_dir.name + ".holdout.json")


def apply_holdout(settings, episodes: list[int], dataset_root: Path,
                  out_dir: Path, *, dry_run: bool,
                  resume: bool = False) -> list[int]:
    """Split off the validation episodes and write the run's manifest.

    Training loss alone cannot tell learning from memorising β€” 30 episodes
    against 500k steps leave ample room to memorise. With
    ``holdout_fraction`` set, the held episodes never reach the trainer and
    the manifest (:func:`holdout_manifest_path`) records exactly which they
    were, in ORIGINAL dataset indices, so an offline evaluation scores the
    checkpoint on data it has provably never seen. Default 0.0: on a small
    dataset the split costs real training data, so switching it on is a
    per-host decision.

    A RESUMED run reuses the manifest it started with rather than
    recomputing: the dataset may have grown since, and a fresh split would
    hold out episodes the checkpoint has already trained on β€” scoring on
    those measures memorisation and calls it generalisation.
    """
    fraction = settings.holdout_fraction
    manifest = holdout_manifest_path(out_dir)
    if resume and manifest.is_file():
        held = set(json.loads(manifest.read_text())["held_episodes"])
        train_eps = [e for e in episodes if e not in held]
        logger.info("resuming with the run's original holdout: %d held, "
                    "%d to train on (%s)", len(held), len(train_eps), manifest)
        return train_eps
    if not fraction:
        return episodes
    train_eps, held = dataset_spec.holdout_split(
        episodes, fraction=fraction, seed=settings.seed,
        tasks=dataset_spec.episode_tasks(dataset_root))
    if not held:
        logger.warning("holdout_fraction=%s but no task has 2+ episodes β€” "
                       "nothing held out", fraction)
        return episodes
    logger.info("holding out %d of %d episodes for validation: %s",
                len(held), len(episodes), held)
    if not dry_run:
        manifest.parent.mkdir(parents=True, exist_ok=True)
        manifest.write_text(json.dumps({
            "dataset_root": str(dataset_root),
            "fraction": fraction,
            "seed": settings.seed,
            "held_episodes": held,
            "train_episodes": train_eps,
        }, indent=2))
    return train_eps



def _sink(settings, args, policy: str, run: str | None = None):
    """A TensorBoard sink for this run, or None when disabled.

    ``run`` names the event subdirectory when it has to differ from the policy β€”
    TensorBoard treats one directory as one run and merges every event file in
    it, so two training runs sharing a directory are drawn as a single
    self-contradicting curve rather than as two.
    """
    out = Path(settings.tb_root).expanduser() / (run or policy)
    if not settings.tb_root or args.dry_run:
        if settings.tb_root and args.dry_run:
            logger.info("would write tensorboard events to %s", out)
        return None
    return tb_logger.TensorBoardSink(
        out, policy, interval=settings.act_log_freq if policy == ACT else None)


def _detector(settings, args, policy: str):
    """A plateau detector, or None when early stopping is off for this policy."""
    enabled = settings.early_stop if args.early_stop is None else args.early_stop
    if enabled and args.early_stop is None:
        # An explicit --early-stop overrides the per-policy list; the config
        # alone does not turn it on for a policy that opted out.
        enabled = policy in settings.early_stop_policies
    if not enabled:
        logger.info("early stopping OFF for %s β€” training the full step budget", policy)
        return None
    # Logged before the dry-run bail-out: whether a run will cut itself short is
    # part of the plan, and a --dry-run that hides it is not showing the plan.
    logger.info("early stopping ON for %s (window=%d, patience=%d, min_delta=%.1f%%, "
                "warmup=%d observations)", policy, settings.early_stop_window,
                settings.early_stop_patience, settings.early_stop_min_delta * 100,
                settings.early_stop_warmup)
    if args.dry_run:
        return None
    return early_stop.PlateauDetector(
        window=settings.early_stop_window,
        patience=settings.early_stop_patience,
        min_delta=settings.early_stop_min_delta,
        warmup=settings.early_stop_warmup,
    )


# ---------------------------------------------------------------------------
# ACT
# ---------------------------------------------------------------------------

def train_act(settings, args) -> int:
    dataset_root = settings.dataset_root(args.repo_id)
    info = dataset_spec.load_info(dataset_root)
    episodes = usable_episodes(dataset_root, info, filter_truncated=settings.filter_truncated,
                                filter_invalid=settings.filter_invalid)

    out_dir = Path(settings.output_root).expanduser() / f"act_{Path(args.repo_id).name}"
    if out_dir.exists() and not args.resume:
        logger.info("removing previous output %s (pass --resume to keep it)", out_dir)
        if not args.dry_run:
            shutil.rmtree(out_dir)
    episodes = apply_holdout(settings, episodes, dataset_root, out_dir,
                             dry_run=args.dry_run, resume=args.resume)

    cmd = [
        act_entrypoint(settings, required=not args.dry_run),
        f"--dataset.repo_id={args.repo_id}",
        f"--dataset.root={dataset_root}",
        # Explicit episode list: lerobot has no truncation filter of its own.
        f"--dataset.episodes={json.dumps(episodes, separators=(',', ''))}",
        "--policy.type=act",
        f"--policy.device={settings.resolved_device()}",
        "--policy.push_to_hub=false",
        f"--output_dir={out_dir}",
        f"--steps={args.steps or settings.act_steps}",
        f"--batch_size={args.batch_size or settings.act_batch_size}",
        f"--num_workers={settings.act_num_workers}",
        f"--save_freq={settings.act_save_freq}",
        f"--log_freq={settings.act_log_freq}",
        f"--seed={settings.seed}",
        "--wandb.enable=false",
    ]
    if settings.act_image_transforms:
        # lerobot defaults these OFF; a policy trained on one fixed lighting
        # and framing fails the same rig under a moved lamp. GR00T's own
        # pipeline augments regardless, so this knob is ACT-only.
        cmd.append("--dataset.image_transforms.enable=true")
    rc = _run(cmd, dry_run=args.dry_run, watch=ACT,
              detector=_detector(settings, args, ACT),
              sink=_sink(settings, args, ACT),
              ckpt_root=out_dir / "checkpoints")
    # Whatever the exit code: an interrupted run still leaves servable checkpoints,
    # and one without its masker.json would read as trained on unmasked frames.
    _stamp_robot_profile(dataset_root, out_dir / "checkpoints", dry_run=args.dry_run)
    _stamp_tasks(dataset_root, out_dir / "checkpoints", dry_run=args.dry_run)
    return rc


# ---------------------------------------------------------------------------
# GR00T
# ---------------------------------------------------------------------------

def _stage_dataset(source: Path, staged: Path, *, dry_run: bool) -> None:
    """Work copy for the converter, which rewrites in place.

    ``staged`` is <staging_root>/<repo_id>, not <staging_root>: the converter
    re-joins repo_id onto whatever --root it is given.
    """
    logger.info("staging %s -> %s", source, staged)
    if dry_run:
        return
    if staged.exists():
        shutil.rmtree(staged)
    # Also clear the converter's own backup copy from a previous run, or it
    # refuses / leaves a stale tree behind.
    for suffix in ("_v30", "_v3.0"):
        backup = staged.with_name(staged.name + suffix)
        if backup.exists():
            shutil.rmtree(backup)
    staged.parent.mkdir(parents=True, exist_ok=True)
    shutil.copytree(source, staged, symlinks=True)


def _carry_profile(source: Path, staged: Path) -> None:
    """Put the dataset's ``meta/robot_profile.json`` back after conversion.

    The converter rebuilds ``meta/`` from what it understands and drops the
    profile, so the converted copy no longer says how its state vector groups.
    ``dataset_spec.groups_of`` then falls back to guessing four groups from the
    component names, which is wrong for any layout the recorder has grown since
    β€” a 17-wide vector with the lift column made that guess raise, minutes into a
    run. Older datasets that never carried a profile are left to the fallback.
    The same goes for ``meta/masker.json`` on a masked dataset.
    """
    for name in CARRIED_META:
        f = source / "meta" / name
        if f.is_file():
            shutil.copy2(f, staged / "meta" / name)


def _filter_and_reindex(staged: Path, episodes: list[int], *, dry_run: bool,
                        read_from: Path | None = None) -> None:
    """Keep ``episodes``, renumber them 0..n-1, and fix the counts in info.json.

    Runs on the v3.0 copy before conversion. ``episode_index`` only names the
    output files; the slices the converter reads (``dataset_from_index`` /
    ``dataset_to_index`` for data, ``from``/``to_timestamp`` for video) are
    carried through untouched, which is what makes the renumbering safe.

    ``read_from`` exists for --dry-run: staging is skipped there, so the staged
    directory does not exist yet and the table has to be read from the source.
    """
    import pandas as pd  # noqa: PLC0415 - training-env only

    files = sorted((read_from or staged).glob("meta/episodes/**/*.parquet"))
    table = pd.concat([pd.read_parquet(f) for f in files], ignore_index=True)
    before = len(table)
    table = (table[table["episode_index"].isin(episodes)]
             .sort_values("episode_index")
             .reset_index(drop=True))
    if len(table) != len(episodes):
        raise SystemExit(
            f"expected {len(episodes)} episodes after filtering, got {len(table)} β€” the "
            f"episode table does not contain every index that passed the intact check")
    original = [int(e) for e in table["episode_index"]]
    table["episode_index"] = list(range(len(table)))

    logger.info("filtered %d -> %d episodes; kept original indices %s",
                before, len(table), original)
    if dry_run:
        return

    episodes_dir = staged / "meta" / "episodes"
    shutil.rmtree(episodes_dir)
    (episodes_dir / "chunk-000").mkdir(parents=True)
    table.to_parquet(episodes_dir / "chunk-000" / "file-000.parquet", index=False)

    info_path = staged / "meta" / "info.json"
    info = json.loads(info_path.read_text())
    info["total_episodes"] = len(table)
    if "length" in table.columns:
        info["total_frames"] = int(table["length"].sum())
    info["splits"] = {"train": f"0:{len(table)}"}
    info_path.write_text(json.dumps(info, indent=4))


def train_groot(settings, args) -> int:
    source = settings.dataset_root(args.repo_id)
    info = dataset_spec.load_info(source)
    episodes = usable_episodes(source, info, filter_truncated=settings.filter_truncated,
                               filter_invalid=settings.filter_invalid)

    name = Path(args.repo_id).name
    work_root = Path(settings.output_root).expanduser()
    # convert_v3_to_v2 does `root = Path(root) / repo_id` internally, and when
    # that path does not exist it falls back to downloading repo_id from the
    # Hub β€” which for a locally-recorded dataset is a 404 several minutes into
    # the run. So the staging tree must mirror <root>/<repo_id>, and --root gets
    # the PARENT. Handing it the dataset directory directly is the bug that
    # looks like "the converter wants my dataset on HuggingFace".
    staging_root = work_root / f"groot_staging_{name}"
    staged = staging_root / args.repo_id

    relative_groups = (list(args.relative_groups) if args.relative_groups is not None
                       else list(settings.groot_relative_groups))
    # A relative run must not land on an absolute run's output directory. Step 5
    # clears out_dir before training, so sharing the name would delete a finished
    # model's checkpoints β€” and the two are not interchangeable, since only one of
    # them can be served with native RTC. The suffix also puts the encoding in the
    # artifact name, which is precisely what the operator has to know to serve it.
    suffix = "_rel" if relative_groups else ""
    out_dir = work_root / f"groot_{name}{suffix}"
    config_path = work_root / f"groot_modality_{name}{suffix}.py"
    # Before staging: _filter_and_reindex renumbers survivors contiguously, so
    # the held-out manifest must be cut while indices still mean the source's.
    # (The manifest itself is a SIBLING of out_dir β€” step 5 clears out_dir.)
    episodes = apply_holdout(
        settings, episodes, source, out_dir, dry_run=args.dry_run,
        resume=(args.resume or getattr(args, "resume_from_checkpoint", False)))

    # 1. stage
    _stage_dataset(source, staged, dry_run=args.dry_run)

    # 2. filter + reindex on the v3.0 copy
    _filter_and_reindex(staged, episodes, dry_run=args.dry_run,
                        read_from=source if args.dry_run else None)

    horizon = args.chunk_horizon or settings.groot_chunk_horizon
    env = dict(os.environ, HF_HOME=str(Path(settings.hf_home).expanduser()))

    # 3. convert v3.0 -> v2.1 (keeps the original as <name>_v3.0)
    rc = _run([convert_python(settings, required=not args.dry_run),
               Path(settings.isaac_root).expanduser()
               / "scripts" / "lerobot_conversion" / "convert_v3_to_v2.py",
               "--repo-id", args.repo_id,
               "--root", staging_root],
              env=env, dry_run=args.dry_run)
    if rc != 0:
        return rc
    if not args.dry_run:
        _carry_profile(source, staged)

    # 4. generate the modality artifacts β€” AFTER conversion, not before.
    #
    # The converter does not edit in place: it builds a fresh tree and swaps it
    # in (`move(root -> root_v3.0)`, `move(new -> root)`). Anything written into
    # the dataset beforehand therefore ends up in the BACKUP, and the trained-on
    # copy has none of it. Writing modality.json first cost a run that died
    # minutes in with FileNotFoundError on exactly that path.
    #
    # Reading the layout from the pre-conversion copy is still correct β€” the
    # group boundaries and camera roles are properties of the recording, which
    # the v2.1 rewrite does not change.
    if args.dry_run:
        logger.info("would write %s/meta/modality.json", staged)
        logger.info("would write %s (horizon=%d)", config_path, horizon)
        reps = groot_modality.action_reps(
            [g.name for g in dataset_spec.groups_of(source, info)], relative_groups)
        logger.info("action rep: %s", ", ".join(f"{k}={v}" for k, v in reps.items()))
    else:
        groot_modality.write_modality_json(staged, info)
        groot_modality.write_embodiment_config(
            staged, config_path,
            chunk_horizon=horizon, embodiment_tag=settings.groot_embodiment_tag,
            relative_groups=relative_groups, info=info)
        modality = staged / "meta" / "modality.json"
        if not modality.is_file():
            raise SystemExit(f"{modality} is missing after conversion β€” refusing to start a "
                             f"multi-hour fine-tune that would fail on it minutes in")

    # 5. fine-tune
    resuming = getattr(args, "resume_from_checkpoint", False)
    if out_dir.exists() and not (args.resume or resuming) and not args.dry_run:
        logger.info("removing previous output %s (pass --resume to keep it)", out_dir)
        shutil.rmtree(out_dir)
    if resuming:
        # Fail here rather than minutes into a load: Isaac resolves the checkpoint
        # itself (the flag is a bool, not a path) and an empty output directory
        # would silently start a fresh run from the base model instead.
        existing = sorted(out_dir.glob("checkpoint-*")) if out_dir.exists() else []
        if not existing:
            raise SystemExit(
                f"--resume-from-checkpoint but {out_dir} holds no checkpoint-* to resume "
                f"from. Isaac picks the newest one in the output directory, so the "
                f"directory has to be the one the earlier run wrote.")
        newest = max(existing, key=lambda p: int(p.name.split("-")[-1]))
        logger.info("resuming from %s (Isaac picks the newest itself)", newest.name)

    isaac = Path(settings.isaac_root).expanduser()
    rc = _run([*_groot_launcher(settings, args),
               isaac / "gr00t" / "experiment" / "launch_finetune.py",
               "--base-model-path", settings.groot_base_model,
               "--dataset-path", staged,
               "--embodiment-tag", settings.groot_embodiment_tag,
               "--modality-config-path", config_path,
               "--num-gpus", str(args.num_gpus),
               "--output-dir", out_dir,
               "--max-steps", str(args.steps or settings.groot_steps),
               "--save-steps", str(settings.groot_save_steps),
               "--save-total-limit", str(settings.groot_save_total_limit),
               "--global-batch-size", str(args.batch_size or settings.groot_batch_size),
               "--dataloader-num-workers", str(settings.groot_num_workers),
               *(["--resume-from-checkpoint"] if resuming else [])],
              env=env, cwd=isaac, dry_run=args.dry_run, watch=GROOT,
              detector=_detector(settings, args, GROOT),
              sink=_sink(settings, args, GROOT, run=f"{GROOT}{suffix}"),
              ckpt_root=out_dir)
    # Stamped from the SOURCE dataset, not the staged copy: the converter
    # swaps trees, so the staged one is whatever survived that swap. Stamped
    # whatever the exit code, so an interrupted run's checkpoints carry their masker.
    _stamp_robot_profile(source, out_dir, dry_run=args.dry_run)
    _stamp_tasks(source, out_dir, dry_run=args.dry_run)
    return rc


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

def build_parser(settings) -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description=__doc__.split("\n\n")[0],
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--policy", required=True, choices=[ACT, GROOT],
                        help="which policy family to train")
    parser.add_argument("--repo-id", default=settings.repo_id,
                        help=f"dataset under {settings.datasets_root} (default: %(default)s)")
    parser.add_argument("--steps", type=int, default=None,
                        help="training steps (default: per-policy value from training.yaml)")
    parser.add_argument("--batch-size", type=int, default=None,
                        help="batch size (default: per-policy value from training.yaml)")
    parser.add_argument("--chunk-horizon", type=int, default=None,
                        help=f"GR00T supervised chunk steps (default: "
                             f"{settings.groot_chunk_horizon})")
    parser.add_argument("--relative-groups", default=None, metavar="GROUP,GROUP",
                        type=lambda s: [p for p in (x.strip() for x in s.split(",")) if p],
                        help="GR00T action groups to supervise as state-relative deltas "
                             f"(default: {settings.groot_relative_groups or 'none, all absolute'}). "
                             "Pass an empty string to force all-absolute. Output goes to "
                             "groot_<dataset>_rel, and the result must be served with "
                             "relative_blend rather than native RTC.")
    parser.add_argument("--num-gpus", type=int, default=1, help="GR00T only (default: %(default)s)")
    parser.add_argument("--resume", action="store_true",
                        help="keep an existing output directory instead of clearing it")
    parser.add_argument("--resume-from-checkpoint", action="store_true",
                        help="GR00T only: continue from the newest checkpoint-* already in "
                             "the output directory instead of starting from the base model. "
                             "Implies --resume. NOTE the LR schedule is defined over "
                             "--steps and is recomputed on resume, so a run whose budget "
                             "already annealed to ~0 restarts at the LR its NEW budget "
                             "puts at that step β€” a warm restart, not a seamless extension.")
    parser.add_argument("--early-stop", dest="early_stop", action="store_true", default=None,
                        help="stop when the loss plateaus (overrides training.yaml)")
    parser.add_argument("--no-early-stop", dest="early_stop", action="store_false",
                        help="train the full step budget regardless of the loss curve")
    parser.add_argument("--dry-run", action="store_true",
                        help="print the plan and the exact commands, execute nothing")
    return parser


def main() -> int:
    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
    settings = training_config.SETTINGS
    args = build_parser(settings).parse_args()

    dataset_root = settings.dataset_root(args.repo_id)
    logger.info("policy=%s repo_id=%s device=%s",
                args.policy, args.repo_id, settings.resolved_device())
    logger.info("dataset=%s", dataset_root)
    logger.info("output =%s", Path(settings.output_root).expanduser())

    if args.policy == ACT:
        return train_act(settings, args)
    return train_groot(settings, args)


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