Robotics
LeRobot
gr00t
act
pi05
training
bimanual
pl2m-training / scripts /early_stop.py
minssuung's picture
Add PL-2 M training code
acba5e6 verified
Raw History Blame Contribute Delete
6.48 kB
#!/usr/bin/env python3
"""Stop a training run once its loss stops improving.
WHAT THIS IS FOR — AND WHAT IT IS NOT
-------------------------------------
This is a **budget guard**: it ends a run that is no longer buying anything, so
the GPU hours go somewhere useful. It is NOT model selection.
In behaviour cloning the training loss falling is not the same as the policy
getting better — it is the model fitting the demonstrations more tightly, which
past some point is memorisation. Task success rate can peak well before the loss
flattens and decline afterwards, and nothing in this file can see that. Picking
which checkpoint to ship still means running several of them on the robot.
Treated as a guard rather than a selector, plateau detection is straightforwardly
useful, which is why it is opt-in per policy rather than on by default.
THE LR-SCHEDULE TRAP
--------------------
"Set the step count very high and let early stopping decide" is only safe when
the learning rate does not depend on the step count. It does for GR00T: Isaac
anneals to ~0 across ``max_steps`` (the 2026-07-26 run ended at lr=3e-13), so
declaring 1,000,000 steps and stopping at 50,000 trains the whole time at nearly
full LR and never anneals — a materially worse model than a real 50,000-step run.
ACT is the opposite: lerobot's ACT preset has no scheduler at all
(``get_scheduler_preset`` returns None; the logs show a flat lr=1.0e-05), so a
generous step budget plus early stopping is exactly right there.
So: raise the ceiling for ACT, keep GR00T's budget honest and let this catch the
case where it converges sooner than expected.
STOPPING POINT
--------------
A plateau does not stop the run immediately — it arms it. The process is ended
at the next checkpoint the trainer writes, so the run always terminates on a
saved model instead of discarding everything since the last save.
"""
from __future__ import annotations
import logging
import re
from dataclasses import dataclass, field
logger = logging.getLogger(__name__)
ACT = "act"
GROOT = "groot"
#: How each trainer prints its training loss. Both were read off real logs
#: rather than guessed:
#: ACT step:2K smpl:14K ep:14 epch:0.24 loss:1.598 grdn:53.926 lr:1.0e-05
#: GR00T {'loss': 0.0033, 'grad_norm': 0.066, 'learning_rate': 3.6e-11}
#: The ACT pattern anchors on a word boundary so it cannot also match
#: ``l1_loss:`` or ``kld_loss:`` later in the same line.
LOSS_PATTERNS = {
ACT: re.compile(r"(?:^|\s)loss:([0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?)"),
GROOT: re.compile(r"'loss':\s*([0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?)"),
}
#: How each trainer announces that a checkpoint is on disk.
#: ACT INFO ... Checkpoint policy after step 25000
#: GR00T ... checkpoint-10000 ...
SAVE_PATTERNS = {
ACT: re.compile(r"Checkpoint policy after step (\d+)"),
GROOT: re.compile(r"checkpoint-(\d+)"),
}
def parse_loss(line: str, policy: str) -> float | None:
"""The training loss on this line, or None if it carries none."""
pattern = LOSS_PATTERNS.get(policy)
if pattern is None:
return None
match = pattern.search(line)
if match is None:
return None
try:
return float(match.group(1))
except ValueError:
return None
def parse_save(line: str, policy: str) -> int | None:
"""The step of a checkpoint this line announces, or None."""
pattern = SAVE_PATTERNS.get(policy)
if pattern is None:
return None
match = pattern.search(line)
if match is None:
return None
try:
return int(match.group(1))
except ValueError:
return None
@dataclass
class PlateauDetector:
"""Relative-improvement plateau detection over a windowed mean.
Per-step loss is far too noisy to compare directly, so observations are
averaged into fixed-size windows and only window means are compared. A
window improves when it beats the best window seen by more than
``min_delta`` RELATIVE — relative because a run ending near 0.003 (GR00T)
and one ending near 0.4 (ACT) cannot share an absolute threshold.
"""
#: Loss observations per window. One observation is one logged line, so the
#: step span depends on the trainer's log frequency (ACT: log_freq=200).
window: int = 25
#: Consecutive windows without improvement before declaring a plateau.
patience: int = 4
#: Required relative improvement over the best window, e.g. 0.01 = 1%.
min_delta: float = 0.01
#: Observations to ignore before arming. Loss falls steeply at the start and
#: an early flat stretch is not convergence.
warmup: int = 100
_buffer: list = field(default_factory=list, repr=False)
_best: float | None = field(default=None, repr=False)
_stale: int = field(default=0, repr=False)
_seen: int = field(default=0, repr=False)
#: Set once a plateau is found. The caller stops at the next checkpoint.
plateaued: bool = field(default=False, repr=False)
reason: str = field(default="", repr=False)
def observe(self, loss: float) -> bool:
"""Feed one loss. Returns True once a plateau has been declared."""
if self.plateaued:
return True
self._seen += 1
self._buffer.append(loss)
if len(self._buffer) < self.window:
return False
mean = sum(self._buffer) / len(self._buffer)
self._buffer.clear()
if self._seen <= self.warmup:
# Still warming up: track the best so the first armed comparison is
# against something real, but never count staleness.
if self._best is None or mean < self._best:
self._best = mean
return False
if self._best is None or mean < self._best * (1.0 - self.min_delta):
self._best = min(mean, self._best) if self._best is not None else mean
self._stale = 0
return False
self._stale += 1
logger.info("no improvement for %d/%d window(s) (window mean %.5f, best %.5f)",
self._stale, self.patience, mean, self._best)
if self._stale >= self.patience:
self.plateaued = True
self.reason = (
f"loss plateaued: {self.patience} consecutive windows of {self.window} "
f"observations with no {self.min_delta:.1%} relative improvement over the "
f"best window mean ({self._best:.5f})")
return self.plateaued