Skip to content

[Train] Shut down failed worker group before sizing replacement - #67651

Open
ryanaoleary wants to merge 4 commits into
ray-project:masterfrom
ryanaoleary:train-elastic-recovery
Open

ryanaoleary wants to merge 4 commits into
ray-project:masterfrom
ryanaoleary:train-elastic-recovery

Conversation

@ryanaoleary

@ryanaoleary ryanaoleary commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Two teardown bugs in Ray Train V2 leave resources stuck or stall recovery when a worker group fails or restarts:

  1. Simplify elastic TPU scaling to use simpler slice counting (ray#62141) deferred worker group teardown from the restart scaling path to resize execution. When an elastic run drops below its minimum worker count, the scaling policy returns a no-op decision on every poll and resize execution never runs. Surviving worker actors and their placement group stay alive and hold nodes and TPU /dev/vfio devices while training waits for capacity.
  2. The backend setup callback ran collective teardown during every worker group shutdown, even when workers errored or had not finished cleanly. When a peer has died or a collective is hung, dispatching JAX or PyTorch distributed teardown onto surviving actors hits 5s to 30s shutdown timeouts and prevents worker shutdown callbacks from running. During mid-step elastic resizes, it can also race active collectives on the training thread.

Behavior changes

Before asking the scaling policy for a replacement size, the controller now shuts down the failed worker group unless a proper subset of replica groups can be replaced in place under Ray Train manages TorchFT replica group restarts (ray#61475):

# TrainController._make_and_handle_scaling_decision_for_non_running_worker_group
if self._worker_group and not self._can_partially_replace_replica_groups():
    self._shutdown_worker_group()

scaling_decision = self._scaling_policy.make_decision_for_non_running_worker_group()

Shutdown clears the worker group reference, so teardown runs once on restart and is skipped on later no-op polls and during resize execution. Partial replica-group failures keep the worker group intact for in-place replacement; full replica-group failures and restarts with no failing workers tear down immediately.

During shutdown, the backend setup callback now skips graceful collective teardown when the latest poll status has errors or is unfinished, matching Ray Train V1 restart behavior:

# BackendSetupCallback.before_worker_group_shutdown
def before_worker_group_shutdown(self, worker_group: WorkerGroup):
    poll_status = worker_group.get_latest_poll_status()
    if poll_status and (poll_status.errors or not poll_status.finished):
        logger.debug(
            "Skipping graceful backend shutdown because the worker group "
            "did not finish cleanly (errors=%s, finished=%s).",
            bool(poll_status.errors),
            poll_status.finished,
        )
        return
    self.before_execution_group_shutdown(worker_group)

Worker group cleanup also resets the cached poll status alongside the rest of its state. Cleanly finished runs, unpolled direct worker group shutdowns, and single replica-group replacements still run graceful backend teardown.

Related issue number

Contributes to [Train] JaxTrainer Implementation Tracking Issue (ray#55162) and [Core][Train] Support Torch runtime with TPUs (ray#64055).
Complements [Train] Wait for worker TPU VFIO devices before distributed init (ray#67756).

Checks

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@ryanaoleary

Copy link
Copy Markdown
Contributor Author

Manual Testing Steps

Step 1: Deploy a TPU v7x RayCluster (two single-host 2x2x1 slices)

The containers run ray start followed by sleep infinity, so the test can stop and restart one slice's Ray node without KubeRay restarting the pod.

apiVersion: ray.io/v1
kind: RayCluster
metadata:
  name: ray-tpu-elastic-verify
spec:
  headGroupSpec:
    rayStartParams: {}
    template:
      metadata:
        annotations:
          ray.io/overwrite-container-cmd: "true"
      spec:
        containers:
          - name: ray-head
            image: us-central1-docker.pkg.dev/tpu-vm-gke-testing/ray-torchtpu/ray-torchtpu:latest
            command: ["/bin/bash", "-lc"]
            args:
              - ray start --head --port=6379 --dashboard-host=0.0.0.0 --dashboard-agent-listen-port=52365 --num-cpus=0 && sleep infinity
  workerGroupSpecs:
    - groupName: tpu-group
      replicas: 2
      numOfHosts: 1
      rayStartParams: {}
      template:
        metadata:
          annotations:
            ray.io/overwrite-container-cmd: "true"
        spec:
          nodeSelector:
            cloud.google.com/gke-tpu-accelerator: tpu7x
            cloud.google.com/gke-tpu-topology: 2x2x1
          containers:
            - name: ray-worker
              image: us-central1-docker.pkg.dev/tpu-vm-gke-testing/ray-torchtpu/ray-torchtpu:latest
              command: ["/bin/bash", "-lc"]
              args:
                - ray start --address=ray-tpu-elastic-verify-head-svc:6379 --dashboard-agent-listen-port=52365 --resources='{"TPU":4}' && sleep infinity
              resources:
                limits:
                  google.com/tpu: "4"
                requests:
                  google.com/tpu: "4"

Step 2: Apply PR Changes to Cluster Pods

To capture the master baseline, run Step 3 before this step, once with --only test1 and once with --only test2. Master fails Test 1, which ends the script. Then copy controller.py from this PR onto every pod. elastic.py and the rest of Ray stay at master:

for pod in $(kubectl get pods -l ray.io/cluster=ray-tpu-elastic-verify -o jsonpath='{.items[*].metadata.name}'); do
  dst=$(kubectl exec "$pod" -- python3 -c 'import ray.train.v2._internal.execution.controller.controller as m; print(m.__file__)')
  kubectl cp python/ray/train/v2/_internal/execution/controller/controller.py "$pod:$dst"
  kubectl exec "$pod" -- sh -c "rm -rf $(dirname "$dst")/__pycache__"
done

Step 3: Run End-to-End Verification Script

The script runs two JaxTrainer jobs across both slices. Each training step updates a 1024×1024 weight under shard_map, averages gradients with pmean across all TPU devices, and commits a checkpoint from rank 0. Checkpoints go to an in-memory filesystem hosted by a named actor on the head node, so no cloud bucket is needed. --storage-path gs://... uses GCS instead. The driver runs with log_to_driver=False, and a Train callback relays controller state transitions, worker group shutdowns, and resize decisions to the driver, which prints them:

  • Test 1 uses num_workers=(2, 2). During step 2, it stops the Ray node on the slice that doesn't host rank 0 (ray stop --grace-period 1), which leaves the run below min_workers. It checks that the controller waits in RestartingState with no placement groups left and the surviving slice's TPUs free. Then it runs a standalone TPU task on the surviving slice, restarts the stopped node, and checks that training resumes from the step 1 checkpoint.
  • Test 2 uses num_workers=(1, 2). It stops the same slice during step 2 and checks that training recovers onto one slice without a startup timeout, and that the worker group shutdown comes before the resize decision.

Save the following script as run_tpu_elastic_recovery_manual_test.py:

"""Manual TPU7x E2E verification for Ray Train elastic controller teardown."""

import argparse
import contextlib
import errno
import io
import os
import pickle
import resource
import socket
import subprocess as sp
import sys
import time
import fsspec
from fsspec.implementations.memory import MemoryFileSystem
import numpy as np
import pyarrow.fs
import ray
import ray.train as rt
from ray.train.v2._internal.exceptions import WorkerGroupStartupTimeoutError
from ray.train.v2._internal.execution import callback as cb
from ray.train.v2.jax import JaxTrainer
from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy as Pin
from ray.util.tpu import get_tpu_worker_resources

HEAD = os.environ.get("RAY_HEAD_SVC", "ray-tpu-elastic-verify-head-svc:6379")
TOPO, ACCEL = "2x2x1", "TPU-V7X"
_AGENT = """import shutil, socket, subprocess as sp, sys, time
s = socket.create_server(("0.0.0.0", int(sys.argv[1])))
print("OK", flush=True); time.sleep(0.1)
sp.run(["ray", "stop", "--grace-period", "1"], capture_output=True)
shutil.rmtree("/tmp/tpu_logs", ignore_errors=True); s.settimeout(300)
c, _ = s.accept()
if c.recv(8) == b"rejoin":
    r = f'--resources={{"TPU":{sys.argv[3]}}}'
    sp.run(["ray", "start", f"--address={sys.argv[2]}", r], capture_output=True, check=True)
    c.sendall(b"OK")
c.close(); s.close()
"""


@ray.remote(num_cpus=0)
class _Hub:
    def __init__(self):
        self.fs, self.ev, self.logs = MemoryFileSystem(), [], []

    def fs_call(self, fn: str, *a, **kw):
        r = getattr(self.fs, fn)(*a, **kw)
        if fn == "info":
            return {**r, "name": r["name"].lstrip("/")}
        if fn == "ls":
            return [
                {**x, "name": x["name"].lstrip("/")}
                if isinstance(x, dict)
                else x.lstrip("/")
                for x in r
            ]
        return r

    def reset(self):
        self.ev, self.logs = [], []

    def put(self, k: str, v=None, m: str = ""):
        if m:
            self.logs.append(m)
        self.ev.append((k, time.time(), v))

    def snap(self):
        logs, self.logs = self.logs, []
        return list(self.ev), logs


class _MemFS(fsspec.AbstractFileSystem):
    protocol, cachable = "rayshared", False

    def __reduce__(self):
        return (_MemFS, ())

    def _call(self, fn: str, *a, **kw):
        return ray.get(ray.get_actor("hub").fs_call.remote(fn, *a, **kw))

    def _open(self, path, mode="rb", **kw):
        if "r" in mode:
            return io.BytesIO(self._call("cat_file", path))
        b, orig = io.BytesIO(), None

        def _close():
            if not b.closed:
                self._call("pipe_file", path, b.getvalue())
            orig()

        orig, b.close = b.close, _close
        return b


def _fwd(fn: str):
    def _m(self, *a, **kw):
        return self._call(fn, *a, **kw)

    return _m


for _fn in ("mkdir", "makedirs", "rm", "info", "ls"):
    setattr(_MemFS, _fn, _fwd(_fn))


class AuditCallback(cb.ControllerCallback, cb.WorkerGroupCallback, cb.ReportCallback):
    def _put(self, k: str, v=None, m: str = ""):
        ray.get(ray.get_actor("hub").put.remote(k, v, m))

    def after_report(self, training_report, metrics):
        if training_report.checkpoint:
            s = training_report.metrics["step"]
            self._put("ckpt", s, f"[Controller] Committed checkpoint (step={s})")

    def after_controller_state_update(self, prev, curr):
        p, c = type(prev).__name__, type(curr).__name__
        self._put("state", c, f"[Controller] {p} -> {c}" if p != c else "")
        if isinstance(
            getattr(curr, "training_failed_error", None), WorkerGroupStartupTimeoutError
        ):
            self._put("timeout", 1, "[Controller] WorkerGroupStartupTimeoutError")

    def before_worker_group_shutdown(self, wg):
        n = len(wg.get_workers())
        self._put("wg_shutdown", n, f"[Controller] WorkerGroup.shutdown(size={n})")

    def before_controller_execute_resize_decision(self, d):
        self._put(
            "resize",
            d.num_workers,
            f"[Controller] ResizeDecision(num_workers={d.num_workers})",
        )


@ray.remote(num_cpus=0)
def _stop_slice(port: int, tpu: int) -> str:
    cmd = [sys.executable, "-u", "-c", _AGENT, str(port), HEAD, str(tpu)]
    return sp.Popen(
        cmd, stdout=sp.PIPE, text=True, start_new_session=True
    ).stdout.readline()


@ray.remote(max_calls=1)
def verify_surviving_slice_vfio() -> dict:
    vfio = sorted(f"/dev/vfio/{d}" for d in os.listdir("/dev/vfio") if d.isdigit())
    for _ in range(50):
        try:
            for g in vfio:
                os.close(os.open(g, os.O_RDWR))
            break
        except OSError as e:
            if e.errno != errno.EBUSY:
                raise
            time.sleep(0.2)
    else:
        raise RuntimeError("VFIO EBUSY after 10s")
    import jax
    import jax.numpy as jnp

    devs = jax.local_devices()
    n, kind, host = len(devs), devs[0].device_kind, socket.gethostname()
    out = float(
        jax.device_get(
            jax.pmap(lambda v: jax.lax.psum(v * 2.0, "i"), "i")(
                jnp.arange(1, n + 1, dtype=jnp.float32)
            )[0]
        )
    )
    assert out == float(n * (n + 1))
    return {"host": host, "kind": kind, "cores": n, "psum": out}


def train_loop_per_worker(_: dict) -> None:
    import jax
    from jax import shard_map
    import jax.numpy as jnp
    from jax.sharding import Mesh, NamedSharding, PartitionSpec as P

    resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
    ctx, hub = rt.get_context(), ray.get_actor("hub")
    rk, wd = ctx.get_world_rank(), ctx.get_world_size()

    def _log(k: str, v=None, m: str = ""):
        if rk == 0:
            ray.get(hub.put.remote(k, v, m))

    w = np.random.default_rng(42).standard_normal((1024, 1024), np.float32) * 0.02
    st0, ckpt = 0, rt.get_checkpoint()
    if ckpt:
        with ckpt.as_directory() as d, open(f"{d}/s.pkl", "rb") as f:
            st0, w = pickle.load(f)
        _log(
            "restored",
            st0,
            f"[Worker 0] Restored step {st0} (norm={np.linalg.norm(w):.4f})",
        )
    nd, nl = jax.device_count(), jax.local_device_count()
    _log(
        "jax_init",
        (nd, ray.get_runtime_context().get_node_id()),
        f"[Worker 0] JAX ready on {nd} TPU cores (world={wd})",
    )
    mesh = Mesh(np.array(jax.devices()), ("d",))
    d_sh, rep = NamedSharding(mesh, P("d", None)), NamedSharding(mesh, P())
    rw = jax.device_put(w, rep)

    @jax.jit(in_shardings=(rep, d_sh, d_sh), out_shardings=(rep, rep))
    def step_fn(p, x, y):
        def per_shard(pw, xl, yl):
            loss, g = jax.value_and_grad(
                lambda m: jnp.mean((jnp.tanh(xl @ m) - yl) ** 2)
            )(pw)
            return pw - 0.05 * jax.lax.pmean(g, "d"), jax.lax.pmean(loss, "d")

        return shard_map(
            per_shard,
            mesh=mesh,
            in_specs=(P(), P("d", None), P("d", None)),
            out_specs=(P(), P()),
            check_vma=False,
        )(p, x, y)

    for s in range(st0 + 1, 4):
        xl = np.random.default_rng(99 + s * 10 + rk).standard_normal(
            (nl * 16, 1024), np.float32
        )
        xg = jax.make_array_from_process_local_data(d_sh, xl, (nd * 16, 1024))
        yg = jax.make_array_from_process_local_data(
            d_sh, np.roll(xl, 1, -1) * 0.5, (nd * 16, 1024)
        )
        rw, la = step_fn(rw, xg, yg)
        loss = round(float(jax.device_get(la)), 6)
        _log("active", s)
        time.sleep(4.5 if s == 2 and st0 == 0 else 0.2)
        hw, out_c = np.asarray(jax.device_get(rw)), None
        if rk == 0:
            os.makedirs("/tmp/ck", exist_ok=True)
            with open("/tmp/ck/s.pkl", "wb") as f:
                pickle.dump((s, hw), f)
            out_c = rt.Checkpoint.from_directory("/tmp/ck")
        m = {"step": s, "loss": loss, "devices": nd, "restored_step": st0}
        rt.report(m, checkpoint=out_c)
        _log("step", m, f"[Worker 0] Step {s} reported on {nd} cores (loss={loss:.6f})")


@ray.remote(num_cpus=0)
def _fit(nw: tuple[int, int], res: dict, path: str, name: str) -> dict:
    fs = (
        None
        if path.startswith(("gs://", "s3://"))
        else pyarrow.fs.PyFileSystem(pyarrow.fs.FSSpecHandler(_MemFS()))
    )
    kw = {"use_tpu": True, "topology": TOPO, "accelerator_type": ACCEL}
    sc = rt.ScalingConfig(
        num_workers=nw,
        resources_per_worker=res,
        elastic_resize_monitor_interval_s=2.0,
        **kw,
    )
    rc = rt.RunConfig(
        name=name,
        storage_path=path,
        storage_filesystem=fs,
        callbacks=[AuditCallback()],
        failure_config=rt.FailureConfig(max_failures=3),
    )
    return dict(
        JaxTrainer(train_loop_per_worker, scaling_config=sc, run_config=rc)
        .fit()
        .metrics
    )


def _wait(hub, pred=None, fref=None):
    for _ in range(480):
        if fref and ray.wait([fref], timeout=0)[0]:
            ray.get(fref)
        ev, logs = ray.get(hub.snap.remote())
        for m in logs:
            print(m, flush=True)
        if pred is None or (v := pred(ev)):
            return ev if pred is None else (v, ev)
        time.sleep(0.25)
    raise TimeoutError("Timed out polling state")


def _rejoin(ip: str, port: int) -> None:
    with socket.create_connection((ip, port), timeout=30.0) as s:
        s.sendall(b"rejoin")
        assert s.recv(8) == b"OK"


@contextlib.contextmanager
def _scenario(title: str, min_s: int, port: int, path: str):
    print(f"\n{'=' * 72}\n{title}\n{'=' * 72}", flush=True)
    hub, hid = ray.get_actor("hub"), ray.get_runtime_context().get_node_id()
    ray.get(hub.reset.remote())
    wps, res = get_tpu_worker_resources(topology=TOPO, accelerator_type=ACCEL)
    tpu = float(res["TPU"])
    _wait(hub, lambda _: ray.available_resources().get("TPU", 0.0) >= 2 * tpu)
    ns = [n for n in ray.nodes() if n.get("Alive") and n["Resources"].get("TPU", 0) > 0]
    nodes = sorted(ns, key=lambda n: n["NodeManagerHostname"])
    fref = _fit.options(scheduling_strategy=Pin(hid, soft=False)).remote(
        (min_s * wps, 2 * wps), res, path, f"r{port}"
    )
    _wait(hub, lambda e: [v for k, _, v in e if k == "ckpt"], fref)
    _, ev = _wait(hub, lambda e: [v for k, _, v in e if k == "active" and v == 2], fref)
    r0 = next((v[1] for k, _, v in reversed(ev) if k == "jax_init"), None)
    v = next((n for n in nodes if n["NodeID"] != r0), nodes[-1])
    vip = v["NodeManagerAddress"]
    print(
        f"[Driver] Stopping slice 2 ({v['NodeManagerHostname']}, ip={vip}) in step 2...",
        flush=True,
    )
    t0, box = time.time(), [False]
    ray.get(
        _stop_slice.options(scheduling_strategy=Pin(v["NodeID"], soft=False)).remote(
            port, int(tpu)
        )
    )
    try:
        yield hub, fref, vip, tpu, wps, t0, box
    except Exception:
        ray.cancel(fref, force=True)
        raise
    finally:
        if not box[0]:
            _rejoin(vip, port)


def _test1(path: str) -> None:
    def pgs():
        return [
            (p["name"], p["state"])
            for p in ray.util.placement_group_table().values()
            if p["state"] != "REMOVED"
        ]

    with _scenario(
        "TEST 1: < min_workers Teardown, VFIO Probe & Rejoin", 2, 19871, path
    ) as (h, fref, vip, tpu, _, _, box):
        _wait(
            h,
            lambda e: "RestartingState" in [v for k, _, v in e if k == "state"]
            and ray.cluster_resources().get("TPU", 0.0) <= tpu,
            fref,
        )
        for _ in range(32):
            if ray.available_resources().get("TPU", 0.0) >= tpu and not pgs():
                break
            time.sleep(0.25)
        ev, lp = _wait(h), pgs()
        av, cl = ray.available_resources().get("TPU", 0.0), ray.cluster_resources().get(
            "TPU", 0.0
        )
        st = [v for k, _, v in ev if k == "state"][-1]
        print(
            f"[Test 1a Check] state={st} cluster_TPU={cl} available_TPU={av} non_removed_PGs={len(lp)}",
            flush=True,
        )
        assert st == "RestartingState" and not lp and av >= tpu, f"{st} {av} {lp}"
        vfio = ray.get(
            verify_surviving_slice_vfio.options(
                num_cpus=1, resources={"TPU": tpu}
            ).remote(),
            timeout=60.0,
        )
        print(f"[Test 1b VFIO] Surviving slice probe passed: {vfio}", flush=True)
        _wait(h, lambda _: ray.available_resources().get("TPU", 0.0) >= tpu)
        print(f"[Test 1c Rejoin] Rejoining slice 2 (ip={vip})...", flush=True)
        _rejoin(vip, 19871)
        box[0] = True
        m = ray.get(fref, timeout=150.0)
        _wait(h)
        assert m["step"] == 3 and m["devices"] == 16 and m["restored_step"] >= 1, m
        print(
            f"[Test 1 PASS] Resumed step {m['restored_step']}, finished on 16 TPU cores: {m}",
            flush=True,
        )


def _test2(path: str) -> None:
    with _scenario("TEST 2: 2 -> 1 Multi-Slice Elastic Scale-Down", 1, 19872, path) as (
        h,
        fref,
        _,
        _,
        wps,
        t0,
        _,
    ):
        hit, _ = _wait(
            h,
            lambda e: [t for k, t, v in e if k == "jax_init" and t > t0 and v[0] == 8],
            fref,
        )
        rec, m, ev = hit[0] - t0, ray.get(fref, timeout=90.0), _wait(h)
        sd = next(t for k, t, _ in ev if k == "wg_shutdown" and t > t0) - t0
        rs = next(t for k, t, v in ev if k == "resize" and t > t0 and v == wps) - t0
        to, ok = sum(1 for k, _, _ in ev if k == "timeout"), sd < rs
        print(
            f"[Test 2 Scale-Down] recovery_s={rec:.2f}s startup_timeouts={to} wg_shutdown_before_resize={ok} (+{sd:.2f}s vs +{rs:.2f}s)",
            flush=True,
        )
        assert (
            ok
            and to == 0
            and rec < 25.0
            and m["step"] == 3
            and m["devices"] == 8
            and m["restored_step"] >= 1
        )
        print(
            f"[Test 2 PASS] Recovered 2 -> 1 slice in {rec:.2f}s, restored step {m['restored_step']}, finished on 8 TPU cores: {m}",
            flush=True,
        )


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--storage-path", default="ray-tpu-elastic-verify")
    ap.add_argument("--only", choices=["all", "test1", "test2"], default="all")
    args = ap.parse_args()
    ray.init(address="auto", log_to_driver=False)
    hub = _Hub.options(
        name="hub",
        scheduling_strategy=Pin(ray.get_runtime_context().get_node_id(), soft=False),
    ).remote()
    try:
        if args.only in ("all", "test1"):
            _test1(args.storage_path)
        if args.only in ("all", "test2"):
            _test2(args.storage_path)
    finally:
        ray.kill(hub)
        ray.shutdown()


if __name__ == "__main__":
    main()
HEAD_POD=$(kubectl get pods -l ray.io/node-type=head,ray.io/cluster=ray-tpu-elastic-verify -o jsonpath='{.items[0].metadata.name}')
kubectl cp run_tpu_elastic_recovery_manual_test.py "$HEAD_POD:/tmp/run_tpu_elastic_recovery_manual_test.py"
kubectl exec "$HEAD_POD" -- python3 -u /tmp/run_tpu_elastic_recovery_manual_test.py

Step 4: Results

1. This PR (controller.py patched)

2026-10-31 01:57:23,595	INFO worker.py:1693 -- Using address 127.0.0.1:6379 set in the environment variable RAY_ADDRESS
2026-10-31 01:57:23,598	INFO worker.py:1844 -- Connecting to existing Ray cluster at address: 10.228.3.109:6379...
2026-10-31 01:57:23,622	INFO worker.py:2035 -- Connected to Ray cluster. View the dashboard at http://10.228.3.109:8265 

========================================================================
TEST 1: < min_workers Teardown, VFIO Probe & Rejoin
========================================================================
[Controller] InitializingState -> SchedulingState
[Controller] ResizeDecision(num_workers=2)
[Controller] SchedulingState -> RunningState
[Worker 0] JAX ready on 16 TPU cores (world=2)
[Worker 0] Step 1 reported on 16 cores (loss=0.492408)
[Controller] Committed checkpoint (step=1)
[Driver] Stopping slice 2 (ray-tpu-elastic-verify-tpu-group-worker-ts2nq, ip=10.228.9.7) in step 2...
[Controller] RunningState -> RestartingState
[Controller] WorkerGroup.shutdown(size=2)
[Test 1a Check] state=RestartingState cluster_TPU=4.0 available_TPU=4.0 non_removed_PGs=0
[Test 1b VFIO] Surviving slice probe passed: {'host': 'ray-tpu-elastic-verify-tpu-group-worker-rjxt2', 'kind': 'TPU7x', 'cores': 8, 'psum': 72.0}
[Test 1c Rejoin] Rejoining slice 2 (ip=10.228.9.7)...
[Controller] RestartingState -> SchedulingState
[Controller] ResizeDecision(num_workers=2)
[Controller] SchedulingState -> RunningState
[Worker 0] Restored step 1 (norm=20.4607)
[Worker 0] JAX ready on 16 TPU cores (world=2)
[Worker 0] Step 2 reported on 16 cores (loss=0.493049)
[Worker 0] Step 3 reported on 16 cores (loss=0.491811)
[Controller] Committed checkpoint (step=2)
[Controller] Committed checkpoint (step=3)
[Controller] RunningState -> ShuttingDownState
[Controller] WorkerGroup.shutdown(size=2)
[Controller] ShuttingDownState -> FinishedState
[Test 1 PASS] Resumed step 1, finished on 16 TPU cores: {'step': 3, 'loss': 0.491811, 'devices': 16, 'restored_step': 1}

========================================================================
TEST 2: 2 -> 1 Multi-Slice Elastic Scale-Down
========================================================================
[Controller] InitializingState -> SchedulingState
[Controller] ResizeDecision(num_workers=2)
[Controller] SchedulingState -> RunningState
[Worker 0] JAX ready on 16 TPU cores (world=2)
[Worker 0] Step 1 reported on 16 cores (loss=0.492408)
[Controller] Committed checkpoint (step=1)
[Driver] Stopping slice 2 (ray-tpu-elastic-verify-tpu-group-worker-ts2nq, ip=10.228.9.7) in step 2...
[Controller] RunningState -> RestartingState
[Controller] WorkerGroup.shutdown(size=2)
[Controller] RestartingState -> SchedulingState
[Controller] ResizeDecision(num_workers=1)
[Controller] SchedulingState -> RunningState
[Worker 0] Restored step 1 (norm=20.4607)
[Controller] RunningState -> RestartingState
[Controller] WorkerGroup.shutdown(size=1)
[Controller] RestartingState -> SchedulingState
[Controller] ResizeDecision(num_workers=1)
[Controller] SchedulingState -> RunningState
[Worker 0] Restored step 1 (norm=20.4607)
[Worker 0] JAX ready on 8 TPU cores (world=1)
[Worker 0] Step 2 reported on 8 cores (loss=0.494078)
[Controller] Committed checkpoint (step=2)
[Worker 0] Step 3 reported on 8 cores (loss=0.489143)
[Controller] Committed checkpoint (step=3)
[Controller] RunningState -> ShuttingDownState
[Controller] WorkerGroup.shutdown(size=1)
[Controller] ShuttingDownState -> FinishedState
[Test 2 Scale-Down] recovery_s=19.26s startup_timeouts=0 wg_shutdown_before_resize=True (+1.88s vs +6.90s)
[Test 2 PASS] Recovered 2 -> 1 slice in 19.26s, restored step 1, finished on 8 TPU cores: {'step': 3, 'loss': 0.489143, 'devices': 8, 'restored_step': 1}

In Test 2, the first replacement worker group fails and restarts once more, with and without this PR. The new worker can try to open the TPU before the kernel has released it from the killed worker (/dev/vfio returns EBUSY). That race exists on master and is outside the scope of this PR.

2. Master (before this PR)

Master keeps the failed worker group while it waits below min_workers, so Test 1 fails its first check (--only test1):

2026-10-31 02:01:09,759	INFO worker.py:1693 -- Using address 127.0.0.1:6379 set in the environment variable RAY_ADDRESS
2026-10-31 02:01:09,761	INFO worker.py:1844 -- Connecting to existing Ray cluster at address: 10.228.3.109:6379...
2026-10-31 02:01:09,793	INFO worker.py:2035 -- Connected to Ray cluster. View the dashboard at http://10.228.3.109:8265 

========================================================================
TEST 1: < min_workers Teardown, VFIO Probe & Rejoin
========================================================================
[Controller] InitializingState -> SchedulingState
[Controller] ResizeDecision(num_workers=2)
[Controller] SchedulingState -> RunningState
[Worker 0] JAX ready on 16 TPU cores (world=2)
[Worker 0] Step 1 reported on 16 cores (loss=0.492408)
[Controller] Committed checkpoint (step=1)
[Driver] Stopping slice 2 (ray-tpu-elastic-verify-tpu-group-worker-ts2nq, ip=10.228.9.7) in step 2...
[Controller] RunningState -> RestartingState
[Test 1a Check] state=RestartingState cluster_TPU=4.0 available_TPU=0.0 non_removed_PGs=1
Traceback (most recent call last):
  File "/tmp/run_tpu_elastic_recovery_manual_test.py", line 441, in <module>
    main()
    ~~~~^^
  File "/tmp/run_tpu_elastic_recovery_manual_test.py", line 432, in main
    _test1(args.storage_path)
    ~~~~~~^^^^^^^^^^^^^^^^^^^
  File "/tmp/run_tpu_elastic_recovery_manual_test.py", line 362, in _test1
    assert st == "RestartingState" and not lp and av >= tpu, f"{st} {av} {lp}"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: RestartingState 0.0 [('', 'RESCHEDULING')]
command terminated with exit code 1

Test 2 still recovers onto one slice, but master makes the resize decision before it shuts down the failed worker group (--only test2):

2026-10-31 02:03:09,505	INFO worker.py:1693 -- Using address 127.0.0.1:6379 set in the environment variable RAY_ADDRESS
2026-10-31 02:03:09,507	INFO worker.py:1844 -- Connecting to existing Ray cluster at address: 10.228.3.109:6379...
2026-10-31 02:03:09,529	INFO worker.py:2035 -- Connected to Ray cluster. View the dashboard at http://10.228.3.109:8265 

========================================================================
TEST 2: 2 -> 1 Multi-Slice Elastic Scale-Down
========================================================================
[Controller] InitializingState -> SchedulingState
[Controller] ResizeDecision(num_workers=2)
[Controller] SchedulingState -> RunningState
[Worker 0] JAX ready on 16 TPU cores (world=2)
[Worker 0] Step 1 reported on 16 cores (loss=0.492408)
[Controller] Committed checkpoint (step=1)
[Driver] Stopping slice 2 (ray-tpu-elastic-verify-tpu-group-worker-ts2nq, ip=10.228.9.7) in step 2...
[Controller] RunningState -> RestartingState
[Controller] RestartingState -> SchedulingState
[Controller] ResizeDecision(num_workers=1)
[Controller] WorkerGroup.shutdown(size=2)
[Controller] SchedulingState -> RunningState
[Worker 0] Restored step 1 (norm=20.4607)
[Controller] RunningState -> RestartingState
[Controller] RestartingState -> SchedulingState
[Controller] ResizeDecision(num_workers=1)
[Controller] WorkerGroup.shutdown(size=1)
[Controller] SchedulingState -> RunningState
[Worker 0] Restored step 1 (norm=20.4607)
[Worker 0] JAX ready on 8 TPU cores (world=1)
[Worker 0] Step 2 reported on 8 cores (loss=0.494078)
[Controller] Committed checkpoint (step=2)
[Worker 0] Step 3 reported on 8 cores (loss=0.489143)
[Controller] Committed checkpoint (step=3)
[Controller] RunningState -> ShuttingDownState
[Controller] WorkerGroup.shutdown(size=1)
[Controller] ShuttingDownState -> FinishedState
[Test 2 Scale-Down] recovery_s=21.46s startup_timeouts=0 wg_shutdown_before_resize=False (+1.95s vs +1.95s)
Traceback (most recent call last):
  File "/tmp/run_tpu_elastic_recovery_manual_test.py", line 441, in <module>
    main()
    ~~~~^^
  File "/tmp/run_tpu_elastic_recovery_manual_test.py", line 434, in main
    _test2(args.storage_path)
    ~~~~~~^^^^^^^^^^^^^^^^^^^
  File "/tmp/run_tpu_elastic_recovery_manual_test.py", line 407, in _test2
    ok
    ...<4 lines>...
    and m["restored_step"] >= 1
AssertionError
command terminated with exit code 1

@ryanaoleary
ryanaoleary marked this pull request as ready for review October 31, 2026 04:31
@ryanaoleary
ryanaoleary requested a review from a team as a code owner October 31, 2026 04:31
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 93491ad. Configure here.

@ray-gardener ray-gardener Bot added train Ray Train Related Issue community-contribution Contributed by the community labels Oct 31, 2026

@Jadiouo Jadiouo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified 93491ad against base d6974fe on CPU through the public API: a local Cluster with a 0-CPU head and two 1-CPU nodes, DataParallelTrainer with num_workers=(2, 2) and elastic_resize_monitor_interval_s=2.0. I removed one node mid-training and checked resources 40 s later.

  • PR: on entering RestartingState the old worker group is shut down right away. 40 s later available CPU is 1.0, no placement group is left, and a standalone 1-CPU task runs within 8 s. Training restarts once the node rejoins.
  • Base: in 1 of 4 runs, the failure was detected about 22 s after the node removal. The scaling decision was a no-op and the old group was not shut down. 40 s later available CPU was 0.0, the placement group was RESCHEDULING, and the 1-CPU task couldn't run. In the other 3 runs the failure was detected within 1 s, before the node was marked dead, so base resized right away and shut the old group down as a side effect. The leak therefore shows up when the node is already gone at decision time, as in your GKE preemption test, and this PR handles both orderings.

The new test fails on base and passes here; test_resize_and_fail_with_replica_groups passes on both.

@ryanaoleary ryanaoleary added the go add ONLY when ready to merge, run all tests label Nov 5, 2026
ryanaoleary added a commit that referenced this pull request Nov 9, 2026
)

## Why are these changes needed?

When `ray.kill` terminates a TPU worker during fault recovery or elastic
resizing, the Raylet releases the placement group's TPU bundle as soon
as the worker IPC socket closes. Meanwhile, the Linux kernel is still
releasing the dying process's VFIO devices and unpinning IOMMU DMA
pages, which takes 2.1–2.4 s on an 8-core TPU v7x worker with 256 GiB of
allocated HBM. Because `libtpu` and `TorchTPU` open `/dev/vfio/<group>`
once without retry, a replacement worker scheduled onto the same host
during that window fails with `EBUSY`:

- In `JaxTrainer`, the replacement worker fails on its first
`jax.devices()` call, consuming one `FailureConfig(max_failures)` retry
and 7.3–9.7 s to restart the worker group.
- In `TorchTrainer` with `backend="tpu_dist"`,
`dist.init_process_group("tpu_dist")` runs inside
`after_worker_group_start`, where a `RuntimeError` raises a
non-retryable `ControllerError` that aborts the job regardless of
`max_failures`.

Because Linux VFIO `O_RDWR` opens are mutually exclusive, a worker must
only probe its own assigned groups so it does not contend with healthy
peer workers on the same host. This PR adds `wait_for_tpu_vfio_ready` in
`ray._private.accelerators.tpu` and calls it before TPU distributed
initialization in `JaxTrainer` and `TorchTrainer`:

- `get_current_process_tpu_vfio_devices` filters
`/sys/kernel/iommu_groups/<group>/devices/*/vendor` for Google TPU PCI
devices with vendor ID `0x1ae0`, sorts them by PCI
`domain:bus:device.function`, and groups dual-VF functions `.0` and `.1`
by physical chip.
- Whole-chip workers resolve their assigned VFIO groups from
`TPU_VISIBLE_CHIPS`, or all chips on the host when unset. Per-device
`TorchTrainer` workers using `tpu_dist` pass their single assigned
device index from `TPU_VISIBLE_DEVICES` or `LOCAL_RANK`.
- `wait_for_tpu_vfio_ready` probes only the current process's target
`/dev/vfio/<group>` paths with `os.open` and `os.close`, polling every
50 ms while `os.open` returns `EBUSY` up to a 10 s timeout. On hosts
without TPU VFIO groups, it returns immediately.

## Related issue number

Contributes to [[Train] JaxTrainer Implementation Tracking Issue
(ray#55162)](#55162) and
[[Core][Train] Support Torch runtime with TPUs
(ray#64055)](#64055).
Complements [[Train] Shut down failed worker group before sizing
replacement (ray#67651)](#67651).

## Checks

- [x] I've signed off every commit(by using the -s flag, i.e., `git
commit -s`) in this PR.
- [x] I've run `scripts/format.sh` to lint the changes in this PR.
- [ ] I've included any doc changes needed for
https://docs.ray.io/en/master/.
- [ ] I've added any new APIs to the API reference. For example, if I
added a method in Python, I've added it to `doc/source/tune/api/` under
the corresponding `.rst` file.
- [x] I've made sure the tests are passing. Note that there might be a
few flaky tests, see the recent failures at https://flakey-tests.ray.io/
- Testing Strategy
- [x] Unit tests (`test_tpu.py`: 121 passed,
`test_torch_device_manager.py`: 8 passed, `test_jax_trainer.py`: 3
passed) and manual verification on GKE TPU v7x (see comment below)
   - [ ] Release tests
   - [ ] This PR is not tested :(

---------

Signed-off-by: Ryan O'Leary <[email protected]>
@ryanaoleary

Copy link
Copy Markdown
Contributor Author

@liulehui @pseudo-rnd-thoughts this PR is ready for review if you get a chance.

During elastic recovery, failed worker groups stayed alive holding nodes and /dev/vfio devices while waiting for capacity, and collective on_shutdown could hang teardown on failed or unfinished groups. This shuts down the failed worker group before sizing the replacement and skips collective on_shutdown unless training finished cleanly.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community go add ONLY when ready to merge, run all tests train Ray Train Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants