Skip to content

[Train] Wait for worker TPU VFIO devices before distributed init - #67756

Merged
ryanaoleary merged 3 commits into
ray-project:masterfrom
ryanaoleary:tpu-vfio-readiness
Nov 9, 2026
Merged

ryanaoleary merged 3 commits into
ray-project:masterfrom
ryanaoleary:tpu-vfio-readiness

Conversation

@ryanaoleary

@ryanaoleary ryanaoleary commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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) and [Core][Train] Support Torch runtime with TPUs (ray#64055).
Complements [Train] Shut down failed worker group before sizing replacement (ray#67651).

Checks

@ryanaoleary

ryanaoleary commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Benchmarking & Speedup Results (GKE TPU v7x)

Verified on GKE tpu7x (2x2x1, 4 dual-chiplet chips / 8 VFIO groups, Linux 6.12.105+, libtpu 0.0.50, jax 0.11.2, torch 2.14.0 + torch_tpu).

1. Live tpu7x Fault Recovery & Rapid Reuse (run_vfio_ab_e2e.py)

The following table compares master (45c4123857) against this PR across four tpu7x scenarios (hardware runs executed against initial commit 82f029a68f; the follow-up commit logs only initially busy groups and starts the timer before the first probe round, without changing when the wait returns):

Scenario (tpu7x 2x2x1, 8 VFs) master (45c4123857) With This PR
Kernel SIGKILL → VFIO release probe (256 GiB HBM, 1 run) /dev/vfio/{4,2,3,6} released 2.074 s, 2.160 s, 2.244 s, and 2.393 s after SIGKILL (27 EBUSY probes before each group's release took group_lock) Absorbed by wait_for_tpu_vfio_ready in the workloads below
@ray.remote 8-core rapid reuse (actor calls wait_for_tpu_vfio_ready directly) Crashed after 1.489 s: open(/dev/vfio/4): 16: Device or resource busy Waited 1.80 s (wait_s=1.848 s), initialized 8 cores, psum = 36.0, 0 EBUSY
JaxTrainer 8-core rapid reuse + mid-step-2 ray.kill First init failed with EBUSY on /dev/vfio/2 as a retryable WorkerGroupError (ErroredState with max_failures=0) Waited 3.33 s on initial startup against the harness holder (includes part of the harness's 1.2 s pre-kill delay), survived mid-step-2 ray.kill, restored step 1, and finished step 3 (0 EBUSY)
TorchTrainer (tpu_dist) 8 per-VF workers + mid-step-2 ray.kill(torch_worker_3) _setup_torch_process_group failed in after_worker_group_start on /dev/vfio/3, raising a non-retryable ControllerError(RayTaskError) regardless of max_failures The 4 workers on held .0 VFs waited 4.29–4.55 s on initial startup against the harness holder (includes part of the harness's 4.8 s pre-kill delay); the 4 .1 VFs did not wait; survived mid-step-2 ray.kill and finished step 3 (world_size=8, 0 EBUSY; harness bound via LOCAL_RANK, while single-index TPU_VISIBLE_DEVICES is covered by unit tests)
Sub-host 2-chip (TPU_VISIBLE_CHIPS=0,1 vs. 2,3) & intra-chip dual-VF isolation Not applicable Worker B survived 3 rapid SIGKILL restarts (wait_s = 0.126 s, 0.169 s, 0.149 s) while Peer Worker A completed 240 continuous pmap steps without an exception; single free sibling-VF probe took 0.1 ms

2. Multi-Slice JaxTrainer Elastic Recovery Speedup

Across two unpatched multi-slice JaxTrainer runs on tpu7x (668M-parameter 8-layer Transformer, 1.34 GB and 1.86 GB GCS checkpoints), each EBUSY collision consumed one FailureConfig(max_failures) retry and 7.32–9.67 s of gross wall-clock time (including 2.98–4.28 s blocked in libtpu tpu_hal.cc:268 Hardware Abstraction Layer (HAL) teardown):

  • 2 → 1 slice crash recovery (1.34 GB checkpoint): 9.41 s (3.91 s HAL teardown stall)
  • 2 → 4 slice clean elastic scale-up (1.86 GB checkpoint): 8.49 s (3.70 s HAL teardown stall)
  • 4 → 2 slice crash recovery (1.86 GB checkpoint): 9.67 s (4.28 s HAL teardown stall)
  • 2 → 1 slice crash recovery (1.86 GB checkpoint): 7.32 s (2.98 s HAL teardown stall)

The following table compares 2 → 1 slice post-shutdown recovery between the unpatched runs and three trials using the worker-entry VFIO polling prototype (ensure_vfio_ready):

2 → 1 Slice Recovery Metric (tpu7x 2x2x1) Unpatched (n=1 baseline, n=1 ray#67651 only) With VFIO Readiness Polling (n=3: min–max, mean ± std) Net Delta vs. Baseline
Failure detection (T_failure_injected → T_failure_detected) 1.77 s (baseline), 0.94 s (ray#67651) 1.77–1.79 s (1.78 ± 0.01 s) +0.01 s
Old 2-slice worker-group shutdown (T_wg_shutdown_begin → T_wg_shutdown_end) 5.01 s (baseline), 5.01 s (ray#67651) 5.01–5.01 s (5.01 ± 0.00 s) 0.00 s
Post-shutdown device readiness (T_wg_shutdown_end → worker_jax_devices_ready) 14.49 s (baseline), 12.03 s (ray#67651) 8.57–8.64 s (8.60 ± 0.04 s) -5.88 s (-40.6%; -3.43 s vs. ray#67651)
Total control-plane recovery (T_failure_injected → worker_jax_devices_ready) 21.28 s (baseline), 17.98 s (ray#67651) 15.36–15.44 s (15.40 ± 0.04 s) -5.88 s (-27.6%; -2.58 s vs. ray#67651)
Wasted FailureConfig(max_failures) retries 1 (Error count: 2) 0 (Error count: 1 in all 3 trials) -1 retry

3. Clean-Startup Latency & FS Operation Profile (When /dev/vfio Devices Are Free)

When all assigned VFIO groups are free (0 time.sleep calls), wait_for_tpu_vfio_ready executes 10 os.listdir calls (1 on /dev/vfio + 9 on /sys/kernel/iommu_groups/<id>/devices), 9 sysfs vendor reads, and N os.open(..., os.O_RDWR) + N os.close calls across N assigned VFs (19 + 2N Python FS operations):

Mode Python FS Operations Local /dev/shm (1,000 runs: p50 / mean ± std) Live tpu7x Kernel devtmpfs/sysfs
Hosts without /dev/vfio (e.g., TPU v4 /dev/accel*) 1 6.9 µs (7.4 ± 4.6 µs) Not applicable
Per-VF worker (visible_devices="5", 1 VF) 21 732.2 µs (747.2 ± 47.2 µs) 100 µs (0.0001 s)
Sub-host worker (TPU_VISIBLE_CHIPS="2,3", 4 VFs) 27 845.1 µs (874.1 ± 87.4 µs) 0.0 s (at 1 ms rounding)
Full-host worker (8 VFs free) 35 964.5 µs (983.7 ± 80.9 µs) Not measured separately

Manual Testing Steps

Step 1: Deploy a TPU v7x RayCluster

apiVersion: ray.io/v1
kind: RayCluster
metadata:
  name: ray-tpu-vfio-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-vfio-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: Run Baseline Verification (master)

Save run_vfio_ab_e2e.py below, copy it to the head pod, and run --mode baseline on unpatched master:

HEAD_POD=$(kubectl get pods -l ray.io/cluster=ray-tpu-vfio-verify,ray.io/node-type=head -o jsonpath='{.items[0].metadata.name}')
kubectl cp run_vfio_ab_e2e.py "$HEAD_POD:/tmp/run_vfio_ab_e2e.py"
kubectl exec "$HEAD_POD" -- python3 -u /tmp/run_vfio_ab_e2e.py --mode baseline
run_vfio_ab_e2e.py (full A/B verification script)
"""Live tpu7x A/B E2E verification for TPU VFIO readiness across Ray Core, JaxTrainer, Sub-Host Isolation, and TorchTrainer (tpu_dist)."""

import argparse
import errno
import glob
import io
import os
import pickle
import re
import resource
import signal
import subprocess
import sys
import threading
import time
import traceback

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.execution import callback as cb
from ray.train.v2.jax import JaxTrainer
from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy as Pin


def _strip_ansi(text: str) -> str:
    return re.sub(r"\x1b\[[0-9;]*m", "", text)


def _summarize_exc(exc: Exception) -> str:
    clean = _strip_ansi(str(exc)).strip()
    for ln in reversed(clean.splitlines()):
        if "RuntimeError:" in ln or "Device or resource busy" in ln or "RayActorError" in ln:
            return ln.strip()
    return clean.splitlines()[-1] if clean else str(exc)


def _alloc_tpu_64gib(jax, jnp, devs, gib_per_core: int = 8):
    sharding = jax.sharding.NamedSharding(
        jax.sharding.Mesh(np.array(devs), ("i",)), jax.sharding.PartitionSpec("i")
    )
    dim0 = gib_per_core * 256
    buf = jax.jit(
        lambda: jnp.ones((len(devs), dim0, 1024, 1024), dtype=jnp.float32),
        out_shardings=sharding,
    )()
    buf.block_until_ready()
    return buf


@ray.remote(num_cpus=0)
class _PriorTpuHolder:
    """Holds a live JAX TPU process (64 GiB across 8 cores) and SIGKILLs it right as incoming RayTrainWorkers finish importing jaxlib/torch_tpu."""

    def __init__(self):
        self.proc = None

    def start_and_arm_sigkill_on_train_import(
        self,
        target_so_substr: str,
        min_matches: int = 1,
        sigterm_grace_s: float = 0.0,
    ) -> list[str]:
        code = (
            "import os, resource, time\n"
            "resource.setrlimit(resource.RLIMIT_CORE, (0, 0))\n"
            "import jax, jax.numpy as jnp, numpy as np\n"
            "devs = jax.local_devices()\n"
            "sh = jax.sharding.NamedSharding(jax.sharding.Mesh(np.array(devs), ('i',)), jax.sharding.PartitionSpec('i'))\n"
            "b = jax.jit(lambda: jnp.ones((len(devs), 8192, 1024, 1024), dtype=jnp.float32), out_shardings=sh)()\n"
            "b.block_until_ready()\n"
            "for fd in list(os.listdir('/proc/self/fd')):\n"
            "    try:\n"
            "        if os.readlink(f'/proc/self/fd/{fd}') == '/tmp/libtpu_lockfile':\n"
            "            os.close(int(fd))\n"
            "    except OSError:\n"
            "        pass\n"
            "vfio = sorted(\n"
            "    os.readlink(f'/proc/self/fd/{fd}')\n"
            "    for fd in os.listdir('/proc/self/fd')\n"
            "    if os.path.exists(f'/proc/self/fd/{fd}')\n"
            "    and os.readlink(f'/proc/self/fd/{fd}').startswith('/dev/vfio/')\n"
            "    and os.readlink(f'/proc/self/fd/{fd}') != '/dev/vfio/vfio'\n"
            ")\n"
            "print('READY', ','.join(vfio), flush=True)\n"
            "time.sleep(120)\n"
        )
        p = subprocess.Popen(
            [sys.executable, "-c", code],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
        )
        self.proc = p
        line = p.stdout.readline().strip()
        assert line.startswith("READY "), (
            f"Unexpected holder output: {line!r} stderr={p.stderr.read()[-400:]!r}"
        )

        if target_so_substr == "NONE_MANUAL":
            return line.split(" ", 1)[1].split(",")

        def _pids_with_lib() -> set[int]:
            found = set()
            for entry in os.listdir("/proc"):
                if not entry.isdigit():
                    continue
                pid = int(entry)
                try:
                    with open(f"/proc/{pid}/maps", errors="ignore") as f:
                        if target_so_substr in f.read():
                            found.add(pid)
                except OSError:
                    continue
            return found

        existing_loaded_pids = _pids_with_lib() | {p.pid}

        def _watch_and_sigkill():
            deadline = time.monotonic() + 45.0
            while time.monotonic() < deadline and p.poll() is None:
                newly_loaded = _pids_with_lib() - existing_loaded_pids
                if len(newly_loaded) >= min_matches:
                    if sigterm_grace_s > 0:
                        time.sleep(sigterm_grace_s)
                    if p.poll() is None:
                        os.kill(p.pid, signal.SIGKILL)
                    p.wait()
                    return
                time.sleep(0.01)
            if p.poll() is None:
                os.kill(p.pid, signal.SIGKILL)
                p.wait()

        threading.Thread(target=_watch_and_sigkill, daemon=True).start()
        return line.split(" ", 1)[1].split(",")

    def sigkill_async(self) -> None:
        p = self.proc
        self.proc = None
        if p is not None and p.poll() is None:
            os.kill(p.pid, signal.SIGKILL)
            threading.Thread(target=p.wait, daemon=True).start()


@ray.remote(num_cpus=0)
class _Hub:
    def __init__(self):
        self.reset()

    def reset(self):
        MemoryFileSystem.store.clear()
        self.fs = MemoryFileSystem()
        self.logs = []
        self.victim = None
        self.errors = []

    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 log(self, msg: str):
        self.logs.append(msg)

    def register_victim(self, actor_handle) -> bool:
        if self.victim is None:
            self.victim = actor_handle
            return True
        return False

    def pop_victim(self):
        v, self.victim = self.victim, None
        return v

    def record_error(self, err_text: str):
        self.errors.append(err_text)

    def drain(self):
        out, self.logs = list(self.logs), []
        return out, list(self.errors)


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

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

    def _call(self, fn: str, *a, **kw):
        return ray.get(ray.get_actor("vfio_ab_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 = io.BytesIO()
        orig = b.close

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

        b.close = _close
        return b


for _fn in ("mkdir", "makedirs", "rm", "info", "ls"):
    setattr(_MemFS, _fn, lambda self, *a, _f=_fn, **kw: self._call(_f, *a, **kw))


class _AuditCallback(cb.ControllerCallback):
    def after_controller_state_update(self, prev, curr):
        p, c = type(prev).__name__, type(curr).__name__
        if p == c:
            return
        hub = ray.get_actor("vfio_ab_hub")
        err = getattr(curr, "training_failed_error", None)
        msg = f"[Controller] {p} -> {c}"
        if err is not None:
            full_tb = _strip_ansi(
                "".join(traceback.format_exception(type(err), err, err.__traceback__))
            )
            wf = getattr(err, "worker_failures", None)
            if wf:
                full_tb += "\n" + "\n".join(
                    f"worker {k}: {_strip_ansi(str(v))}" for k, v in wf.items()
                )
            ray.get(hub.record_error.remote(full_tb))
            summary = next(
                (
                    ln.strip()
                    for ln in full_tb.splitlines()
                    if "Device or resource busy" in ln
                    or "Couldn't open iommu group" in ln
                    or "Failed to acquire a TPU device node" in ln
                    or "RayActorError" in ln
                ),
                full_tb.strip().splitlines()[-1] if full_tb.strip() else str(err),
            )
            msg += f" | failure={summary}"
        ray.get(hub.log.remote(msg))


@ray.remote(num_cpus=0)
def snapshot_worker_log_offsets() -> dict[str, int]:
    offsets = {}
    for path in glob.glob("/tmp/ray/session_latest/logs/*worker*"):
        try:
            offsets[path] = os.path.getsize(path)
        except OSError:
            continue
    return offsets


@ray.remote(num_cpus=0)
def collect_vfio_worker_logs(offsets: dict[str, int]) -> list[str]:
    matches = []
    for path in sorted(glob.glob("/tmp/ray/session_latest/logs/*worker*")):
        try:
            size = os.path.getsize(path)
            start = offsets.get(path, 0)
            if size <= start:
                continue
            with open(path, "rb") as bf:
                bf.seek(start)
                text = bf.read().decode("utf-8", errors="ignore")
            for line in text.splitlines():
                if (
                    "TPU VFIO devices" in line
                    or "Timed out after" in line
                    or "Couldn't open iommu group" in line
                    or "Device or resource busy" in line
                    or "Failed to acquire a TPU device node" in line
                ):
                    matches.append(_strip_ansi(line.rstrip()))
        except OSError:
            continue
    return matches


@ray.remote(num_cpus=0)
def wait_host_vfio_idle() -> None:
    vfio_devs = [f"/dev/vfio/{e}" for e in os.listdir("/dev/vfio") if e.isdigit()]
    deadline = time.monotonic() + 15.0
    while time.monotonic() < deadline:
        busy = False
        for d in vfio_devs:
            try:
                os.close(os.open(d, os.O_RDWR))
            except OSError as exc:
                if exc.errno == errno.EBUSY:
                    busy = True
                    break
        if not busy:
            return
        time.sleep(0.05)


@ray.remote(num_cpus=0)
def measure_kernel_vfio_unpin_window() -> dict:
    child_code = """
import os, resource, time
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
import jax, jax.numpy as jnp, numpy as np
devs = jax.local_devices()
sh = jax.sharding.NamedSharding(jax.sharding.Mesh(np.array(devs), ("i",)), jax.sharding.PartitionSpec("i"))
b = jax.jit(lambda: jnp.ones((len(devs), 8192, 1024, 1024), dtype=jnp.float32), out_shardings=sh)()
b.block_until_ready()
vfio = sorted(
    os.readlink(f"/proc/self/fd/{fd}")
    for fd in os.listdir("/proc/self/fd")
    if os.path.exists(f"/proc/self/fd/{fd}")
    and os.readlink(f"/proc/self/fd/{fd}").startswith("/dev/vfio/")
    and os.readlink(f"/proc/self/fd/{fd}") != "/dev/vfio/vfio"
)
print("READY", len(devs), devs[0].device_kind, ",".join(vfio), flush=True)
time.sleep(60)
"""
    p = subprocess.Popen(
        [sys.executable, "-c", child_code], stdout=subprocess.PIPE, text=True
    )
    parts = p.stdout.readline().strip().split(" ")
    ncores, kind, targets = int(parts[1]), parts[2], parts[3].split(",")
    t0 = time.monotonic()
    os.kill(p.pid, signal.SIGKILL)
    released = {}
    ebusy_probes = 0
    while len(released) < len(targets) and time.monotonic() - t0 < 15.0:
        for d in targets:
            if d in released:
                continue
            try:
                fd = os.open(d, os.O_RDWR)
            except OSError as exc:
                if exc.errno == errno.EBUSY:
                    ebusy_probes += 1
            else:
                os.close(fd)
                released[d] = round(time.monotonic() - t0, 3)
        if len(released) < len(targets):
            time.sleep(0.01)
    p.wait()
    return {
        "device_kind": kind,
        "num_cores": ncores,
        "allocated_hbm_gib": ncores * 32,
        "ebusy_probes": ebusy_probes,
        "released_after_sigkill_s": released,
    }


# ---------------------------------------------------------------------------
# Workload 1A: Warm Ray TPU Actor Rapid Replacement
# ---------------------------------------------------------------------------
@ray.remote(num_cpus=1)
def _prewarm_jax_worker_slot(hold_s: float = 0.4) -> int:
    import jax  # noqa: F401

    resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
    time.sleep(hold_s)
    return os.getpid()


@ray.remote(num_cpus=0, max_restarts=0)
class _WarmTpuJaxActor:
    def __init__(self):
        import jax  # noqa: F401

        resource.setrlimit(resource.RLIMIT_CORE, (0, 0))

    def ping(self) -> int:
        return os.getpid()

    def init_and_compute(self, use_readiness_wait: bool) -> dict:
        import jax
        import jax.numpy as jnp

        wait_s = 0.0
        if use_readiness_wait:
            from ray._private.accelerators.tpu import wait_for_tpu_vfio_ready

            t0 = time.monotonic()
            wait_for_tpu_vfio_ready()
            wait_s = round(time.monotonic() - t0, 3)

        devs = jax.local_devices()
        buf = _alloc_tpu_64gib(jax, jnp, devs)
        fn = jax.pmap(lambda x: jax.lax.psum(x, "i"), axis_name="i")
        psum_val = float(
            jax.device_get(fn(jnp.arange(1, len(devs) + 1, dtype=jnp.float32))[0])
            + 0.0 * jax.device_get(buf[0, 0, 0, 0])
        )
        return {
            "pid": os.getpid(),
            "cores": len(devs),
            "device_kind": devs[0].device_kind,
            "wait_s": wait_s,
            "psum": psum_val,
        }


@ray.remote(num_cpus=0)
def _sigkill_pid_on_node(pid: int) -> None:
    os.kill(pid, signal.SIGKILL)


def run_direct_task_case(mode: str, hub, target_node: str) -> dict:
    label = "BASELINE A (Unpatched)" if mode == "baseline" else "TREATMENT B (Patched)"
    print("\n" + "=" * 76)
    print(
        f"WORKLOAD 1A [{label}]: @ray.remote 8-Core tpu7x Rapid Reuse During VFIO Teardown"
    )
    print("=" * 76, flush=True)
    ray.get(
        wait_host_vfio_idle.options(scheduling_strategy=Pin(target_node, soft=False)).remote()
    )
    ray.get(hub.reset.remote())
    w2 = _WarmTpuJaxActor.options(
        scheduling_strategy=Pin(target_node, soft=False)
    ).remote()
    w2_pid = ray.get(w2.ping.remote())
    holder = _PriorTpuHolder.options(
        scheduling_strategy=Pin(target_node, soft=False)
    ).remote()
    held_vfio = ray.get(
        holder.start_and_arm_sigkill_on_train_import.remote("NONE_MANUAL")
    )
    print(
        f"[Setup] Warm replacement actor ready (pid={w2_pid}); prior 256-GiB TPU worker active on {held_vfio}",
        flush=True,
    )

    log_offsets = ray.get(
        snapshot_worker_log_offsets.options(
            scheduling_strategy=Pin(target_node, soft=False)
        ).remote()
    )
    t_kill = time.monotonic()
    ray.get(holder.sigkill_async.remote())
    time.sleep(0.05)
    r2_ref = w2.init_and_compute.remote(use_readiness_wait=(mode == "treatment"))

    try:
        r2 = ray.get(r2_ref)
        elapsed_s = round(time.monotonic() - t_kill, 3)
        print(f"[Worker 2] Replacement succeeded in {elapsed_s}s: {r2}", flush=True)
        outcome = {"succeeded": True, "result": r2}
    except Exception as exc:
        elapsed_s = round(time.monotonic() - t_kill, 3)
        err_msg = _strip_ansi(str(exc)).strip().splitlines()[-1]
        print(f"[Worker 2] Replacement CRASHED after {elapsed_s}s: {err_msg}", flush=True)
        outcome = {"succeeded": False, "error": err_msg}
    finally:
        ray.kill(w2, no_restart=True)

    time.sleep(0.3)
    wlogs = ray.get(
        collect_vfio_worker_logs.options(
            scheduling_strategy=Pin(target_node, soft=False)
        ).remote(log_offsets)
    )
    for line in wlogs:
        print(f"[Worker Log] {line}", flush=True)
    outcome["ebusy_logs"] = [
        ln
        for ln in wlogs
        if "Device or resource busy" in ln or "Couldn't open iommu group" in ln
    ]
    outcome["vfio_ready_logs"] = [ln for ln in wlogs if "TPU VFIO devices" in ln]
    ray.kill(holder, no_restart=True)
    ray.get(
        wait_host_vfio_idle.options(scheduling_strategy=Pin(target_node, soft=False)).remote()
    )
    return outcome


# ---------------------------------------------------------------------------
# Workload 1B: JaxTrainer Rapid Reuse Under Kernel Unpinning + Fault Recovery
# ---------------------------------------------------------------------------
def _jax_train_fn(_: dict) -> None:
    import jax
    import jax.numpy as jnp

    resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
    hub = ray.get_actor("vfio_ab_hub")
    st0 = 0
    w = np.random.default_rng(42).standard_normal((2048, 2048), np.float32) * 0.02
    ckpt = rt.get_checkpoint()
    if ckpt:
        with ckpt.as_directory() as d, open(f"{d}/state.pkl", "rb") as f:
            st0, w = pickle.load(f)
        ray.get(hub.log.remote(f"[JaxWorker] Restored checkpoint at step={st0}"))

    devs = jax.local_devices()
    nd = len(devs)
    ray.get(
        hub.log.remote(
            f"[JaxWorker] JAX initialized on {nd}x {devs[0].device_kind} cores"
        )
    )

    hold = _alloc_tpu_64gib(jax, jnp, devs, gib_per_core=32)
    sharding = jax.sharding.NamedSharding(
        jax.sharding.Mesh(np.array(devs), ("i",)), jax.sharding.PartitionSpec("i")
    )
    rw = jax.device_put(np.broadcast_to(w, (nd, *w.shape)), sharding)

    step_fn = jax.pmap(
        lambda pw, xl, yl: (
            loss_grad := jax.value_and_grad(
                lambda m: jnp.mean((jnp.tanh(xl @ m) - yl) ** 2)
            )(pw),
            pw - 0.05 * jax.lax.pmean(loss_grad[1], "i"),
            jax.lax.pmean(loss_grad[0], "i"),
        )[1:],
        axis_name="i",
    )

    for s in range(st0 + 1, 4):
        xl = np.random.default_rng(100 + s).standard_normal((nd, 64, 2048), np.float32)
        yl = np.roll(xl, 1, axis=-1) * 0.5
        rw, la = step_fn(rw, xl, yl)
        loss = round(
            float(jax.device_get(la[0])) + 0.0 * float(jax.device_get(hold[0, 0, 0, 0])),
            6,
        )

        if s == 2 and st0 == 0:
            time.sleep(0.25)
            self_actor = ray.get_runtime_context().current_actor
            if ray.get(hub.register_victim.remote(self_actor)):
                ray.get(
                    hub.log.remote("[JaxWorker] Ready for mid-step-2 SIGKILL injection")
                )
                time.sleep(10.0)

        hw = np.asarray(jax.device_get(rw[0]))
        os.makedirs("/tmp/vfio_jax_ckpt", exist_ok=True)
        with open("/tmp/vfio_jax_ckpt/state.pkl", "wb") as f:
            pickle.dump((s, hw), f)
        rt.report(
            {"step": s, "loss": loss, "cores": nd},
            checkpoint=rt.Checkpoint.from_directory("/tmp/vfio_jax_ckpt"),
        )
        ray.get(hub.log.remote(f"[JaxWorker] Step {s} committed (loss={loss:.6f})"))


@ray.remote(num_cpus=0)
def _fit_jax_trainer(run_name: str, max_failures: int) -> dict:
    os.environ["RAY_TRAIN_HEALTH_CHECK_INTERVAL_S"] = "0.05"
    fs = pyarrow.fs.PyFileSystem(pyarrow.fs.FSSpecHandler(_MemFS()))
    sc = rt.ScalingConfig(
        num_workers=1,
        resources_per_worker={"TPU": 4},
        use_tpu=True,
        topology="2x2x1",
        accelerator_type="TPU-V7X",
    )
    rc = rt.RunConfig(
        name=run_name,
        storage_path=f"jax_{run_name}",
        storage_filesystem=fs,
        callbacks=[_AuditCallback()],
        failure_config=rt.FailureConfig(max_failures=max_failures),
    )
    return dict(JaxTrainer(_jax_train_fn, scaling_config=sc, run_config=rc).fit().metrics)


def run_jax_trainer_case(mode: str, hub, target_node: str) -> dict:
    label = "BASELINE A (Unpatched)" if mode == "baseline" else "TREATMENT B (Patched)"
    print("\n" + "=" * 76)
    print(f"WORKLOAD 1B [{label}]: JaxTrainer 8-Core tpu7x Rapid Reuse & Fault Recovery")
    print("=" * 76, flush=True)
    ray.get(
        wait_host_vfio_idle.options(scheduling_strategy=Pin(target_node, soft=False)).remote()
    )
    holder = _PriorTpuHolder.options(
        scheduling_strategy=Pin(target_node, soft=False)
    ).remote()
    held_vfio = ray.get(
        holder.start_and_arm_sigkill_on_train_import.remote("jaxlib", 1, 1.20)
    )
    print(
        f"[Setup] Armed SIGKILL of prior 256-GiB TPU worker on {held_vfio} upon RayTrainWorker jaxlib load",
        flush=True,
    )

    ray.get(hub.reset.remote())
    log_offsets = ray.get(
        snapshot_worker_log_offsets.options(
            scheduling_strategy=Pin(target_node, soft=False)
        ).remote()
    )
    head_id = ray.get_runtime_context().get_node_id()
    max_failures = 0 if mode == "baseline" else 1
    fit_ref = _fit_jax_trainer.options(
        scheduling_strategy=Pin(head_id, soft=False)
    ).remote(f"jax_{mode}", max_failures)

    killed = False
    while True:
        done, _ = ray.wait([fit_ref], timeout=0.05)
        logs, _ = ray.get(hub.drain.remote())
        for m in logs:
            print(m, flush=True)
        if not killed:
            victim = ray.get(hub.pop_victim.remote())
            if victim is not None:
                print("[Driver] Injecting ray.kill(jax_worker) mid-step 2...", flush=True)
                ray.kill(victim, no_restart=True)
                killed = True
        if done:
            try:
                metrics = ray.get(fit_ref)
            except Exception as exc:
                metrics = {"failed": _summarize_exc(exc)}
            logs, errs = ray.get(hub.drain.remote())
            for m in logs:
                print(m, flush=True)
            break

    time.sleep(0.3)
    wlogs = ray.get(
        collect_vfio_worker_logs.options(
            scheduling_strategy=Pin(target_node, soft=False)
        ).remote(log_offsets)
    )
    for line in wlogs:
        print(f"[Worker Log] {line}", flush=True)
    ray.kill(holder, no_restart=True)

    ebusy_hits = sum(
        1
        for e in errs
        if "Device or resource busy" in e
        or "Couldn't open iommu group" in e
        or "Failed to acquire a TPU device node" in e
    ) + sum(
        1
        for ln in wlogs
        if "Device or resource busy" in ln
        or "Couldn't open iommu group" in ln
        or "Failed to acquire a TPU device node" in ln
    )
    summary = {
        "metrics": metrics,
        "controller_failures": len(errs),
        "ebusy_hits": ebusy_hits,
        "vfio_ready_logs": [ln for ln in wlogs if "TPU VFIO devices" in ln],
    }
    print(
        f"[Workload 1B {mode} Summary] metrics={metrics}, "
        f"controller_failures={len(errs)}, ebusy_hits={ebusy_hits}, "
        f"vfio_ready_logs={len(summary['vfio_ready_logs'])}",
        flush=True,
    )
    return summary


# ---------------------------------------------------------------------------
# Workload 2: Sub-Host 2-Chip Peer Isolation + Intra-Chip VF Isolation on tpu7x
# ---------------------------------------------------------------------------
@ray.remote(resources={"TPU": 2}, max_restarts=0)
class SubHostPeerWorkerA:
    def init_worker(self) -> dict:
        import jax
        import jax.numpy as jnp
        from ray._private.accelerators.tpu import get_current_process_tpu_vfio_devices

        resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
        vis_chips = os.environ.get("TPU_VISIBLE_CHIPS")
        scoped_vfio = get_current_process_tpu_vfio_devices()
        devs = jax.local_devices()
        self._step_fn = jax.pmap(
            lambda x: jax.lax.psum(jnp.mean((x @ x.T) * 0.001), "i"),
            axis_name="i",
        )
        sharding = jax.sharding.NamedSharding(
            jax.sharding.Mesh(np.array(devs), ("i",)), jax.sharding.PartitionSpec("i")
        )
        self._buf = jax.device_put(
            jnp.ones((len(devs), 1024, 1024), dtype=jnp.float32), sharding
        )
        out = float(jax.device_get(self._step_fn(self._buf)[0]))
        return {
            "visible_chips": vis_chips,
            "scoped_vfio": scoped_vfio,
            "num_cores": len(devs),
            "init_psum": round(out, 4),
        }

    def run_continuous_compute(self, duration_s: float) -> dict:
        import jax

        t_end = time.monotonic() + duration_s
        iters = 0
        while time.monotonic() < t_end:
            val = float(jax.device_get(self._step_fn(self._buf)[0]))
            assert val > 0.0
            iters += 1
            time.sleep(0.03)
        return {"worker_a_iters": iters, "errors": 0}


@ray.remote(resources={"TPU": 2}, max_retries=0)
def _subhost_victim_task_b(
    simulate_ray67029_dual_env: bool, hold_latch=None
) -> dict:
    import jax
    import jax.numpy as jnp
    from ray._private.accelerators.tpu import (
        get_current_process_tpu_vfio_devices,
        wait_for_tpu_vfio_ready,
    )

    resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
    vis_chips = os.environ.get("TPU_VISIBLE_CHIPS")
    if simulate_ray67029_dual_env and vis_chips is not None:
        os.environ["TPU_VISIBLE_DEVICES"] = vis_chips
    scoped_vfio = get_current_process_tpu_vfio_devices()
    t0 = time.monotonic()
    wait_for_tpu_vfio_ready()
    wait_s = round(time.monotonic() - t0, 3)

    devs = jax.local_devices()
    buf = _alloc_tpu_64gib(jax, jnp, devs)
    fn = jax.pmap(lambda v: jax.lax.psum(v * 2.0, "i"), axis_name="i")
    psum_val = float(
        jax.device_get(fn(jnp.arange(1, len(devs) + 1, dtype=jnp.float32))[0])
        + 0.0 * jax.device_get(buf[0, 0, 0, 0])
    )
    info = {
        "pid": os.getpid(),
        "visible_chips": vis_chips,
        "tpu_visible_devices": os.environ.get("TPU_VISIBLE_DEVICES"),
        "scoped_vfio": scoped_vfio,
        "wait_s": wait_s,
        "num_cores": len(devs),
        "psum": psum_val,
    }
    if hold_latch is not None:
        ray.get(hold_latch.log.remote(f"B_INFO:{pickle.dumps(info).hex()}"))
        time.sleep(30.0)
    return info


def run_workload_2_subhost_isolation(hub, target_node: str) -> None:
    print("\n" + "=" * 76)
    print(
        "WORKLOAD 2 [TREATMENT B]: Sub-Host Multi-Worker & Intra-Chip VF Isolation on tpu7x"
    )
    print("=" * 76, flush=True)
    ray.get(
        wait_host_vfio_idle.options(scheduling_strategy=Pin(target_node, soft=False)).remote()
    )
    # Pre-warm 5 idle worker processes with `import jax` so each killed Worker B task
    # is replaced immediately inside the 2.4s VFIO unpinning window!
    ray.get(
        [
            _prewarm_jax_worker_slot.options(
                scheduling_strategy=Pin(target_node, soft=False)
            ).remote(0.5)
            for _ in range(5)
        ]
    )
    log_offsets = ray.get(
        snapshot_worker_log_offsets.options(
            scheduling_strategy=Pin(target_node, soft=False)
        ).remote()
    )

    worker_a = SubHostPeerWorkerA.options(
        scheduling_strategy=Pin(target_node, soft=False)
    ).remote()
    info_a = ray.get(worker_a.init_worker.remote())
    print(f"[Worker A (Healthy Peer)] {info_a}", flush=True)

    compute_a_ref = worker_a.run_continuous_compute.remote(12.0)

    def _launch_and_await_b(dual_env: bool) -> dict:
        ray.get(hub.reset.remote())
        b_ref = _subhost_victim_task_b.options(
            scheduling_strategy=Pin(target_node, soft=False)
        ).remote(dual_env, hold_latch=hub)
        while True:
            logs, _ = ray.get(hub.drain.remote())
            for m in logs:
                if m.startswith("B_INFO:"):
                    return pickle.loads(bytes.fromhex(m.split(":", 1)[1]))
            done, _ = ray.wait([b_ref], timeout=0.02)
            if done:
                return ray.get(b_ref)

    info_b = _launch_and_await_b(dual_env=True)
    print(f"[Worker B Initial] {info_b}", flush=True)
    assert set(info_a["scoped_vfio"]).isdisjoint(info_b["scoped_vfio"])

    for cycle in range(1, 4):
        t_kill = time.monotonic()
        ray.get(
            _sigkill_pid_on_node.options(
                scheduling_strategy=Pin(target_node, soft=False)
            ).remote(info_b["pid"])
        )
        info_b = _launch_and_await_b(dual_env=(cycle == 2))
        total_s = round(time.monotonic() - t_kill, 3)
        print(
            f"[Worker B Rapid Restart #{cycle}] wait_s={info_b['wait_s']}s, "
            f"total_recovery_s={total_s}s, scoped_vfio={info_b['scoped_vfio']}, "
            f"cores={info_b['num_cores']}, psum={info_b['psum']}",
            flush=True,
        )
        assert set(info_a["scoped_vfio"]).isdisjoint(info_b["scoped_vfio"])
        assert info_b["wait_s"] < 4.5, (
            f"Stalled {info_b['wait_s']}s on healthy peer's VFIO groups!"
        )

    res_a = ray.get(compute_a_ref)
    print(f"[Worker A Uninterrupted Result] {res_a}", flush=True)
    assert res_a["worker_a_iters"] >= 50 and res_a["errors"] == 0
    ray.get(
        _sigkill_pid_on_node.options(
            scheduling_strategy=Pin(target_node, soft=False)
        ).remote(info_b["pid"])
    )
    ray.kill(worker_a, no_restart=True)
    time.sleep(0.2)
    for line in ray.get(
        collect_vfio_worker_logs.options(
            scheduling_strategy=Pin(target_node, soft=False)
        ).remote(log_offsets)
    ):
        print(f"[Worker Log] {line}", flush=True)

    ray.get(
        wait_host_vfio_idle.options(scheduling_strategy=Pin(target_node, soft=False)).remote()
    )

    @ray.remote(num_cpus=0)
    def verify_intrachip_vf_isolation() -> dict:
        from ray._private.accelerators.tpu import (
            get_current_process_tpu_vfio_devices,
            wait_for_tpu_vfio_ready,
        )

        vf4 = get_current_process_tpu_vfio_devices(visible_devices="4")
        vf5 = get_current_process_tpu_vfio_devices(visible_devices="5")
        assert len(vf4) == 1 and len(vf5) == 1 and vf4 != vf5
        fd_vf4 = os.open(vf4[0], os.O_RDWR)
        try:
            t0 = time.monotonic()
            wait_for_tpu_vfio_ready(timeout_s=2.0, visible_devices="5")
            dt = round(time.monotonic() - t0, 4)
        finally:
            os.close(fd_vf4)
        return {
            "chip2_vf0_held_busy": vf4[0],
            "chip2_vf1_probed": vf5[0],
            "wait_s": dt,
        }

    intra = ray.get(
        verify_intrachip_vf_isolation.options(
            scheduling_strategy=Pin(target_node, soft=False)
        ).remote()
    )
    print(f"[Workload 2b Intra-Chip Dual-VF Isolation] {intra}", flush=True)
    assert intra["wait_s"] < 0.2


# ---------------------------------------------------------------------------
# Workload 3: TorchTrainer (tpu_dist) 8-VF Rapid Reuse & Fault Recovery
# ---------------------------------------------------------------------------
def _torch_train_fn(_: dict) -> None:
    import torch
    import torch.distributed as dist
    import torch_tpu  # noqa: F401

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

    st0 = 0
    ckpt = rt.get_checkpoint()
    if ckpt:
        with ckpt.as_directory() as d, open(f"{d}/tstate.pkl", "rb") as f:
            st0 = pickle.load(f)
        if rk == 0:
            ray.get(hub.log.remote(f"[TorchWorker 0] Restored checkpoint at step={st0}"))

    dev = torch.device("tpu:0")
    hold = torch.ones((1024, 1024, 1024), dtype=torch.float32, device=dev)
    w = torch.full((1024, 1024), 0.01 * (rk + 1), dtype=torch.float32, device=dev)
    if rk == 0:
        ray.get(
            hub.log.remote(
                f"[TorchWorker 0] tpu_dist initialized across world_size={wd} tpu7x VFs"
            )
        )

    for s in range(st0 + 1, 4):
        y = (w @ w.T).mean() + 0.0 * hold[0, 0, 0]
        dist.all_reduce(y)
        val = round(float(y.cpu().item()), 6)

        if s == 2 and st0 == 0 and lrk == 3:
            time.sleep(0.25)
            self_actor = ray.get_runtime_context().current_actor
            if ray.get(hub.register_victim.remote(self_actor)):
                ray.get(
                    hub.log.remote(
                        "[TorchWorker 3 (VF 3)] Ready for mid-step-2 SIGKILL injection"
                    )
                )
                time.sleep(10.0)

        out_c = None
        if rk == 0:
            os.makedirs("/tmp/vfio_torch_ckpt", exist_ok=True)
            with open("/tmp/vfio_torch_ckpt/tstate.pkl", "wb") as f:
                pickle.dump(s, f)
            out_c = rt.Checkpoint.from_directory("/tmp/vfio_torch_ckpt")
        rt.report({"step": s, "all_reduce_sum": val, "world_size": wd}, checkpoint=out_c)
        if rk == 0:
            ray.get(
                hub.log.remote(
                    f"[TorchWorker 0] Step {s} committed (all_reduce_sum={val:.6f})"
                )
            )


@ray.remote(num_cpus=0)
def _fit_torch_trainer(run_name: str, max_failures: int) -> dict:
    from ray.train.torch import TorchConfig, TorchTrainer

    os.environ["RAY_TRAIN_HEALTH_CHECK_INTERVAL_S"] = "0.1"
    fs = pyarrow.fs.PyFileSystem(pyarrow.fs.FSSpecHandler(_MemFS()))
    sc = rt.ScalingConfig(
        num_workers=8,
        use_tpu=False,
        resources_per_worker={"CPU": 1},
        label_selector={"ray.io/node-group": "tpu-group"},
        placement_strategy="PACK",
    )
    rc = rt.RunConfig(
        name=run_name,
        storage_path=f"torch_{run_name}",
        storage_filesystem=fs,
        callbacks=[_AuditCallback()],
        failure_config=rt.FailureConfig(max_failures=max_failures),
    )
    trainer = TorchTrainer(
        _torch_train_fn,
        torch_config=TorchConfig(backend="tpu_dist"),
        scaling_config=sc,
        run_config=rc,
    )
    return dict(trainer.fit().metrics)


def run_torch_trainer_case(mode: str, hub, target_node: str) -> dict:
    label = "BASELINE A (Unpatched)" if mode == "baseline" else "TREATMENT B (Patched)"
    print("\n" + "=" * 76)
    print(
        f"WORKLOAD 3 [{label}]: TorchTrainer (tpu_dist) 8-VF tpu7x Rapid Reuse & Fault Recovery"
    )
    print("=" * 76, flush=True)
    ray.get(
        wait_host_vfio_idle.options(scheduling_strategy=Pin(target_node, soft=False)).remote()
    )
    holder = _PriorTpuHolder.options(
        scheduling_strategy=Pin(target_node, soft=False)
    ).remote()
    held_vfio = ray.get(
        holder.start_and_arm_sigkill_on_train_import.remote("libtorch", 8, 4.8)
    )
    print(
        f"[Setup] Armed 4.8s SIGTERM-grace -> SIGKILL of prior 256-GiB TPU worker on {held_vfio} upon 8x RayTrainWorker libtorch load",
        flush=True,
    )

    ray.get(hub.reset.remote())
    log_offsets = ray.get(
        snapshot_worker_log_offsets.options(
            scheduling_strategy=Pin(target_node, soft=False)
        ).remote()
    )
    head_id = ray.get_runtime_context().get_node_id()
    max_failures = 0 if mode == "baseline" else 1
    fit_ref = _fit_torch_trainer.options(
        scheduling_strategy=Pin(head_id, soft=False)
    ).remote(f"torch_{mode}", max_failures)

    killed = False
    while True:
        done, _ = ray.wait([fit_ref], timeout=0.1)
        logs, _ = ray.get(hub.drain.remote())
        for m in logs:
            print(m, flush=True)
        if not killed:
            victim = ray.get(hub.pop_victim.remote())
            if victim is not None:
                print(
                    "[Driver] Injecting ray.kill(torch_worker_3) mid-step 2...",
                    flush=True,
                )
                ray.kill(victim, no_restart=True)
                killed = True
        if done:
            try:
                metrics = ray.get(fit_ref)
            except Exception as exc:
                metrics = {"failed": _summarize_exc(exc)}
            logs, errs = ray.get(hub.drain.remote())
            for m in logs:
                print(m, flush=True)
            break

    time.sleep(0.3)
    wlogs = ray.get(
        collect_vfio_worker_logs.options(
            scheduling_strategy=Pin(target_node, soft=False)
        ).remote(log_offsets)
    )
    for line in wlogs:
        print(f"[Worker Log] {line}", flush=True)
    ray.kill(holder, no_restart=True)

    ebusy_hits = sum(
        1
        for e in errs
        if "Device or resource busy" in e
        or "Couldn't open iommu group" in e
        or "Failed to acquire a TPU device node" in e
    ) + sum(
        1
        for ln in wlogs
        if "Device or resource busy" in ln
        or "Couldn't open iommu group" in ln
        or "Failed to acquire a TPU device node" in ln
    )
    summary = {
        "metrics": metrics,
        "controller_failures": len(errs),
        "ebusy_hits": ebusy_hits,
        "vfio_ready_logs": [ln for ln in wlogs if "TPU VFIO devices" in ln],
    }
    print(
        f"[Workload 3 {mode} Summary] metrics={metrics}, "
        f"controller_failures={len(errs)}, ebusy_hits={ebusy_hits}, "
        f"vfio_ready_logs={len(summary['vfio_ready_logs'])}",
        flush=True,
    )
    return summary


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--mode", choices=["baseline", "treatment"], required=True)
    args = parser.parse_args()

    os.environ["RAY_IGNORE_UNHANDLED_ERRORS"] = "1"
    ray.init(address="auto", log_to_driver=False)
    tpu_nodes = sorted(
        [n for n in ray.nodes() if n.get("Alive") and n["Resources"].get("TPU", 0) >= 4],
        key=lambda n: n["NodeID"],
    )
    assert tpu_nodes, "No live 4-chip TPU nodes found in cluster"
    target_node = tpu_nodes[0]["NodeID"]

    hub = _Hub.options(name="vfio_ab_hub").remote()
    try:
        if args.mode == "baseline":
            print("=" * 76)
            print("BASELINE A (PART 0): Live tpu7x Kernel SIGKILL -> VFIO Unpinning Window")
            print("=" * 76, flush=True)
            probe = ray.get(
                measure_kernel_vfio_unpin_window.options(
                    scheduling_strategy=Pin(target_node, soft=False)
                ).remote()
            )
            print(f"[Kernel Unpin Probe] {probe}", flush=True)

            d_base = run_direct_task_case("baseline", hub, target_node)
            assert not d_base["succeeded"] and (
                "Device or resource busy" in d_base.get("error", "")
                or len(d_base["ebusy_logs"]) >= 1
            )

            j_base = run_jax_trainer_case("baseline", hub, target_node)
            assert j_base["ebusy_hits"] >= 1

            t_base = run_torch_trainer_case("baseline", hub, target_node)
            assert t_base["ebusy_hits"] >= 1

            print(
                "\nALL BASELINE A UNPATCHED EBUSY REPRODUCTION ASSERTIONS CONFIRMED!",
                flush=True,
            )
        else:
            d_treat = run_direct_task_case("treatment", hub, target_node)
            assert d_treat["succeeded"] and len(d_treat["ebusy_logs"]) == 0
            assert len(d_treat["vfio_ready_logs"]) >= 1

            s1 = run_jax_trainer_case("treatment", hub, target_node)
            assert s1["metrics"].get("step") == 3
            assert s1["ebusy_hits"] == 0 and s1["controller_failures"] == 1
            assert len(s1["vfio_ready_logs"]) >= 1

            run_workload_2_subhost_isolation(hub, target_node)

            s3 = run_torch_trainer_case("treatment", hub, target_node)
            assert s3["metrics"].get("step") == 3 and s3["metrics"].get("world_size") == 8
            assert s3["ebusy_hits"] == 0 and s3["controller_failures"] == 1
            assert len(s3["vfio_ready_logs"]) >= 1

            print("\nALL TREATMENT B LIVE TPU7X HARDWARE ASSERTIONS PASSED!", flush=True)
    finally:
        ray.get(
            wait_host_vfio_idle.options(scheduling_strategy=Pin(target_node, soft=False)).remote()
        )
        ray.kill(hub)


if __name__ == "__main__":
    main()

Step 3: Apply PR Changes and Run Treatment Verification

Copy the three modified files from this PR onto every pod and run --mode treatment:

for pod in $(kubectl get pods -l ray.io/cluster=ray-tpu-vfio-verify -o jsonpath='{.items[*].metadata.name}'); do
  for rel in _private/accelerators/tpu.py train/v2/jax/config.py train/torch/config.py; do
    kubectl cp "python/ray/$rel" "$pod:/home/ray/anaconda3/lib/python3.11/site-packages/ray/$rel"
  done
done
kubectl exec "$HEAD_POD" -- python3 -u /tmp/run_vfio_ab_e2e.py --mode treatment

Step 4: Verbatim Output

1. With This PR (--mode treatment)

2026-10-31 06:19:36,570	INFO worker.py:1683 -- Using address 127.0.0.1:6379 set in the environment variable RAY_ADDRESS
2026-10-31 06:19:36,572	INFO worker.py:1833 -- Connecting to existing Ray cluster at address: 10.228.3.117:6379...
2026-10-31 06:19:36,585	INFO worker.py:2015 -- Connected to Ray cluster. View the dashboard at �[1m�[32mhttp://10.228.3.117:8265 �[39m�[22m

============================================================================
WORKLOAD 1A [TREATMENT B (Patched)]: @ray.remote 8-Core tpu7x Rapid Reuse During VFIO Teardown
============================================================================
[Setup] Warm replacement actor ready (pid=199005); prior 256-GiB TPU worker active on ['/dev/vfio/2', '/dev/vfio/3', '/dev/vfio/4', '/dev/vfio/6']
[Worker 2] Replacement succeeded in 5.844s: {'pid': 199005, 'cores': 8, 'device_kind': 'TPU7x', 'wait_s': 1.848, 'psum': 36.0}
[Worker Log] TPU VFIO devices ['/dev/vfio/4', '/dev/vfio/5', '/dev/vfio/3', '/dev/vfio/0', '/dev/vfio/2', '/dev/vfio/1', '/dev/vfio/6', '/dev/vfio/7'] became ready after 1.80s.

============================================================================
WORKLOAD 1B [TREATMENT B (Patched)]: JaxTrainer 8-Core tpu7x Rapid Reuse & Fault Recovery
============================================================================
[Setup] Armed SIGKILL of prior 256-GiB TPU worker on ['/dev/vfio/2', '/dev/vfio/3', '/dev/vfio/4', '/dev/vfio/6'] upon RayTrainWorker jaxlib load
[Controller] InitializingState -> SchedulingState
[Controller] SchedulingState -> RunningState
[JaxWorker] JAX initialized on 8x TPU7x cores
[JaxWorker] Step 1 committed (loss=0.608425)
[Driver] Injecting ray.kill(jax_worker) mid-step 2...
[JaxWorker] Ready for mid-step-2 SIGKILL injection
[Controller] RunningState -> RestartingState | failure=The actor is dead because it was killed by `ray.kill`.
[Controller] RestartingState -> SchedulingState
[Controller] SchedulingState -> RunningState
[JaxWorker] Restored checkpoint at step=1
[JaxWorker] JAX initialized on 8x TPU7x cores
[JaxWorker] Step 2 committed (loss=0.607806)
[JaxWorker] Step 3 committed (loss=0.607885)
[Controller] RunningState -> ShuttingDownState
[Controller] ShuttingDownState -> FinishedState
[Worker Log] TPU VFIO devices ['/dev/vfio/4', '/dev/vfio/5', '/dev/vfio/3', '/dev/vfio/0', '/dev/vfio/2', '/dev/vfio/1', '/dev/vfio/6', '/dev/vfio/7'] became ready after 3.33s.
[Workload 1B treatment Summary] metrics={'step': 3, 'loss': 0.607885, 'cores': 8}, controller_failures=1, ebusy_hits=0, vfio_ready_logs=1

============================================================================
WORKLOAD 2 [TREATMENT B]: Sub-Host Multi-Worker & Intra-Chip VF Isolation on tpu7x
============================================================================
[Worker A (Healthy Peer)] {'visible_chips': '0,1', 'scoped_vfio': ['/dev/vfio/4', '/dev/vfio/5', '/dev/vfio/3', '/dev/vfio/0'], 'num_cores': 4, 'init_psum': 4.096}
[Worker B Initial] {'pid': 205712, 'visible_chips': '2,3', 'tpu_visible_devices': '2,3', 'scoped_vfio': ['/dev/vfio/2', '/dev/vfio/1', '/dev/vfio/6', '/dev/vfio/7'], 'wait_s': 0.0, 'num_cores': 4, 'psum': 20.0}
(raylet) A worker died or was killed while executing a task by an unexpected system error. To troubleshoot the problem, check the logs for the dead worker. Lease ID: 0f0000001e000000ffffffffffffffffffffffffffffffffffffffffffffffff Worker ID: 6c9452d4d131c0b50e26e8776db3b5d18f470a8694c8aef2df7d2210 Node ID: 265a5b8ca5501275fc4ccf259a852244f09da816aa45f5af8ccdf143 Worker IP address: 10.228.2.9 Worker port: 10240 Worker PID: 205712 Worker exit type: SYSTEM_ERROR Worker exit detail: Worker unexpectedly exits with a connection error code 2. End of file. Some common causes include: (1) the process was killed by the OOM killer due to high memory usage, (2) ray stop --force was called, or (3) the worker crashed unexpectedly due to SIGSEGV or another unexpected error. If the process was killed by the kernel OOM killer (verifiable by checking for OOM in dmesg of the OOMing node), consider enabling resource isolation via --enable-resource-isolation to prevent node deaths by resource contention and significant loss of progress by uninformed kernel OOM killing.
[Worker B Rapid Restart #1] wait_s=0.126s, total_recovery_s=3.867s, scoped_vfio=['/dev/vfio/2', '/dev/vfio/1', '/dev/vfio/6', '/dev/vfio/7'], cores=4, psum=20.0
[Worker B Rapid Restart #2] wait_s=0.169s, total_recovery_s=3.849s, scoped_vfio=['/dev/vfio/2', '/dev/vfio/1', '/dev/vfio/6', '/dev/vfio/7'], cores=4, psum=20.0
(raylet) A worker died or was killed while executing a task by an unexpected system error. To troubleshoot the problem, check the logs for the dead worker. Lease ID: 130000001e000000ffffffffffffffffffffffffffffffffffffffffffffffff Worker ID: c69052d5735ee88333d9fb13a4457dfb5db865de04f7836fa956aa79 Node ID: 265a5b8ca5501275fc4ccf259a852244f09da816aa45f5af8ccdf143 Worker IP address: 10.228.2.9 Worker port: 10237 Worker PID: 205715 Worker exit type: SYSTEM_ERROR Worker exit detail: Worker unexpectedly exits with a connection error code 2. End of file. Some common causes include: (1) the process was killed by the OOM killer due to high memory usage, (2) ray stop --force was called, or (3) the worker crashed unexpectedly due to SIGSEGV or another unexpected error. If the process was killed by the kernel OOM killer (verifiable by checking for OOM in dmesg of the OOMing node), consider enabling resource isolation via --enable-resource-isolation to prevent node deaths by resource contention and significant loss of progress by uninformed kernel OOM killing.�[32m [repeated 2x across cluster] (Ray deduplicates logs by default. Set RAY_DEDUP_LOGS=0 to disable log deduplication, or see https://docs.ray.io/en/master/ray-observability/user-guides/configure-logging.html#log-deduplication for more options.)�[0m
[Worker B Rapid Restart #3] wait_s=0.149s, total_recovery_s=3.934s, scoped_vfio=['/dev/vfio/2', '/dev/vfio/1', '/dev/vfio/6', '/dev/vfio/7'], cores=4, psum=20.0
[Worker A Uninterrupted Result] {'worker_a_iters': 240, 'errors': 0}
[Workload 2b Intra-Chip Dual-VF Isolation] {'chip2_vf0_held_busy': '/dev/vfio/2', 'chip2_vf1_probed': '/dev/vfio/1', 'wait_s': 0.0001}

============================================================================
WORKLOAD 3 [TREATMENT B (Patched)]: TorchTrainer (tpu_dist) 8-VF tpu7x Rapid Reuse & Fault Recovery
============================================================================
[Setup] Armed 4.8s SIGTERM-grace -> SIGKILL of prior 256-GiB TPU worker on ['/dev/vfio/2', '/dev/vfio/3', '/dev/vfio/4', '/dev/vfio/6'] upon 8x RayTrainWorker libtorch load
[Controller] InitializingState -> SchedulingState
[Controller] SchedulingState -> RunningState
[TorchWorker 0] tpu_dist initialized across world_size=8 tpu7x VFs
[TorchWorker 0] Step 1 committed (all_reduce_sum=20.895433)
[TorchWorker 3 (VF 3)] Ready for mid-step-2 SIGKILL injection
[Driver] Injecting ray.kill(torch_worker_3) mid-step 2...
[Controller] RunningState -> RestartingState | failure=The actor is dead because it was killed by `ray.kill`.
[Controller] RestartingState -> SchedulingState
[Controller] SchedulingState -> RunningState
[TorchWorker 0] Restored checkpoint at step=1
[TorchWorker 0] tpu_dist initialized across world_size=8 tpu7x VFs
[TorchWorker 0] Step 2 committed (all_reduce_sum=20.895433)
[TorchWorker 0] Step 3 committed (all_reduce_sum=20.895433)
[Controller] RunningState -> ShuttingDownState
[Controller] ShuttingDownState -> FinishedState
[Worker Log] TPU VFIO devices ['/dev/vfio/4'] became ready after 4.38s.
[Worker Log] TPU VFIO devices ['/dev/vfio/6'] became ready after 4.29s.
[Worker Log] TPU VFIO devices ['/dev/vfio/2'] became ready after 4.55s.
[Worker Log] TPU VFIO devices ['/dev/vfio/3'] became ready after 4.47s.
[Workload 3 treatment Summary] metrics={'step': 3, 'all_reduce_sum': 20.895433, 'world_size': 8}, controller_failures=1, ebusy_hits=0, vfio_ready_logs=4

ALL TREATMENT B LIVE TPU7X HARDWARE ASSERTIONS PASSED!
(raylet) A worker died or was killed while executing a task by an unexpected system error. To troubleshoot the problem, check the logs for the dead worker. Lease ID: 150000001e000000ffffffffffffffffffffffffffffffffffffffffffffffff Worker ID: ca021a094411c3efa8ca1be0e9441fab77f596066e3b6cb43d2e7c02 Node ID: 265a5b8ca5501275fc4ccf259a852244f09da816aa45f5af8ccdf143 Worker IP address: 10.228.2.9 Worker port: 10238 Worker PID: 205713 Worker exit type: SYSTEM_ERROR Worker exit detail: Worker unexpectedly exits with a connection error code 2. End of file. Some common causes include: (1) the process was killed by the OOM killer due to high memory usage, (2) ray stop --force was called, or (3) the worker crashed unexpectedly due to SIGSEGV or another unexpected error. If the process was killed by the kernel OOM killer (verifiable by checking for OOM in dmesg of the OOMing node), consider enabling resource isolation via --enable-resource-isolation to prevent node deaths by resource contention and significant loss of progress by uninformed kernel OOM killing.

2. master (--mode baseline)

2026-10-31 06:18:26,293	INFO worker.py:1683 -- Using address 127.0.0.1:6379 set in the environment variable RAY_ADDRESS
2026-10-31 06:18:26,296	INFO worker.py:1833 -- Connecting to existing Ray cluster at address: 10.228.3.117:6379...
2026-10-31 06:18:26,308	INFO worker.py:2015 -- Connected to Ray cluster. View the dashboard at �[1m�[32mhttp://10.228.3.117:8265 �[39m�[22m
============================================================================
BASELINE A (PART 0): Live tpu7x Kernel SIGKILL -> VFIO Unpinning Window
============================================================================
[Kernel Unpin Probe] {'device_kind': 'TPU7x', 'num_cores': 8, 'allocated_hbm_gib': 256, 'ebusy_probes': 27, 'released_after_sigkill_s': {'/dev/vfio/4': 2.074, '/dev/vfio/2': 2.16, '/dev/vfio/3': 2.244, '/dev/vfio/6': 2.393}}

============================================================================
WORKLOAD 1A [BASELINE A (Unpatched)]: @ray.remote 8-Core tpu7x Rapid Reuse During VFIO Teardown
============================================================================
[Setup] Warm replacement actor ready (pid=189401); prior 256-GiB TPU worker active on ['/dev/vfio/2', '/dev/vfio/3', '/dev/vfio/4', '/dev/vfio/6']
[Worker 2] Replacement CRASHED after 1.489s: RuntimeError: Unable to initialize backend 'tpu': FAILED_PRECONDITION: TPU initialization failed: open(/dev/vfio/4): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/4 (set JAX_PLATFORMS='' to automatically choose an available backend)

============================================================================
WORKLOAD 1B [BASELINE A (Unpatched)]: JaxTrainer 8-Core tpu7x Rapid Reuse & Fault Recovery
============================================================================
[Setup] Armed SIGKILL of prior 256-GiB TPU worker on ['/dev/vfio/2', '/dev/vfio/3', '/dev/vfio/4', '/dev/vfio/6'] upon RayTrainWorker jaxlib load
[Controller] InitializingState -> SchedulingState
[Controller] SchedulingState -> RunningState
[Controller] RunningState -> ShuttingDownState
[Controller] ShuttingDownState -> ErroredState | failure=RuntimeError: Unable to initialize backend 'tpu': FAILED_PRECONDITION: TPU initialization failed: open(/dev/vfio/2): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/2 (set JAX_PLATFORMS='' to automatically choose an available backend)
[Worker Log] jax.errors.JaxRuntimeError: FAILED_PRECONDITION: TPU initialization failed: open(/dev/vfio/2): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/2
[Worker Log] RuntimeError: Unable to initialize backend 'tpu': FAILED_PRECONDITION: TPU initialization failed: open(/dev/vfio/2): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/2 (set JAX_PLATFORMS='' to automatically choose an available backend)
[Workload 1B baseline Summary] metrics={'failed': "RuntimeError: Unable to initialize backend 'tpu': FAILED_PRECONDITION: TPU initialization failed: open(/dev/vfio/2): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/2 (set JAX_PLATFORMS='' to automatically choose an available backend)"}, controller_failures=1, ebusy_hits=3, vfio_ready_logs=0

============================================================================
WORKLOAD 3 [BASELINE A (Unpatched)]: TorchTrainer (tpu_dist) 8-VF tpu7x Rapid Reuse & Fault Recovery
============================================================================
[Setup] Armed 4.8s SIGTERM-grace -> SIGKILL of prior 256-GiB TPU worker on ['/dev/vfio/2', '/dev/vfio/3', '/dev/vfio/4', '/dev/vfio/6'] upon 8x RayTrainWorker libtorch load
[Controller] InitializingState -> SchedulingState
[Controller] SchedulingState -> ShuttingDownState
[Controller] ShuttingDownState -> ErroredState | failure=RuntimeError: [TorchTPU] Failed to acquire a TPU device node '/dev/vfio/3' because it is already opened by another process on this host.
[Workload 3 baseline Summary] metrics={'failed': "RuntimeError: [TorchTPU] Failed to acquire a TPU device node '/dev/vfio/3' because it is already opened by another process on this host."}, controller_failures=1, ebusy_hits=1, vfio_ready_logs=0

ALL BASELINE A UNPATCHED EBUSY REPRODUCTION ASSERTIONS CONFIRMED!

3. Multi-Slice JaxTrainer Unpatched EBUSY Logs (2 → 1 Recovery & 2 → 4 Scale-Up)

2 → 1 slice crash recovery without VFIO readiness polling (bench1_jax_1to2_unpatched_baseline.log, lines 6292, 7127, 7467–7470):

(pid=, ip=10.228.2.8) E1022 07:14:56.512453   23759 vfio_device_access.cc:240] FAILED_PRECONDITION: open(/dev/vfio/6): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/6
(pid=, ip=10.228.2.8) E1022 07:15:00.425049   23754 tpu_hal.cc:268] Failed to initialize TPU system with error: FAILED_PRECONDITION: open(/dev/vfio/6): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/6
(RayTrainWorker pid=23382, ip=10.228.2.8) jax.errors.JaxRuntimeError: FAILED_PRECONDITION: TPU initialization failed: open(/dev/vfio/6): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/6
(TrainController pid=4013) [FailurePolicy] RETRY
(TrainController pid=4013)   Source: worker group
(TrainController pid=4013)   Error count: 2 (max allowed: 3)

2 → 4 clean scale-up, 4 → 2 crash recovery, and 2 → 1 crash recovery with ray#67651 alone (arm1d_pr1_stress_trial1.log, lines 10891, 11082, 11227–11229, 14524, 14606, 17796, 17799, 17850, 17966–17968):

(pid=, ip=10.228.2.12) E1029 11:43:11.626355   10254 vfio_device_access.cc:240] FAILED_PRECONDITION: open(/dev/vfio/6): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/6
(pid=, ip=10.228.2.12) E1029 11:43:15.325789   10250 tpu_hal.cc:268] Failed to initialize TPU system with error: FAILED_PRECONDITION: open(/dev/vfio/6): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/6
(TrainController pid=1026) [FailurePolicy] RETRY
(TrainController pid=1026)   Source: worker group
(TrainController pid=1026)   Error count: 1 (max allowed: 6)
(pid=, ip=10.228.2.12) E1029 11:44:56.775415   15490 vfio_device_access.cc:240] FAILED_PRECONDITION: open(/dev/vfio/7): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/7
(pid=, ip=10.228.2.12) E1029 11:45:01.051920   15484 tpu_hal.cc:268] Failed to initialize TPU system with error: FAILED_PRECONDITION: open(/dev/vfio/7): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/7
(pid=, ip=10.228.2.12) E1029 11:46:35.775798   20575 vfio_device_access.cc:240] FAILED_PRECONDITION: open(/dev/vfio/6): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/6
(pid=, ip=10.228.2.12) E1029 11:46:35.775882   20577 vfio_device_access.cc:240] FAILED_PRECONDITION: open(/dev/vfio/7): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/7
(pid=, ip=10.228.2.12) E1029 11:46:38.757044   20571 tpu_hal.cc:268] Failed to initialize TPU system with error: FAILED_PRECONDITION: open(/dev/vfio/6): 16: Device or resource busy; Couldn't open iommu group /dev/vfio/6
(TrainController pid=1026) [FailurePolicy] RETRY
(TrainController pid=1026)   Source: worker group
(TrainController pid=1026)   Error count: 5 (max allowed: 6)

@ryanaoleary
ryanaoleary marked this pull request as ready for review November 4, 2026 02:59
@ryanaoleary
ryanaoleary requested review from a team, andrewsykim and edoakes as code owners November 4, 2026 02:59
@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!

@ray-gardener ray-gardener Bot added train Ray Train Related Issue community-contribution Contributed by the community labels Nov 4, 2026
@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 5, 2026
… device ID (#67575)

## Why are these changes needed?

When `use_tpu=True`, Ray Train previously sorted workers only by TPU
slice name via `TPU_NAME`. Because placement group bundles are not
ordered by host worker ID or device ID, workers within a slice received
ranks in arbitrary scheduling order:

```text
Before (sorted only by slice name):
  world_rank 0 -> slice-0, host 1 (TPU_WORKER_ID=1), device 5  (local_rank 0)
  world_rank 1 -> slice-0, host 0 (TPU_WORKER_ID=0), device 6  (local_rank 0)
  world_rank 2 -> slice-0, host 1 (TPU_WORKER_ID=1), device 2  (local_rank 1)
  ...

After (sorted by slice name, host worker ID, and lowest device ID):
  world_rank 0..7  -> slice-0, host 0 (TPU_WORKER_ID=0), devices 0..7  (local_rank 0..7)
  world_rank 8..15 -> slice-0, host 1 (TPU_WORKER_ID=1), devices 0..7  (local_rank 0..7)
```

This PR updates `WorkerGroup._sort_workers_by_tpu_pod_name` to fetch
each worker's slice name and integer `TPU_WORKER_ID` in a single
parallel call and sort TPU workers by `(pod_name, tpu_worker_id,
node_id, min_tpu_id)`:

- Grouping each host's workers into a contiguous `world_rank` block
keeps intra-node process groups on one TPU host and prevents TorchTPU
slice-builder port collisions.
- Ordering hosts within each slice by `TPU_WORKER_ID`, with `node_id` as
a tie-breaker when `TPU_WORKER_ID` is unset, pins `world_rank 0` to host
0 of slice 0 and aligns host rank blocks with KubeRay's
`TPU_WORKER_HOSTNAMES` and `TORCH_TPU_SLICEBUILDER_ADDRESSES`.
- Sorting workers on each host by their lowest assigned TPU ID maps
`local_rank 0..N-1` to ascending TPU devices, matching
`TPU_VISIBLE_CHIPS` and [Set `TPU_VISIBLE_DEVICES` alongside
`TPU_VISIBLE_CHIPS` for per-device MPMD
(ray#67029)](#67029).

## Related issue number

Contributes to [[Core][Train] Support Torch runtime with TPUs
(ray#64055)](#64055).
Related to [Set `TPU_VISIBLE_DEVICES` alongside `TPU_VISIBLE_CHIPS` for
per-device MPMD
(ray#67029)](#67029), [Order
subslice hosts by physical topology and pin slice bundles to worker IDs
(ray#66029)](#66029), and [Wait
for worker TPU VFIO devices before distributed init
(ray#67756)](#67756).

## 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.
- [x] 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_worker_group.py`, `test_jax_trainer.py`) 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

cc: @edoakes @andrewsykim @rueian for core review

@ryanaoleary
ryanaoleary merged commit 9145ea9 into ray-project:master Nov 9, 2026
7 checks passed
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.

3 participants