Robotics
LeRobot
gr00t
act
pi05
training
bimanual
pl2m-training / scripts /training_config.py
minssuung's picture
Add PL-2 M training code
acba5e6 verified
Raw History Blame Contribute Delete
14.9 kB
#!/usr/bin/env python3
"""Training settings SSOT β€” the one place a training knob is written down.
WHY THIS EXISTS
---------------
Before this module the training knobs lived as literals inside ad-hoc shell
scripts on whatever GPU box happened to be leased that week
(``_groot_train.sh``, ``_act_train.sh``). Those scripts were not in any repo, so
every number in them β€” steps, batch size, the action horizon, the list of
episodes to train on β€” was a decision nobody could review and nothing could
reproduce. Deleting the box deleted the configuration.
So the knobs come here, and the values that are *derivable* are not knobs at all:
camera roles, state/action group boundaries and the intact-episode set are read
off the dataset (see ``dataset_spec.py``) rather than restated. A number you can
compute is a number that cannot drift.
LAYERING
--------
Mirrors ``pl_imitation_inference``: dataclass defaults are the SSOT, and ``config/training.yaml``
overrides them for a particular host or run. Same relationship ``inference.yaml``
has to ``pl_imitation_inference/config.py``.
Dataset identity (``datasets_root`` / ``repo_id``) is NOT restated here β€” it is
imported from the recorder's own config, which already resolves the per-machine
override in ``~/.pl2_recorder.json``. Training on a stale root because the
trainer kept a second copy of the path is exactly the failure this avoids.
RUNS WITHOUT ROS
----------------
Import-safe on a bare GPU container: stdlib + PyYAML only, no rclpy, no torch.
The recorder config it imports is stdlib-only for the same reason.
"""
from __future__ import annotations
import logging
import sys
from dataclasses import dataclass, field, fields
from pathlib import Path
logger = logging.getLogger(__name__)
# This file is <repo>/scripts/training_config.py, so parents[1] is the
# pl_imitation repo root in BOTH layouts that matter:
# * inside the pl_2m workspace -> src/pl_imitation/
# * cloned standalone on a GPU box -> ~/pl_imitation/
# Deliberately not parents[2] + glob("*/pl_imitation_recorder") the way make_modality.py
# did: from a standalone clone that walk lands on the clone's PARENT and the
# glob can match a sibling checkout's recorder package instead of this one's.
_REPO_ROOT = Path(__file__).resolve().parents[1]
_RECORDER_PKG = _REPO_ROOT / "pl_imitation_recorder"
_CONFIG_YAML = _REPO_ROOT / "config" / "training.yaml"
if _RECORDER_PKG.is_dir() and str(_RECORDER_PKG) not in sys.path:
sys.path.insert(0, str(_RECORDER_PKG))
try:
from pl_imitation_recorder.recorder.config import SETTINGS as _RECORDER_SETTINGS
except ImportError as exc: # pragma: no cover - exercised by the standalone-clone guard
raise ImportError(
f"cannot import the recorder config from {_RECORDER_PKG}. training_config.py "
f"resolves it as <repo>/pl_imitation_recorder relative to {_REPO_ROOT}; if that directory "
f"is absent the checkout is incomplete (expected the pl_imitation repo "
f"root, which contains pl_imitation_recorder/ beside scripts/)."
) from exc
@dataclass
class TrainingSettings:
"""Every training knob, with the defaults that actually produced a model."""
# --- dataset identity (imported, never restated) --------------------------
#: Where datasets live. From the recorder SSOT so a rig that moved its
#: datasets root does not train on a stale one.
datasets_root: str = _RECORDER_SETTINGS.datasets_root
#: "<owner>/<name>", the recorder's per-machine dataset identity.
repo_id: str = _RECORDER_SETTINGS.repo_id
# --- where trained models go ----------------------------------------------
#: The serving shelf that ``pl_imitation_studio.infer`` already scans
#: (InferSettings.default_checkpoint_roots). Training writes where inference
#: looks, so a finished run appears in the picker with no extra step β€” and
#: deliberately OUTSIDE the source tree, unlike the old outputs/train/.
output_root: str = str(Path.home() / "pl2_models")
# --- shared training knobs -------------------------------------------------
#: "auto" resolves to cuda when torch sees a GPU, else cpu.
device: str = "auto"
seed: int = 1000
#: Drop episodes whose video is short of the span the metadata claims.
#: Detected per-episode, never hand-listed β€” see dataset_spec.intact_episodes.
filter_truncated: bool = True
#: Drop episodes the recorder itself judged invalid (safety not armed,
#: lease held outside the declared driver set) β€” dataset_spec.validity_summary
#: reads the verdict sidecar. Datasets recorded before the sidecar existed
#: carry no verdicts and pass through untouched.
filter_invalid: bool = True
#: Fraction of episodes held out of training for offline validation,
#: stratified per task, deterministic in ``seed``. 0.0 = off. The held
#: indices land in <out_dir>/holdout.json; scripts/val_loss.py scores a
#: checkpoint on exactly those episodes. On a small dataset the split
#: costs real training data β€” switching it on is a per-host decision.
holdout_fraction: float = 0.0
# --- ACT (lerobot-train) ---------------------------------------------------
act_steps: int = 300_000
act_batch_size: int = 8
act_num_workers: int = 8
act_save_freq: int = 25_000
act_log_freq: int = 200
#: Random image transforms (brightness/contrast/crop jitter) during ACT
#: training. lerobot ships them OFF by default, which trains the policy on
#: exactly one lighting/framing and fails a rig whose light changed. GR00T's
#: pipeline applies its own augmentation regardless of this knob. The only
#: honest reason to set False is reproducing an older un-augmented run.
act_image_transforms: bool = True
# --- GR00T (Isaac launch_finetune) -----------------------------------------
groot_steps: int = 30_000
groot_batch_size: int = 64
groot_num_workers: int = 4
groot_save_steps: int = 10_000
groot_save_total_limit: int = 5
groot_base_model: str = "nvidia/GR00T-N1.7-3B"
#: Isaac's embodiment tag. Upper-case here because that is the form
#: launch_finetune takes on the command line; pl_imitation_inference stores the
#: lower-case form it receives back from the server.
groot_embodiment_tag: str = "NEW_EMBODIMENT"
#: How many chunk steps to SUPERVISE β€” the length of the action modality's
#: delta_indices, and the horizon the served policy actually reports.
#:
#: Not the same quantity as config.json's ``action_horizon``, which is the
#: width of N1.7's action tensor (also 40). A fine-tune is free to supervise
#: fewer steps than that width; the 2026-07-26 run used 16, and that is what
#: this was until the drive-side numbers came in.
#:
#: WHY 40 AND NOT 16
#: Two constraints bind ``n_action_steps`` (how many steps the node consumes
#: per chunk), and at H=16 they have no overlap:
#:
#: RTC invariant replay must land inside the correction window: 3n <= H
#: Producer latency a chunk must cover its own cycle: n / control_hz >= cycle
#:
#: The measured producer cycle is ~204 ms p50 β€” not the 145-155 ms of server
#: inference alone, because observation assembly (camera fetch, CUDA decode),
#: the wire, and smoothing add ~50 ms on top. That puts the latency floor at
#: n >= 7, while H=16 caps the invariant at n <= 5. No n satisfies both, which
#: is why n=5 still drifted a tick or two past the correction window every
#: cycle instead of failing outright.
#:
#: H=40 opens it: n <= 13 against a floor of 7. The latency margin at a given
#: n is identical for any H that admits it β€” H only sets the ceiling β€” so the
#: value of 40 is that n stays tunable AFTER training. n sized from a p50
#: cycle underruns half the time by construction, so the real n wants a tail
#: percentile, and discovering that it needs 9 or 10 must not cost a second
#: 20-GPU-hour run. 40 is also the tensor's full width, so nothing is padded.
groot_chunk_horizon: int = 40
#: Action groups supervised as state-relative deltas (``action - state[-1]``)
#: instead of absolute joint targets. Empty means every group is absolute.
#:
#: Per group, not one switch, because the grippers want the other answer: a
#: gripper is a near-binary open/close, so its action-minus-state is mostly
#: zero with occasional spikes and normalises badly. ``["right_arm",
#: "left_arm"]`` is the split Isaac's own shipped configs use.
#:
#: The names are validated against the dataset's real groups β€” a typo raises
#: rather than quietly training everything absolute.
#:
#: WHY THE DEFAULT IS ABSOLUTE
#: Relative and native RTC are mutually exclusive. RTC repairs a chunk seam
#: by holding part of the previous chunk, and a held delta is not a held
#: position β€” it decodes to a jump of about the state change across the seam,
#: which is the mechanism behind the 11-15 deg wrist pop measured on the
#: first relative model. A relative checkpoint therefore has to be served
#: decode-to-absolute (``relative_blend``), giving up the native-RTC headroom
#: that ``groot_chunk_horizon`` 40 exists to provide.
groot_relative_groups: list = field(default_factory=list)
# --- early stopping --------------------------------------------------------
#: Stop once the loss stops improving. OFF by default, and deliberately so:
#: it is a budget guard, not model selection (see early_stop.py). It is also
#: only unambiguously safe where the LR does not depend on the step count β€”
#: ACT (no scheduler, flat lr) yes; GR00T anneals to ~0 across max_steps, so
#: a huge budget plus an early stop yields a model that never annealed.
early_stop: bool = False
#: Which policies the flag applies to. Split per policy because the two
#: families answer differently: ACT has no LR scheduler, so a generous step
#: budget plus a plateau stop is strictly good; GR00T anneals to ~0 across
#: max_steps, so stopping early leaves a model that never annealed. For
#: GR00T a fired stop is best read as budget DISCOVERY β€” re-run with
#: groot_steps set to where it stopped.
early_stop_policies: list = field(default_factory=lambda: ["act"])
#: Loss observations averaged into one window. One observation is one logged
#: line, so at ACT's log_freq=200 a window of 25 spans 5000 steps.
early_stop_window: int = 25
#: Consecutive windows without improvement before the stop is armed.
early_stop_patience: int = 4
#: Relative improvement a window must beat the best by. Relative, because a
#: GR00T run ending near 0.003 and an ACT run near 0.4 share no absolute one.
early_stop_min_delta: float = 0.01
#: Observations ignored before arming β€” loss drops steeply at the start and
#: an early flat stretch is not convergence.
early_stop_warmup: int = 100
# --- tensorboard -----------------------------------------------------------
#: Write TensorBoard scalars, parsed from the trainer's own output rather
#: than by patching it (see tb_logger.py). "" disables; the default puts one
#: subdirectory per policy under the model shelf, so `tensorboard --logdir
#: <tb_root>` shows both runs side by side.
tb_root: str = str(Path.home() / "pl2_models" / "tb")
# --- environments ----------------------------------------------------------
#: Per-stage interpreters. The three stages genuinely need three different
#: environments on a training host (verified on the H200: lerobot 3.12,
#: Isaac 3.12, converter 3.10 with its own pinned lerobot), so a single
#: "the venv" the way train.sh assumed does not exist here.
#: "" means "resolve it from the install roots below".
act_python: str = ""
groot_python: str = ""
convert_python: str = ""
#: Checkouts the interpreters are found under.
lerobot_root: str = str(Path.home() / "caring" / "lerobot")
isaac_root: str = str(Path.home() / "caring" / "Isaac-GR00T")
#: HF cache. Isaac downloads the 12 GB base model plus the gated
#: Cosmos-Reason2-2B into it; pointing it at a persistent volume is what
#: keeps a re-run from re-downloading both.
hf_home: str = str(Path.home() / "caring" / "hf_cache")
def resolved_device(self) -> str:
"""``device``, with "auto" turned into a real answer.
torch is imported lazily and failure is not fatal: the console-side
callers of this module must stay importable on hosts with no torch.
"""
if self.device != "auto":
return self.device
try:
import torch # noqa: PLC0415 - deliberately lazy
except ImportError:
return "cpu"
return "cuda" if torch.cuda.is_available() else "cpu"
def dataset_root(self, repo_id: str | None = None) -> Path:
"""Full path to one dataset."""
return Path(self.datasets_root).expanduser() / (repo_id or self.repo_id)
def _apply_yaml(settings: TrainingSettings, path: Path) -> list[str]:
"""Overlay ``path`` onto ``settings`` in place. Returns the keys applied.
Unknown keys are an error, not a shrug: a typo'd knob that is silently
ignored looks exactly like a knob that had no effect, and the operator would
be reading training curves to find a spelling mistake.
"""
if not path.is_file():
return []
try:
import yaml # noqa: PLC0415 - optional, and absent on some robot hosts
except ImportError:
logger.warning(
"%s exists but PyYAML is not installed in this interpreter β€” using dataclass "
"defaults. Install PyYAML, or run from the training venv where it is present.",
path)
return []
raw = yaml.safe_load(path.read_text()) or {}
if not isinstance(raw, dict):
raise ValueError(f"{path}: expected a mapping at the top level, got {type(raw).__name__}")
known = {f.name for f in fields(TrainingSettings)}
unknown = sorted(set(raw) - known)
if unknown:
raise ValueError(
f"{path}: unknown setting(s) {unknown}. Known settings: {sorted(known)}")
for key, value in raw.items():
setattr(settings, key, value)
return sorted(raw)
def load(path: Path | None = None) -> TrainingSettings:
"""Dataclass defaults with ``config/training.yaml`` overlaid."""
settings = TrainingSettings()
applied = _apply_yaml(settings, path or _CONFIG_YAML)
if applied:
logger.info("training.yaml overrode: %s", ", ".join(applied))
return settings
#: Module-level singleton, matching the pl_imitation_inference / pl_imitation_recorder convention.
SETTINGS = load()