"""Single-node DLC supervisor: independent 1M-step S/M/L runs on 2/2/4 GPUs. Only this invocation's child process groups are stopped on failure/signal. No DSW keeper, platform submission, or old-run mutation occurs here. """ import argparse import csv import datetime import fcntl import json import math import os from pathlib import Path import signal import socket import subprocess import sys import tempfile import time from scale_loss_profile import JERK_WEIGHT_FIELDS ROOT = Path(__file__).resolve().parents[2] GROUP = ROOT / "scale/groups/sml_1m_224_a1e-4_o1e-5_nojerk" EFFECTIVE_MOTION_LR = 1e-4 EFFECTIVE_OMNI_LR = 1e-5 MAX_STEPS = 1_000_000 GLOBAL_BATCH = 48 LAYOUT = {"S": {"gpus": [0, 1], "port": 29752}, "M": {"gpus": [2, 3], "port": 29753}, "L": {"gpus": [4, 5, 6, 7], "port": 29754}} WORKERS = 8 # Per rank; 64 workers total for this eight-GPU job. def save(path, value): path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix=".pending-", delete=False) as f: json.dump(value, f, indent=2, ensure_ascii=False) f.write("\n") temp = f.name os.replace(temp, path) def command(size, mode="train", resume=None): args = [sys.executable, "-B", "-u", str(ROOT / "scale/script/train_scale.py"), "--size", size, "--experiment-root", str(GROUP), "--nproc", str(len(LAYOUT[size]["gpus"])), "--global-batch", str(GLOBAL_BATCH), "--max-steps", str(MAX_STEPS), "--workers", str(WORKERS), "--master-port", str(LAYOUT[size]["port"])] args += ["--resume", str(resume)] if resume else ["--init", "pretrained"] args += ["--effective-motion-lr", str(EFFECTIVE_MOTION_LR)] args += ["--effective-omni-lr", str(EFFECTIVE_OMNI_LR), "--disable-jerk-loss"] if mode != "train": args.append("--check-only" if mode == "check" else "--config-only") return args def child_env(size): env = os.environ.copy() # Do not let parent/DLC distributed settings merge the three torchrun jobs. for key in list(env): if key.startswith(("TORCHELASTIC_", "PET_")) or key in { "RANK", "LOCAL_RANK", "WORLD_SIZE", "LOCAL_WORLD_SIZE", "GROUP_RANK", "ROLE_RANK", "ROLE_WORLD_SIZE", "MASTER_ADDR", "MASTER_PORT", "NODE_RANK"}: env.pop(key, None) env.update(CUDA_DEVICE_ORDER="PCI_BUS_ID", CUDA_VISIBLE_DEVICES=",".join(map(str, LAYOUT[size]["gpus"])), PYTHONDONTWRITEBYTECODE="1", PSI_DATALOADER_PIN_MEMORY="1", PSI_DATALOADER_PREFETCH_FACTOR="1", PSI_WORKER_TORCH_THREADS="1", OPENBLAS_NUM_THREADS="1", MKL_NUM_THREADS="1", PSI_TRAIN_TORCH_THREADS="8", PSI_VIDEO_FAST_SEEK="1", WANDB_MODE=env.get("WANDB_MODE", "offline")) # All durable writable artifacts are isolated from the previous group. for key, relative in { "WANDB_DIR": f"wandb/{size}", "WANDB_CACHE_DIR": f"cache/wandb/{size}", "WANDB_CONFIG_DIR": f"config/wandb/{size}", "WANDB_DATA_DIR": f"wandb_data/{size}", "TRITON_CACHE_DIR": f"cache/triton/{size}", "TORCH_EXTENSIONS_DIR": f"cache/torch_extensions/{size}", }.items(): destination = GROUP / relative destination.mkdir(parents=True, exist_ok=True) env[key] = str(destination) env["TMPDIR"] = tempfile.mkdtemp(prefix=f"movens-1m-{size}-", dir="/tmp") return env def require_idle_eight_gpus(): raw = subprocess.check_output(["nvidia-smi", "--query-gpu=index,uuid,memory.used", "--format=csv,noheader,nounits"], text=True, timeout=10) devices = {int(r[0]): (r[1].strip(), float(r[2])) for r in csv.reader(raw.splitlines())} if set(devices) != set(range(8)): raise RuntimeError("This launcher requires one DLC node with exactly eight GPUs (0–7).") raw = subprocess.check_output(["nvidia-smi", "--query-compute-apps=gpu_uuid,pid", "--format=csv,noheader,nounits"], text=True, timeout=10) allocated = {r[0].strip() for r in csv.reader(raw.splitlines()) if r} busy = [index for index, (uuid, memory) in devices.items() if uuid in allocated or memory >= 500] if busy: raise RuntimeError(f"GPUs already occupied: {busy}. No existing process will be killed; use a fresh DLC job.") for size, spec in LAYOUT.items(): with socket.socket() as sock: try: sock.bind(("127.0.0.1", spec["port"])) except OSError as exc: raise RuntimeError(f"Port {spec['port']} for {size} is occupied") from exc return devices def verify_group_config(size, path): cfg = json.loads(path.read_text()) train = cfg["train"] if cfg.get("world_size_expected") != len(LAYOUT[size]["gpus"]) or train["max_training_steps"] != MAX_STEPS: raise ValueError(f"{size}: unexpected GPU count or step budget") if train["train_batch_size"] * cfg["world_size_expected"] != GLOBAL_BATCH or train["gradient_accumulation_steps"] != 1: raise ValueError(f"{size}: unexpected batch/accumulation") if not Path(train["output_dir"]).resolve().is_relative_to(GROUP.resolve()): raise ValueError("Output escaped the isolated group") if cfg.get("initial_action_checkpoint") or cfg.get("warmstart_checkpoint"): raise ValueError("Old model warmstarts are not part of the new experiment") multiplier = cfg["absolute_height_stage"]["lr_scale"] if not math.isclose(train["learning_rate"] * multiplier, EFFECTIVE_MOTION_LR, rel_tol=1e-12): raise ValueError(f"{size}: effective action LR must be {EFFECTIVE_MOTION_LR}") if not math.isclose(cfg["model"]["lang_backbone_lr"] * multiplier, EFFECTIVE_OMNI_LR, rel_tol=1e-12): raise ValueError(f"{size}: Omni LR must remain {EFFECTIVE_OMNI_LR}") if any(train[key] != 0 for key in JERK_WEIGHT_FIELDS): raise ValueError(f"{size}: every jerk loss coefficient must be zero") return cfg def resume_checkpoint(size): pointer = GROUP / "runs" / f"latest_{size}.json" if not pointer.exists(): return None, False run = Path(json.loads(pointer.read_text())["run_dir"]).resolve() if not run.is_relative_to((GROUP / "runs").resolve()): raise ValueError("Refusing a pointer outside this experiment") cfg = verify_group_config(size, run / "run_config.json") # A partially written checkpoint is not a valid resume point. Require the # original save-completion marker and all ranks' RNG files, then rely on # train_scale's full-state/header validation before starting any worker. sys.path.insert(0, str(ROOT)) from dashboard.training_dashboard import TrainingLog log = TrainingLog(run / "training.log") log.update() complete = sorted(log.completed_checkpoints, reverse=True) needed = ["model.safetensors", "optimizer.bin", "scheduler.bin", "custom_checkpoint_0.pkl", "custom_checkpoint_1.pkl"] needed += [f"random_states_{rank}.pkl" for rank in range(cfg["world_size_expected"])] for step in complete: checkpoint = run / "checkpoints" / f"ckpt_{step}" if all((checkpoint / f).is_file() and (checkpoint / f).stat().st_size > 0 for f in needed): return checkpoint, step >= MAX_STEPS raise RuntimeError(f"{size} has a run pointer but no confirmed complete checkpoint; refusing to silently restart from zero.") def supervise(specs, status_path): children, handles = {}, [] status = dict(group=str(GROUP), max_steps=MAX_STEPS, global_batch=GLOBAL_BATCH, host=socket.gethostname(), state="starting", jobs={}) def interrupted(signum, frame): raise InterruptedError(f"Launcher received signal {signum}") previous = {sig: signal.signal(sig, interrupted) for sig in (signal.SIGTERM, signal.SIGINT)} ok = False try: for size, cmd, env in specs: log_path = status_path.parent / f"{size}.log" handle = log_path.open("a") handles.append(handle) child = subprocess.Popen(cmd, cwd=ROOT, env=env, stdout=handle, stderr=subprocess.STDOUT, start_new_session=True) children[size] = child status["jobs"][size] = dict(pid=child.pid, gpus=LAYOUT[size]["gpus"], log=str(log_path), exit_code=None) save(status_path, status) status["state"] = "running" while True: for size, child in children.items(): status["jobs"][size]["exit_code"] = child.poll() status["updated_at"] = datetime.datetime.now().isoformat() save(status_path, status) failures = [s for s, c in children.items() if c.returncode is not None and c.returncode != 0] if failures: raise RuntimeError(f"New-group member failed: {failures}; inspect {status_path.parent}. Stopping only sibling jobs from this invocation.") if all(c.returncode == 0 for c in children.values()): ok = True break time.sleep(3) except BaseException as exc: status["error"] = str(exc) raise finally: # Ignore a second termination while cleaning up our known process groups. for sig in previous: signal.signal(sig, signal.SIG_IGN) if not ok: for child in children.values(): if child.returncode == 0: continue try: os.killpg(child.pid, signal.SIGTERM) except ProcessLookupError: pass deadline = time.monotonic() + 30 for child in children.values(): try: child.wait(timeout=max(.1, deadline-time.monotonic())) except subprocess.TimeoutExpired: try: os.killpg(child.pid, signal.SIGKILL) except ProcessLookupError: pass child.wait() for size, child in children.items(): status["jobs"][size]["exit_code"] = child.returncode status["state"] = "completed" if ok else "failed_or_interrupted" status["updated_at"] = datetime.datetime.now().isoformat() save(status_path, status) for handle in handles: handle.close() for sig, handler in previous.items(): signal.signal(sig, handler) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--config-only", action="store_true", help="Build isolated configs without any CUDA initialization") parser.add_argument("--check-only", action="store_true", help="Validate all source groups; never start a worker") parser.add_argument("--resume-existing", action="store_true", help="Resume only this group's confirmed complete checkpoints") args = parser.parse_args() diagnostic = args.config_only or args.check_only GROUP.mkdir(parents=True, exist_ok=True) with (GROUP / ".launcher.lock").open("a") as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: raise RuntimeError("This experiment already has an active launcher; no duplicate launch allowed.") pointers = list((GROUP / "runs").glob("latest_*.json")) if pointers and not args.resume_existing: raise RuntimeError("This group already contains training runs. Use --resume-existing; previous pointers/results will not be overwritten by a fresh run.") if not diagnostic: require_idle_eight_gpus() mode = "check" if args.check_only or not diagnostic else "config" prepared = [] for size in LAYOUT: checkpoint, done = resume_checkpoint(size) if args.resume_existing else (None, False) if done: print(f"{size}: already completed {MAX_STEPS} steps; skip", flush=True) continue env = child_env(size) if diagnostic: env["CUDA_VISIBLE_DEVICES"] = "" # Sequential data/config preflight avoids cache initialization races. subprocess.run(command(size, mode, checkpoint), cwd=ROOT, env=env, check=True) verify_group_config(size, GROUP / "validation" / size / "launch_config.json") prepared.append((size, command(size, "train", checkpoint), env)) if diagnostic: print(json.dumps(dict(status="preflight_only_no_training", group=str(GROUP), max_steps=MAX_STEPS, layout=LAYOUT), indent=2), flush=True) return # Recheck after preflight: do not displace jobs started in the meantime. require_idle_eight_gpus() stamp = datetime.datetime.now().strftime("%y%m%d%H%M%S%f") status_path = GROUP / "jobs" / stamp / "status.json" status_path.parent.mkdir(parents=True) save(GROUP / "jobs/latest.json", dict(status_file=str(status_path))) print(json.dumps(dict(group=str(GROUP), status_file=str(status_path), layout=LAYOUT), indent=2), flush=True) supervise(prepared, status_path) if __name__ == "__main__": main()