Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 90 additions & 7 deletions tools/colab_fleet.py
Original file line number Diff line number Diff line change
Expand Up @@ -916,11 +916,59 @@ def _reset_session_workspace(self, sess_name: str, cfg_path: Path, acc_class: st
" pass\n"
"print('fleet_workspace_reset_ok')\n"
)
p = self._run_colab_with_cfg(cfg_path, ["exec", "-s", sess_name, "--timeout", "30", "-c", code], timeout_s=45, request_timeout_s=30)
reset_script = self.cfg_dir / "_reset_workspace.py"
with self._lock:
if not reset_script.is_file():
tmp_reset = self.cfg_dir / f"._reset_workspace.{uuid.uuid4().hex[:6]}.tmp"
tmp_reset.write_text(code, encoding="utf-8")
os.replace(tmp_reset, reset_script)
p = self._run_colab_with_cfg(
cfg_path,
["exec", "-s", sess_name, "--timeout", "30", "-f", str(reset_script)],
timeout_s=45,
request_timeout_s=30,
)
with self._lock:
self._workspace_resets_count += 1
self.log_event("session_workspace_reset", {"session": sess_name, "class": acc_class, "rc": p.returncode})

def _unassign_orphan_endpoint(self, endpoint: str, sku: str) -> Dict[str, Any]:
"""Release a newly appeared unnamed runtime endpoint left behind by a READ_TIMEOUT assign."""
if self._custom_runner is not None:
p = self._custom_runner(["unassign-endpoint", endpoint], 45)
rec = {"endpoint": endpoint, "sku": sku, "rc": p.returncode}
self.log_event("orphan_endpoint_reaped", rec)
return rec
colab_py = Path(self.colab_bin).resolve().parent / "python"
if not colab_py.is_file():
rec = {"endpoint": endpoint, "sku": sku, "rc": -1, "error": "colab_python_not_found"}
self.log_event("orphan_endpoint_reaped", rec)
return rec
auth_enum = "ADC" if self.auth == "adc" else "OAUTH2"
snippet = (
"import sys\n"
"from colab_cli.common import state\n"
"from colab_cli.auth import AuthProvider\n"
f"state.auth_provider = AuthProvider.{auth_enum}\n"
"state.client.unassign(sys.argv[1])\n"
)
try:
p = subprocess.run(
[str(colab_py), "-c", snippet, endpoint],
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=45,
)
rc = p.returncode
except Exception as exc:
rc = -1
self.log_event("orphan_endpoint_reaped", {"endpoint": endpoint, "sku": sku, "rc": rc, "error": redact_secrets(str(exc))[:160]})
return {"endpoint": endpoint, "sku": sku, "rc": rc}
rec = {"endpoint": endpoint, "sku": sku, "rc": rc}
self.log_event("orphan_endpoint_reaped", rec)
return rec

