"""Self-contained bootstrap that runs ON a Vast.ai instance. Replicates ``providers/runpod/train.py:_train_body`` semantics on the Vast substrate: install extra pip deps, fetch the autoslm package from the HF dataset repo, then run the substrate-neutral worker (``autoslm.engine.worker``) to train, uploading the console tail on failure. There is NO return channel from the instance: the worker's HF artifacts (DONE/metrics.json/heartbeat.json) are the success signal, and this bootstrap's attempt-scoped ``vast_attempt.json`` is the terminal marker the control plane keys failures on. This file is shipped verbatim inside the instance's onstart script (see ``providers/vast/jobs.py:build_onstart``), so it must stay self-contained: stdlib + huggingface_hub (installed with the worker deps) only — never import autoslm here. It reads its payload from ``/root/autoslm/payload.json``. """ from __future__ import annotations import contextlib import json import os import shutil import signal import subprocess import sys import threading import time PAYLOAD_PATH = "/root/autoslm/payload.json" CODE_ROOT = "/runcode" CODE_DIR = "/runcode/code" def load_payload(path: str = PAYLOAD_PATH) -> dict: with open(path) as f: return json.load(f) def hf_upload(payload: dict, local_path: str, repo_subpath: str) -> None: """Upload one artifact under the run's HF prefix; never raises.""" try: from huggingface_hub import HfApi HfApi(token=(payload.get("env") or {}).get("HUGGINGFACE_TOKEN")).upload_file( path_or_fileobj=local_path, path_in_repo=f"{payload['hf_prefix']}/{repo_subpath}", repo_id=payload["hf_repo"], repo_type="dataset", ) except Exception as exc: print(f"hf upload warn ({repo_subpath}): {exc}", flush=True) def build_worker_env(payload: dict) -> dict: env = dict(os.environ) env.update({k: str(v) for k, v in (payload.get("env") or {}).items()}) # Pass a large spec via a file, not the environment: a job spec with large inline # params can reach multiple hundred KB, and that big an env var trips execve's # "Argument list too long" when the worker subprocess starts. Mirrors # runpod/train.py:_train_body. spec_json = payload["job_spec_json"] if len(spec_json) > 96_000: with open("/tmp/job_spec.json", "w") as f: f.write(spec_json) env["AUTOSLM_JOB_SPEC_PATH"] = "/tmp/job_spec.json" env.pop("AUTOSLM_JOB_SPEC_JSON", None) else: env["AUTOSLM_JOB_SPEC_JSON"] = spec_json env["PHASE"] = payload["phase"] env["SEED"] = str(payload["seed"]) # Compute substrate for the RunMetrics record (engine.worker reads AUTOSLM_ARM). The # payload env was built by the shared runpod env builder, which stamps "runpod"; this # bootstrap runs on the Vast instance, so override it to the real backend. env["AUTOSLM_ARM"] = "vast" env["PYTHONPATH"] = CODE_DIR + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "") return env def fetch_code(payload: dict) -> None: from huggingface_hub import snapshot_download snapshot_download( repo_id=payload["hf_repo"], repo_type="dataset", allow_patterns=["code/**"], local_dir=CODE_ROOT, token=(payload.get("env") or {}).get("HUGGINGFACE_TOKEN"), ) def run_mode(payload: dict, env: dict, mode: str, deadline_ts: float) -> int: """One worker process; console teed to a file and streamed to the instance log. On failure the console tail is uploaded as console_.txt — like _train_body, because subprocess consoles are the only place engine-core crashes surface. On deadline the process is killed and we return a sentinel nonzero rc. """ console = f"/tmp/console_{mode}.txt" timed_out = False with open(console, "w") as cf: proc = subprocess.Popen( [sys.executable, "-m", "autoslm.engine.worker"], cwd=CODE_DIR, env={**env, "RUN_MODE": mode}, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) def pump(): for line in proc.stdout: print(line, end="", flush=True) cf.write(line) t = threading.Thread(target=pump, daemon=True) t.start() try: proc.wait(timeout=max(10.0, deadline_ts - time.time())) except subprocess.TimeoutExpired: timed_out = True proc.kill() proc.wait() t.join(timeout=10) if proc.returncode != 0 or timed_out: try: tail_path = console + ".tail" with open(console) as f: tail = f.read()[-64_000:] if timed_out: tail += f"\n--- bootstrap: mode '{mode}' hit the wall-clock cap; killed ---\n" with open(tail_path, "w") as f: f.write(tail) hf_upload(payload, tail_path, f"console_{mode}.txt") except Exception as exc: print(f"console upload warn: {exc}", flush=True) if timed_out: raise TimeoutError(f"worker mode '{mode}' exceeded the wall-clock cap") return proc.returncode def write_attempt_marker(payload: dict, ok: bool, error: str = "") -> None: """Attempt-scoped terminal marker: how the control plane distinguishes THIS attempt's failure from a prior attempt's leftovers under the same prefix.""" marker = { "ok": bool(ok), "ts": time.time(), "attempt": int(payload.get("attempt") or 0), "error": error[:2000], } p = "/tmp/vast_attempt.json" with open(p, "w") as f: json.dump(marker, f) hf_upload(payload, p, f"vast_attempt{marker['attempt']}.json") def main() -> int: # Make SIGTERM (vast stop / bash `timeout`) unwind through finally so the # terminal marker still gets uploaded. signal.signal(signal.SIGTERM, lambda *a: sys.exit(1)) payload = load_payload() ok = False error = "" try: # Fast model downloads on Vast: RunPod's Flash runtime ships hf_transfer + sets # HF_HUB_ENABLE_HF_TRANSFER, but Vast hosts don't — so a cold model pull is serial and # slow (measured ~84s for a 2 GB model vs ~6s on RunPod, where setup is now the dominant # cost). Install it + enable so snapshot_download/from_pretrained saturate the NIC. # Best-effort: only enable the flag if the package is present (enabling it WITHOUT the # package makes huggingface_hub hard-error). try: import importlib.util if importlib.util.find_spec("hf_transfer") is None: subprocess.run([sys.executable, "-m", "pip", "install", "hf_transfer"], check=True) os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1" except Exception as _e: print("hf_transfer setup skipped (slow downloads):", _e) # W&B logging (restored post-autoslm-migration): the prebuilt image predates wandb being # added to the stack, so install it on-demand when a W&B key is present. The worker's # wandb_report_to() gates report_to on the package actually importing, so this is what makes # W&B logging real on the current image without a rebuild. try: import importlib.util # local: the hf_transfer block above may fail before importing it _penv = payload.get("env") or {} if (_penv.get("WANDB_API_KEY") or os.environ.get("WANDB_API_KEY")) and ( importlib.util.find_spec("wandb") is None ): subprocess.run([sys.executable, "-m", "pip", "install", "wandb>=0.17"], check=False) print("[wandb] installed wandb on-demand for W&B logging") except Exception as _e: print("wandb setup skipped:", _e) # NB: the Hopper fla guard lives in engine.worker._drop_fla_on_hopper (runs in the worker # process after all installs, before any model import) — not here, where a later # install could pull fla back in. The bootstrap just fetches code and runs the worker. extra_pip = payload.get("extra_pip") or [] if extra_pip: # check=True: a deterministic dependency failure (GRPO / Prime Hub # / verifiers extras) must stop NOW with an actionable error, not proceed to # a later import crash while the paid instance runs (matches the RunPod path). subprocess.run([sys.executable, "-m", "pip", "install", *extra_pip], check=True) # Per-run package-version experiments: AUTOSLM_PIP_OVERRIDE is a whitespace-separated list # of pins installed ADDITIVELY on top of the (baked image) stack, so an A/B can try a # different transformers/vllm/kernels/fla/triton combo without rebuilding the image or a # global change. check=False: an experimental combo that fails resolution shouldn't abort # the run (it just trains on the existing stack); the worker logs what's actually installed. _pip_override = (payload.get("env") or {}).get("AUTOSLM_PIP_OVERRIDE") or os.environ.get( "AUTOSLM_PIP_OVERRIDE" ) if _pip_override: pkgs = [p for p in _pip_override.split() if p.strip()] if pkgs: subprocess.run([sys.executable, "-m", "pip", "install", *pkgs], check=False) print(f"[pip-override] installed experiment pins: {pkgs}") _wenv = payload.get("env") or {} # Optional Triton pin (Hopper fla-fast experiment): fla's Gated-DeltaNet Triton backward is # CORRECT on triton<3.4 (#640 only regresses >=3.4), so pinning an older triton restores # fla's fast kernel on H100 instead of the slow native fallback. torch eager doesn't # need triton (only inductor/compile does), so a downgrade is viable for SFT. Per-run via # worker_env so it never globally downgrades the 4090/5090 GRPO runs (vLLM needs new triton). _triton_pin = _wenv.get("AUTOSLM_TRITON_PIN") or os.environ.get("AUTOSLM_TRITON_PIN") if _triton_pin: subprocess.run( [sys.executable, "-m", "pip", "install", f"triton=={_triton_pin}"], check=False ) print(f"[triton] pinned triton=={_triton_pin} (Hopper fla-fast experiment)") # Hopper Gated-DeltaNet escape hatch: flash-linear-attention's Triton backward is wrong on # H100 (Triton>=3.4, fla #640) and its tilelang fallback aborts in TVM FFI. With # AUTOSLM_DISABLE_FLA=1, uninstall both so transformers uses its native (pure-PyTorch) # Gated-DeltaNet — correct everywhere (slower, but the only working Hopper path for Qwen3.5/3.6). # The knob travels in the PAYLOAD env (forwarded via the control plane allowlist), not the # container env — read it there (mirrors the PRIME_API_KEY lookup below). This MUST run AFTER # extra_pip: WORKER_DEPS lists flash-linear-attention, so an earlier uninstall gets silently # undone by the extra_pip reinstall — uninstalling here is the last word before training. if str(_wenv.get("AUTOSLM_DISABLE_FLA") or os.environ.get("AUTOSLM_DISABLE_FLA") or "") in ( "1", "true", "True", ): subprocess.run( [ sys.executable, "-m", "pip", "uninstall", "-y", "flash-linear-attention", "tilelang", ], check=False, ) print("[fla] uninstalled flash-linear-attention + tilelang (Hopper native delta-rule)") # Install the run's verifiers environment(s) from the Prime Hub via the # authenticated `prime` CLI (mirrors runpod/train.py:_train_body). The public pip # index does not serve PRIVATE env wheels; `prime env install` pulls/builds/installs # public + private alike, authenticated by PRIME_API_KEY forwarded in the payload env. hub_env_ids = payload.get("hub_env_ids") or [] if hub_env_ids: worker_env = {k: str(v) for k, v in (payload.get("env") or {}).items()} prime_key = worker_env.get("PRIME_API_KEY") or os.environ.get("PRIME_API_KEY") if not prime_key: raise RuntimeError( "PRIME_API_KEY is required to install the Prime Hub environment on the worker" ) # Only install `prime` when it isn't already present (it's often baked into the # instance image) — an unconditional install adds latency and a per-run PyPI # failure point every run. if shutil.which("prime") is None: subprocess.run([sys.executable, "-m", "pip", "install", "prime"], check=True) # Resolve the prime binary (located path if present, else the bare name) so the env # install runs through the actually-installed CLI. prime_bin = shutil.which("prime") or "prime" install_env = { **os.environ, "PRIME_API_KEY": prime_key, "PRIME_DISABLE_VERSION_CHECK": "1", "PIP_BREAK_SYSTEM_PACKAGES": "1", } # --with pip: install the env into THIS python via pip, not prime's isolated uv env # (the default), so the trainer can import the env module at load_environment. for env_id in hub_env_ids: subprocess.run( [prime_bin, "env", "install", env_id, "--with", "pip"], check=True, env=install_env, ) fetch_code(payload) env = build_worker_env(payload) deadline = time.time() + float(payload.get("max_wall_s") or 24 * 3600) phase = payload["phase"] # A warm/retried Vast instance can carry a previous attempt's metrics file; a # stale one would let a crashed train phase report the previous run's metrics. # Clear before training (mirrors the RunPod Flash handler in runpod/train.py). for stale in ("/tmp/train_meta.json", "/tmp/metrics.json"): with contextlib.suppress(FileNotFoundError): os.remove(stale) # Train. Nonzero rc tolerated — RL's colocated vLLM can segfault at interpreter # exit AFTER the adapter + metrics.json + DONE are saved. The train phase writes # metrics.json + DONE itself (or restores them from an earlier attempt's DONE). run_mode(payload, env, phase, deadline) if not os.path.exists("/tmp/metrics.json"): raise RuntimeError( f"train phase '{phase}' produced no /tmp/metrics.json (it crashed before " f"finishing); see error_{phase}.txt and console_{phase}.txt in the HF " f"dataset repo" ) ok = True except Exception as exc: # Record genuine failures in the attempt marker (written in `finally`). Don't catch # BaseException — KeyboardInterrupt/SystemExit must propagate after the marker write # rather than be swallowed into a `return 1`. error = f"{type(exc).__name__}: {exc}" print(f"bootstrap failed: {error}", flush=True) finally: write_attempt_marker(payload, ok, error) return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())