def _can_admit_slot(
self,
acc_class: str,
Expand Down Expand Up @@ -1098,9 +1146,27 @@ def _provision_job_session(self, job: FleetJob) -> Tuple[Optional[str], Optional
})
if err_code == "READ_TIMEOUT":
after = self.list_sessions()
leaked = [s for s in after if s["name"] == sess_name]
if leaked:
leaked_named = [s for s in after if s["name"] == sess_name]
if leaked_named:
self.stop_owned_session(sess_name)
else:
# Colab may finish allocating after client read timeout without writing sessions.json,
# appearing as `[?] <endpoint>`. Reap ONLY newly appeared matching-kind endpoints.
with self._lock:
owned_eps = {
str((meta.get("assignment") or {}).get("endpoint", ""))
for meta in self._owned_sessions.values()
}
for cand in after:
ep = cand.get("endpoint", "")
if (
ep
and ep not in before_eps
and ep not in owned_eps
and cand.get("name") == "?"
and cand.get("kind") == SKU_KIND[sku]
):
self._unassign_orphan_endpoint(ep, sku)
if err_code == "429_RATE_LIMITED":
# Strictly ToS-clean: stop immediately on 429, zero retry hammering
return None, None, None, err_code
Expand Down Expand Up @@ -1167,10 +1233,27 @@ def _execute_one_job(
exec_args.extend(["-f", str(job.script)])
p = self._run_colab_with_cfg(cfg_path, exec_args, timeout_s=job.timeout_s + 120, request_timeout_s=120)
rc = p.returncode
log_path.write_text(redact_secrets((p.stdout or "") + "\n" + (p.stderr or "")), encoding="utf-8")
if job.downloads:
self.sync.collect_outputs(sess_name, job.downloads)
note = "ok" if rc == 0 else f"exec_rc_{rc}"
combined_out = (p.stdout or "") + "\n" + (p.stderr or "")
log_path.write_text(redact_secrets(combined_out), encoding="utf-8")
dl_recs = self.sync.collect_outputs(sess_name, job.downloads) if job.downloads else []
failed_dls = [
str(r.get("remote", ""))
for r in dl_recs
if r.get("direction") == "download" and not r.get("ok")
]
has_tb = (
"Traceback (most recent call last)" in combined_out
or "---------------------------------------------------------------------------" in combined_out
)
if rc == 0 and failed_dls:
rc = 1
if has_tb:
note = "ipython_exception_missing_outputs"
else:
missing_names = ",".join(Path(x).name for x in failed_dls[:3])
note = f"missing_outputs:{missing_names}"
else:
note = "ok" if rc == 0 else f"exec_rc_{rc}"
except Exception as exc:
note = redact_secrets(f"{type(exc).__name__}: {exc}")[:200]
rc = 1
Expand Down
23 changes: 21 additions & 2 deletions tools/h100_fast_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,18 +215,36 @@ def _is_weighted_rmsnorm(mod: Any) -> bool:
return nn is not None and isinstance(weight, nn.Parameter) and weight.ndim == 1


def _is_looped_model(model: Any, explicit: bool | None = None) -> bool:
"""Detect looped/recurrent-depth models (e.g. 36-loop Inkling-2 MoE) whose activation footprint overflows 80 GiB without GC."""
if explicit is not None:
return bool(explicit)
cfg = getattr(model, "config", None)
if cfg is None:
return False
for attr in ("num_loop_steps", "loop_count", "num_loops", "num_recurrent_steps"):
val = getattr(cfg, attr, None)
if isinstance(val, int) and val > 1:
return True
return False


def configure_liger_and_checkpointing(
model: Any,
vram_gb: float | None = None,
disable_gc_threshold_gb: float = 70.0,
enable_liger: bool = True,
patch_rmsnorm: bool = True,
final_logit_softcap: float | None = 30.0,
looped_model: bool | None = None,
looped_disable_gc_threshold_gb: float = 110.0,
) -> dict[str, Any]:
"""Apply VRAM-aware gradient checkpointing + Inkling-2-safe Liger kernel configuration."""
_require_torch()
resolved_vram = detect_gpu_vram_gb(vram_gb)
should_disable_gc = resolved_vram >= disable_gc_threshold_gb
is_looped = _is_looped_model(model, explicit=looped_model)
effective_threshold_gb = looped_disable_gc_threshold_gb if is_looped else disable_gc_threshold_gb
should_disable_gc = resolved_vram >= effective_threshold_gb

gc_state = "unchanged"
if should_disable_gc:
Expand Down Expand Up @@ -330,7 +348,8 @@ def _fwd(hidden_states: Any) -> Any:

return {
"vram_gb": resolved_vram,
"disable_gc_threshold_gb": disable_gc_threshold_gb,
"looped_model": is_looped,
"disable_gc_threshold_gb": effective_threshold_gb,
"gradient_checkpointing": gc_state,
"gradient_checkpointing_enabled": not should_disable_gc,
"liger": liger_info,
Expand Down
115 changes: 114 additions & 1 deletion tools/test_colab_fleet.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ def runner(args, _to):
sessions.pop(args[args.index("-s") + 1], None)
return subprocess.CompletedProcess(args, 0, "stopped\n", "")
if cmd == "exec":
if "-c" in args and "fleet_workspace_reset_ok" in args[args.index("-c") + 1]:
if "-f" in args and Path(args[args.index("-f") + 1]).name == "_reset_workspace.py":
reset_calls += 1
return subprocess.CompletedProcess(args, 0, "ok\n", "")
return subprocess.CompletedProcess(args, 0, "", "")
Expand Down Expand Up @@ -409,6 +409,119 @@ def test_offpeak_window_and_heavy_gpu_stacking_cap(self) -> None:
self.assertEqual(disp_off._heavy_gpu_slot_cap(), 3)
self.assertEqual(disp_peak._heavy_gpu_slot_cap(), 2)

def test_read_timeout_reaps_newly_appeared_orphan_preserving_external(self) -> None:
"""If `colab new --tpu V5E1` hits READ_TIMEOUT after Google allocates `[?] tpu-v5e1-...`, reap ONLY the new orphan."""
import subprocess
import threading

with tempfile.TemporaryDirectory(prefix="freetpu_orphan_") as td:
td_p = Path(td)
worker = td_p / "w.py"
worker.write_text("print('ok')\n", encoding="utf-8")
live_eps: dict[str, str] = {
"gpu-a100-s-usc1f0-ext": "[?] gpu-a100-s-usc1f0-ext | Hardware: A100 | Shape: Standard | Variant: GPU",
}
unassigned: list[str] = []
lock = threading.Lock()

def runner(args, _to):
cmd = args[0]
with lock:
if cmd == "usage":
return subprocess.CompletedProcess(
args, 0, f"Current balance: 7000.00 compute units\nUsage rate: 3.26/hr\nActive assignments: {len(live_eps)}\n", ""
)
if cmd == "sessions":
return subprocess.CompletedProcess(args, 0, "\n".join(live_eps.values()) + "\n", "")
if cmd == "new":
# Simulate server creating runtime right as client read times out (unnamed `[?]`)
live_eps["tpu-v5e1-s-r-usw4a0-orphan1"] = (
"[?] tpu-v5e1-s-r-usw4a0-orphan1 | Hardware: V5E1 | Shape: Standard | Variant: TPU"
)
return subprocess.CompletedProcess(args, 1, "", "ReadTimeout: The read operation timed out")
if cmd == "unassign-endpoint":
ep = args[1]
unassigned.append(ep)
live_eps.pop(ep, None)
return subprocess.CompletedProcess(args, 0, "ok\n", "")
return subprocess.CompletedProcess(args, 0, "", "")

disp = cf.ColabFleetDispatcher(
colab_bin="colab",
auth="adc",
run_dir=td_p / "run",
governor_cfg=cf.CuGovernorConfig(max_tpu_slots=1, max_total_slots=4),
spawn_spacing_s=0.0,
command_runner=runner,
)
jobs = [cf.FleetJob("tpu_orphan_test", 1, "TPU", worker, sku_preference=("V5E1",))]
proof = disp.run_queue(jobs)
self.assertEqual(unassigned, ["tpu-v5e1-s-r-usw4a0-orphan1"])
self.assertEqual(proof["teardown"]["external_sessions_preserved"], ["gpu-a100-s-usc1f0-ext"])
self.assertTrue(proof["teardown"]["zero_fleet_leaked"])

def test_ipython_traceback_with_missing_download_marks_failed(self) -> None:
"""If IPython raises FileNotFoundError yet `colab exec` exits 0 and expected downloads fail, mark job failed."""
import subprocess
import threading

with tempfile.TemporaryDirectory(prefix="freetpu_tb_") as td:
td_p = Path(td)
worker = td_p / "w.py"
worker.write_text("raise FileNotFoundError('missing')\n", encoding="utf-8")
out_json = td_p / "out.json"
sessions: dict[str, str] = {}
lock = threading.Lock()

def runner(args, _to):
cmd = args[0]
with lock:
if cmd == "usage":
return subprocess.CompletedProcess(
args, 0, f"Current balance: 7000.00 compute units\nUsage rate: 0.26/hr\nActive assignments: {len(sessions)}\n", ""
)
if cmd == "sessions":
return subprocess.CompletedProcess(args, 0, "\n".join(sessions.values()) + "\n", "")
if cmd == "new":
sname = args[args.index("-s") + 1]
sessions[sname] = f"[{sname}] m-hm-usc1c0-tb1 | Hardware: CPU | Shape: High-RAM | Variant: DEFAULT"
return subprocess.CompletedProcess(args, 0, "ok\n", "")
if cmd == "stop":
sessions.pop(args[args.index("-s") + 1], None)
return subprocess.CompletedProcess(args, 0, "stopped\n", "")
if cmd == "exec":
return subprocess.CompletedProcess(
args, 0,
"---------------------------------------------------------------------------\nFileNotFoundError: missing\n",
"",
)
if cmd == "download":
return subprocess.CompletedProcess(args, 1, "", "404 Not Found")
return subprocess.CompletedProcess(args, 0, "", "")

disp = cf.ColabFleetDispatcher(
colab_bin="colab",
auth="adc",
run_dir=td_p / "run",
governor_cfg=cf.CuGovernorConfig(max_cpu_slots=1, max_total_slots=2),
spawn_spacing_s=0.0,
command_runner=runner,
)
jobs = [
cf.FleetJob(
"crash_job",
1,
"CPU",
worker,
sku_preference=("CPU_HM",),
downloads=(("/content/out.json", out_json),),
)
]
proof = disp.run_queue(jobs)
self.assertEqual(proof["jobs"]["crash_job"]["status"], "failed")
self.assertEqual(proof["jobs"]["crash_job"]["note"], "ipython_exception_missing_outputs")
self.assertTrue(proof["teardown"]["zero_fleet_leaked"])


def main() -> int:
parser = argparse.ArgumentParser(description="Unit tests for tools/colab_fleet.py")
Expand Down
22 changes: 22 additions & 0 deletions tools/test_h100_fast_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,28 @@ def __init__(self):
self.assertFalse(fp8["active"])
self.assertEqual(fp8["eligible_linear_layers"], 1) # q_proj only (lm_head & 64-out gate skipped)

def test_looped_model_keeps_gc_enabled_on_80gb(self) -> None:
class _Cfg:
num_loop_steps = 36

class _LoopedM(nn.Module):
def __init__(self):
super().__init__()
self.config = _Cfg()
self.gradient_checkpointing = False
self.proj = nn.Linear(32, 32)

lm = _LoopedM()
c80 = hfk.configure_liger_and_checkpointing(lm, vram_gb=80.0, enable_liger=False)
self.assertTrue(c80["looped_model"])
self.assertEqual(c80["disable_gc_threshold_gb"], 110.0)
self.assertTrue(c80["gradient_checkpointing_enabled"])
self.assertTrue(lm.gradient_checkpointing)

c141 = hfk.configure_liger_and_checkpointing(lm, vram_gb=141.0, enable_liger=False)
self.assertFalse(c141["gradient_checkpointing_enabled"])
self.assertFalse(lm.gradient_checkpointing)


def main() -> int:
parser = argparse.ArgumentParser(description="Unit tests for tools/h100_fast_kernels.py")
Expand Down
Loading