Skip to content

[Core][TPU] Preserve explicit TPU bounds and visible chip masks across worker tasks - #66400

Merged
rueian merged 3 commits into
ray-project:masterfrom
ryanaoleary:tpu-worker-bounds-fix
Sep 28, 2026
Merged

rueian merged 3 commits into
ray-project:masterfrom
ryanaoleary:tpu-worker-bounds-fix

Conversation

@ryanaoleary

@ryanaoleary ryanaoleary commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Description

Ray's TPU worker initialization currently overwrites explicit PJRT topology bounds and fails on per-worker chip masks, breaking both per-chip PyTorch/TorchTPU frameworks (such as verl) and per-host JAX/SPMD workloads:

  • In verl (PlatformTPU) and TorchTPU, each Ray actor is scheduled on a single TPU chip (TPU=1) with per-worker PJRT environment variables (TPU_CHIPS_PER_HOST_BOUNDS=1,1,1, TPU_HOST_BOUNDS set to the multi-worker topology, and TPU_VISIBLE_CHIPS set to the worker's local chip rank alongside RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1). During worker startup, Ray unconditionally overwrites TPU_HOST_BOUNDS to 1,1,1 for 1-chip allocations and raises an IndexError in get_accelerator_ids_for_accelerator_resource on non-zero local ranks because the worker's initial visible chip list has length 1 while the raylet assigns node-wide slot indices 0..N-1.
  • In multi-host and subslice JAX/SPMD workloads, each Ray actor allocates an entire TPU host (TPU=4) and relies on TPU_CHIPS_PER_HOST_BOUNDS and TPU_HOST_BOUNDS from the KubeRay TPU webhook or the job's runtime environment. During worker startup, Ray unconditionally deletes both variables whenever a worker allocates all TPUs on a node.

This PR fixes these initialization bugs so per-chip TorchTPU/verl collectives, full-host JAX/SPMD slices and subslices, and reused workers preserve their intended topology and device mappings:

Key Changes

  • Preserve existing TPU_CHIPS_PER_HOST_BOUNDS and TPU_HOST_BOUNDS on full-node TPU allocations instead of clearing them.
  • Preserve existing TPU_HOST_BOUNDS when TPU_CHIPS_PER_HOST_BOUNDS already matches the expected 1-chip or 2-chip sub-host configuration, defaulting TPU_HOST_BOUNDS to 1,1,1 only when unset or when Ray overrides chip bounds.
  • Clear stale 1-chip or 2-chip sub-host bounds when a worker process is reused for a CPU-only task or a larger TPU allocation (such as a 4-chip task).
  • Sort mapped physical chip IDs deterministically across all RAY_TPU_RESOURCE_PER_CHIP configurations.
  • Guard original_visible_accelerator_ids index lookups in worker.py when a worker's runtime environment narrows visible accelerator IDs below the node raylet's slot count.

Related issues

Testing

  • Ran unit and integration tests in python/ray/tests/accelerators/test_tpu.py (112 passed), covering full-node, subslice, sub-host, 1-chip collective, worker process reuse across 4- and 8-device nodes, and RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1 actor execution.
  • Manually verified on TPU v6e and TPU v7x GKE clusters across multi-host full-slice (4x4 and 2x2x4) and subslice (2x4 and 2x2x2) JAX collectives, 1-chip and 2-chip sub-host tasks with same-PID worker reuse, and 1-chip-per-worker verl / TorchTPU collectives.

@ryanaoleary

ryanaoleary commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Manual Testing Steps

Step 1: Deploy a multi-host TPU RayCluster (TPU v6e and TPU v7x)

apiVersion: ray.io/v1
kind: RayCluster
metadata:
  name: tpu-multi-host
spec:
  headGroupSpec:
    rayStartParams: {}
    template:
      spec:
        containers:
          - name: ray-head
            image: us-central2-docker.pkg.dev/tpu-vm-gke-testing/tpu-repo/ray-torchtpu-vllm:nightly
  workerGroupSpecs:
    - groupName: tpu-multihost-group
      replicas: 1
      numOfHosts: 4
      rayStartParams: {}
      template:
        spec:
          nodeSelector:
            cloud.google.com/gke-tpu-accelerator: tpu-v6e-slice
            cloud.google.com/gke-tpu-topology: 4x4
          containers:
            - name: ray-worker
              image: us-central2-docker.pkg.dev/tpu-vm-gke-testing/tpu-repo/ray-torchtpu-vllm:nightly
              resources:
                limits:
                  google.com/tpu: '4'
                requests:
                  google.com/tpu: '4'
    - groupName: v7x-multihost-group
      replicas: 1
      numOfHosts: 4
      rayStartParams: {}
      template:
        spec:
          nodeSelector:
            cloud.google.com/gke-tpu-accelerator: tpu7x
            cloud.google.com/gke-tpu-topology: 2x2x4
          containers:
            - name: ray-worker
              image: us-central2-docker.pkg.dev/tpu-vm-gke-testing/tpu-repo/ray-torchtpu-vllm:nightly
              resources:
                limits:
                  google.com/tpu: '4'
                requests:
                  google.com/tpu: '4'

Step 2: Apply PR Changes to Cluster Pods

for pod in $(kubectl get pods -l ray.io/cluster=tpu-multi-host -o jsonpath='{.items[*].metadata.name}'); do
  kubectl cp python/ray/_private/accelerators/tpu.py "$pod:/usr/local/lib/python3.12/site-packages/ray/_private/accelerators/tpu.py"
  kubectl cp python/ray/_private/worker.py "$pod:/usr/local/lib/python3.12/site-packages/ray/_private/worker.py"
done

Step 3: Run End-to-End Verification Script

Save the following script as run_pr2_manual_test.py:

import os
import ray

ray.init(address="auto", log_to_driver=False)


@ray.remote
def get_host_info():
    return {
        "ip": ray.util.get_node_ip_address(),
        "hostname": os.environ.get("HOSTNAME", ""),
        "worker_id": int(os.environ.get("TPU_WORKER_ID", "0")),
    }


nodes = [n for n in ray.nodes() if n["Alive"] and n["Resources"].get("TPU", 0) > 0]
pods = sorted(
    ray.get([get_host_info.options(resources={f"node:{n['NodeManagerAddress']}": 0.01}).remote() for n in nodes]),
    key=lambda x: x["worker_id"],
)


# 1 & 2. Full-host multi-host JAX collective (4x4 full slice & 2x4 subslice)
@ray.remote(resources={"TPU": 4}, num_cpus=1)
class HostWorker:
    def run_psum(self, coord_ip: str, port: int, num_procs: int):
        import jax
        import jax.numpy as jnp

        worker_id = int(os.environ["TPU_WORKER_ID"])
        jax.distributed.initialize(f"{coord_ip}:{port}", num_procs, worker_id)
        xs = jnp.arange(jax.local_device_count(), dtype=jnp.float32) + worker_id * 4 + 1
        psum = float(jax.device_get(jax.pmap(lambda x: jax.lax.psum(x, "i"), axis_name="i")(xs))[0])
        return {
            "worker_id": worker_id,
            "TPU_VISIBLE_CHIPS": os.environ.get("TPU_VISIBLE_CHIPS"),
            "TPU_CHIPS_PER_HOST_BOUNDS": os.environ.get("TPU_CHIPS_PER_HOST_BOUNDS"),
            "TPU_HOST_BOUNDS": os.environ.get("TPU_HOST_BOUNDS"),
            "total_devices": jax.device_count(),
            "psum": psum,
        }


print("=== 1. Full-Slice 4x4 JAX Collective (16 chips across 4 hosts) ===", flush=True)
c1 = [
    HostWorker.options(
        resources={"TPU": 4, f"node:{p['ip']}": 0.01},
        runtime_env={"env_vars": {"TPU_SKIP_MDS_QUERY": "true"}},
    ).remote()
    for p in pods
]
for r in ray.get([a.run_psum.remote(pods[0]["ip"], 8521, 4) for a in c1]):
    assert r["TPU_CHIPS_PER_HOST_BOUNDS"] == "2,2,1" and r["TPU_HOST_BOUNDS"] == "2,2,1", r
    assert r["total_devices"] == 16 and r["psum"] == 136.0, r
    print(" ", r, flush=True)
for a in c1:
    ray.kill(a)

print("\n=== 2. Subslice 2x4 JAX Collective (8 chips across 2 hosts) ===", flush=True)
sub_pods = [pods[1], pods[2]]
sub_ips = ",".join(p["ip"] for p in sub_pods)
sub_addrs = ",".join(f"{p['ip']}:8471" for p in sub_pods)
c2 = [
    HostWorker.options(
        resources={"TPU": 4, f"node:{p['ip']}": 0.01},
        runtime_env={
            "env_vars": {
                "TPU_SKIP_MDS_QUERY": "true",
                "TPU_CHIPS_PER_HOST_BOUNDS": "2,2,1",
                "TPU_HOST_BOUNDS": "1,2,1",
                "TPU_PROCESS_BOUNDS": "1,2,1",
                "TPU_TOPOLOGY": "2x4",
                "TPU_WORKER_ID": str(idx),
                "TPU_WORKER_HOSTNAMES": sub_ips,
                "MEGASCALE_COORDINATOR_ADDRESS": sub_pods[0]["ip"],
                "LIBTPU_INIT_ARGS": f"--deepsea_slice_builder_worker_addresses={sub_addrs} --deepsea_slice_builder_worker_port=8471",
            }
        },
    ).remote()
    for idx, p in enumerate(sub_pods)
]
for r in ray.get([a.run_psum.remote(sub_pods[0]["ip"], 8522, 2) for a in c2]):
    assert r["TPU_CHIPS_PER_HOST_BOUNDS"] == "2,2,1" and r["TPU_HOST_BOUNDS"] == "1,2,1", r
    assert r["total_devices"] == 8 and r["psum"] == 36.0, r
    print(" ", r, flush=True)
for a in c2:
    ray.kill(a)


# 3. Worker process reuse (TPU=1 task -> TPU=4 JAX pmap task on the same PID)
print("\n=== 3. Same-PID Worker Reuse (TPU=1 -> TPU=4 on same worker process) ===", flush=True)


@ray.remote(resources={"TPU": 1}, num_cpus=1)
def task_1chip():
    return {
        "pid": os.getpid(),
        "TPU_VISIBLE_CHIPS": os.environ.get("TPU_VISIBLE_CHIPS"),
        "TPU_CHIPS_PER_HOST_BOUNDS": os.environ.get("TPU_CHIPS_PER_HOST_BOUNDS"),
        "TPU_HOST_BOUNDS": os.environ.get("TPU_HOST_BOUNDS"),
    }


@ray.remote(resources={"TPU": 4}, num_cpus=1)
def task_4chip():
    import jax
    import jax.numpy as jnp

    xs = jnp.arange(4, dtype=jnp.float32) + 1.0
    psum = float(jax.device_get(jax.pmap(lambda x: jax.lax.psum(x, "i"), axis_name="i")(xs))[0])
    return {
        "pid": os.getpid(),
        "TPU_VISIBLE_CHIPS": os.environ.get("TPU_VISIBLE_CHIPS"),
        "TPU_CHIPS_PER_HOST_BOUNDS": os.environ.get("TPU_CHIPS_PER_HOST_BOUNDS"),
        "TPU_HOST_BOUNDS": os.environ.get("TPU_HOST_BOUNDS"),
        "local_devices": jax.local_device_count(),
        "psum": psum,
    }


reuse_env = {
    "env_vars": {
        "TPU_SKIP_MDS_QUERY": "true",
        "LIBTPU_INIT_ARGS": "--deepsea_chips_per_host_bounds=2,2,1 --deepsea_host_bounds=1,1,1",
    }
}
t1 = ray.get(task_1chip.options(resources={"TPU": 1, f"node:{pods[3]['ip']}": 0.01}, runtime_env=reuse_env).remote())
t2 = ray.get(task_4chip.options(resources={"TPU": 4, f"node:{pods[3]['ip']}": 0.01}, runtime_env=reuse_env).remote())
assert t1["pid"] == t2["pid"] and t1["TPU_CHIPS_PER_HOST_BOUNDS"] == "1,1,1", (t1, t2)
assert t2["TPU_CHIPS_PER_HOST_BOUNDS"] is None and t2["local_devices"] == 4 and t2["psum"] == 10.0, t2
print("  1-chip task:", t1, flush=True)
print("  4-chip task:", t2, flush=True)


# 4 & 5. 4-worker 1-chip-per-worker TorchTPU collectives (with and without NOSET=1)
@ray.remote(resources={"TPU": 1}, num_cpus=0.5)
class ChipWorker:
    def get_chip(self):
        return int(os.environ["TPU_VISIBLE_CHIPS"])

    def run_all_reduce(self, host_ip: str, base_port: int):
        import torch
        import torch.distributed as dist
        import torch_tpu  # noqa: F401

        rank = int(os.environ["TPU_VISIBLE_CHIPS"])
        addrs = ",".join(f"{host_ip}:{base_port + i}" for i in range(4))
        os.environ.update(
            {
                "LOCAL_RANK": str(rank),
                "RANK": str(rank),
                "WORLD_SIZE": "4",
                "LOCAL_WORLD_SIZE": "4",
                "TPU_PROCESS_PORT": str(base_port + rank),
                "TPU_PROCESS_ADDRESSES": addrs,
                "TORCH_TPU_SLICEBUILDER_ADDRESSES": addrs,
                "TORCH_TPU_TOPOLOGY": "2,2,1",
                "CHIPS_PER_HOST": "4",
                "CLOUD_TPU_TASK_ID": "0",
                "TPU_WORKER_ID": "0",
                "TPU_WORKER_HOSTNAMES": host_ip,
                "MASTER_ADDR": host_ip,
                "MASTER_PORT": str(base_port + 50),
            }
        )
        torch.tpu.set_device(0)
        dist.init_process_group(backend="tpu_dist", rank=rank, world_size=4)
        t = torch.tensor([float(rank + 1)], device="tpu:0")
        dist.all_reduce(t, op=dist.ReduceOp.SUM)
        all_reduce_sum = float(t.cpu().item())
        world_size = dist.get_world_size()
        dist.destroy_process_group()
        return {
            "world_size": world_size,
            "rank": rank,
            "accel_ids": ray.get_runtime_context().get_accelerator_ids()["TPU"],
            "TPU_VISIBLE_CHIPS": os.environ.get("TPU_VISIBLE_CHIPS"),
            "TPU_CHIPS_PER_HOST_BOUNDS": os.environ.get("TPU_CHIPS_PER_HOST_BOUNDS"),
            "TPU_HOST_BOUNDS": os.environ.get("TPU_HOST_BOUNDS"),
            "torch_tpu_device_count": torch.tpu.device_count(),
            "all_reduce_sum": all_reduce_sum,
        }


host_ip = pods[0]["ip"]
print("\n=== 4. verl 1-Chip-Per-Worker TorchTPU Collective (NOSET=1 + narrow TPU_VISIBLE_CHIPS) ===", flush=True)
c4 = [
    ChipWorker.options(
        resources={"TPU": 1, f"node:{host_ip}": 0.01},
        runtime_env={
            "env_vars": {
                "TPU_SKIP_MDS_QUERY": "true",
                "RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS": "1",
                "TPU_VISIBLE_CHIPS": str(i),
                "TPU_CHIPS_PER_HOST_BOUNDS": "1,1,1",
                "TPU_HOST_BOUNDS": "2,2,1",
            }
        },
    ).remote()
    for i in range(4)
]
for r in ray.get([a.run_all_reduce.remote(host_ip, 8600) for a in c4]):
    assert r["TPU_HOST_BOUNDS"] == "2,2,1" and r["torch_tpu_device_count"] == 1 and r["world_size"] == 4 and r["all_reduce_sum"] == 10.0, r
    print(" ", r, flush=True)
for a in c4:
    ray.kill(a)

print("\n=== 5. Ray-Managed 1-Chip-Per-Worker TorchTPU Collective (no NOSET=1) ===", flush=True)
c5 = [
    ChipWorker.options(
        resources={"TPU": 1, f"node:{host_ip}": 0.01},
        runtime_env={
            "env_vars": {
                "TPU_SKIP_MDS_QUERY": "true",
                "TPU_CHIPS_PER_HOST_BOUNDS": "1,1,1",
                "TPU_HOST_BOUNDS": "2,2,1",
            }
        },
    ).remote()
    for _ in range(4)
]
for r in sorted(ray.get([a.run_all_reduce.remote(host_ip, 8700) for a in c5]), key=lambda x: x["rank"]):
    assert r["TPU_HOST_BOUNDS"] == "2,2,1" and r["torch_tpu_device_count"] == 1 and r["world_size"] == 4 and r["all_reduce_sum"] == 10.0, r
    print(" ", r, flush=True)
for a in c5:
    ray.kill(a)

Copy the script to the head pod and execute:

kubectl cp run_pr2_manual_test.py tpu-multi-host-head-rxs48:/tmp/run_pr2_manual_test.py
kubectl exec tpu-multi-host-head-rxs48 -- python3 -u /tmp/run_pr2_manual_test.py

Step 4: Results

TPU v6e (4x4 slice and 2x4 subslice)

2026-09-23 05:13:43,820	INFO worker.py:1677 -- Using address 127.0.0.1:6379 set in the environment variable RAY_ADDRESS
2026-09-23 05:13:43,824	INFO worker.py:1819 -- Connecting to existing Ray cluster at address: 10.228.1.203:6379...
2026-09-23 05:13:43,837	INFO worker.py:2008 -- Connected to Ray cluster. View the dashboard at http://10.228.1.203:8265 
/usr/local/lib/python3.12/site-packages/ray/_private/worker.py:2056: FutureWarning: Tip: In future versions of Ray, Ray will no longer override accelerator visible devices env var if num_gpus=0 or num_gpus=None (default). To enable this behavior and turn off this error message, set RAY_ACCEL_ENV_VAR_OVERRIDE_ON_ZERO=0
  warnings.warn(
=== 1. Full-Slice 4x4 JAX Collective (16 chips across 4 hosts) ===
  {'worker_id': 0, 'TPU_VISIBLE_CHIPS': None, 'TPU_CHIPS_PER_HOST_BOUNDS': '2,2,1', 'TPU_HOST_BOUNDS': '2,2,1', 'total_devices': 16, 'psum': 136.0}
  {'worker_id': 1, 'TPU_VISIBLE_CHIPS': None, 'TPU_CHIPS_PER_HOST_BOUNDS': '2,2,1', 'TPU_HOST_BOUNDS': '2,2,1', 'total_devices': 16, 'psum': 136.0}
  {'worker_id': 2, 'TPU_VISIBLE_CHIPS': None, 'TPU_CHIPS_PER_HOST_BOUNDS': '2,2,1', 'TPU_HOST_BOUNDS': '2,2,1', 'total_devices': 16, 'psum': 136.0}
  {'worker_id': 3, 'TPU_VISIBLE_CHIPS': None, 'TPU_CHIPS_PER_HOST_BOUNDS': '2,2,1', 'TPU_HOST_BOUNDS': '2,2,1', 'total_devices': 16, 'psum': 136.0}

=== 2. Subslice 2x4 JAX Collective (8 chips across 2 hosts) ===
  {'worker_id': 0, 'TPU_VISIBLE_CHIPS': None, 'TPU_CHIPS_PER_HOST_BOUNDS': '2,2,1', 'TPU_HOST_BOUNDS': '1,2,1', 'total_devices': 8, 'psum': 36.0}
  {'worker_id': 1, 'TPU_VISIBLE_CHIPS': None, 'TPU_CHIPS_PER_HOST_BOUNDS': '2,2,1', 'TPU_HOST_BOUNDS': '1,2,1', 'total_devices': 8, 'psum': 36.0}

=== 3. Same-PID Worker Reuse (TPU=1 -> TPU=4 on same worker process) ===
  1-chip task: {'pid': 12378, 'TPU_VISIBLE_CHIPS': '0', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '1,1,1'}
  4-chip task: {'pid': 12378, 'TPU_VISIBLE_CHIPS': None, 'TPU_CHIPS_PER_HOST_BOUNDS': None, 'TPU_HOST_BOUNDS': None, 'local_devices': 4, 'psum': 10.0}

=== 4. verl 1-Chip-Per-Worker TorchTPU Collective (NOSET=1 + narrow TPU_VISIBLE_CHIPS) ===
  {'world_size': 4, 'rank': 0, 'accel_ids': ['0'], 'TPU_VISIBLE_CHIPS': '0', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '2,2,1', 'torch_tpu_device_count': 1, 'all_reduce_sum': 10.0}
  {'world_size': 4, 'rank': 1, 'accel_ids': ['1'], 'TPU_VISIBLE_CHIPS': '1', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '2,2,1', 'torch_tpu_device_count': 1, 'all_reduce_sum': 10.0}
  {'world_size': 4, 'rank': 2, 'accel_ids': ['2'], 'TPU_VISIBLE_CHIPS': '2', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '2,2,1', 'torch_tpu_device_count': 1, 'all_reduce_sum': 10.0}
  {'world_size': 4, 'rank': 3, 'accel_ids': ['3'], 'TPU_VISIBLE_CHIPS': '3', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '2,2,1', 'torch_tpu_device_count': 1, 'all_reduce_sum': 10.0}

=== 5. Ray-Managed 1-Chip-Per-Worker TorchTPU Collective (no NOSET=1) ===
  {'world_size': 4, 'rank': 0, 'accel_ids': ['0'], 'TPU_VISIBLE_CHIPS': '0', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '2,2,1', 'torch_tpu_device_count': 1, 'all_reduce_sum': 10.0}
  {'world_size': 4, 'rank': 1, 'accel_ids': ['1'], 'TPU_VISIBLE_CHIPS': '1', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '2,2,1', 'torch_tpu_device_count': 1, 'all_reduce_sum': 10.0}
  {'world_size': 4, 'rank': 2, 'accel_ids': ['2'], 'TPU_VISIBLE_CHIPS': '2', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '2,2,1', 'torch_tpu_device_count': 1, 'all_reduce_sum': 10.0}
  {'world_size': 4, 'rank': 3, 'accel_ids': ['3'], 'TPU_VISIBLE_CHIPS': '3', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '2,2,1', 'torch_tpu_device_count': 1, 'all_reduce_sum': 10.0}

TPU v7x (2x2x4 slice and 2x2x2 subslice)

=== CONFIG 1: Full-Host Webhook Bounds Preservation on v7x-32 (2x2x4) ===
  PASS Config 1 on v7x-32 (2x2x4): sample={'hostname': 'v7x-multihost-group-0-0', 'worker_id': 0, 'device_kind': 'TPU7x', 'accel_ids': ['0', '1', '2', '3'], 'TPU_VISIBLE_CHIPS': '0,1,2,3', 'TPU_CHIPS_PER_HOST_BOUNDS': '2,2,1', 'TPU_HOST_BOUNDS': '1,1,4', 'local_devs': 8, 'total_devs': 32, 'psum': 528.0}

=== CONFIG 2: Subslice Full-Host runtime_env Bounds on v7x 2x2x2 subslice ===
  PASS Config 2 on v7x 2x2x2 subslice: sample={'hostname': 'v7x-multihost-group-0-0', 'worker_id': 0, 'device_kind': 'TPU7x', 'accel_ids': ['0', '1', '2', '3'], 'TPU_VISIBLE_CHIPS': '0,1,2,3', 'TPU_CHIPS_PER_HOST_BOUNDS': '2,2,1', 'TPU_HOST_BOUNDS': '1,1,2', 'local_devs': 8, 'total_devs': 16, 'psum': 136.0}

=== CONFIG 3: 1-Chip & 2-Chip Sub-Host Tasks + Reuse Cleanup on v7x ===
  PASS Config 3 on v7x: 1-chip={'pid': 50737, 'accel_ids': ['0'], 'TPU_VISIBLE_CHIPS': '0', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '1,1,1', 'val': 14.0, 'after_4chip_reuse_chip_bounds': None, 'after_4chip_reuse_host_bounds': None}, 2-chip={'pid': 51682, 'accel_ids': ['0', '1'], 'TPU_VISIBLE_CHIPS': '0,1', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,2,1', 'TPU_HOST_BOUNDS': '1,1,1', 'val': 14.0, 'after_4chip_reuse_chip_bounds': None, 'after_4chip_reuse_host_bounds': None}

=== CONFIG 4: verl NOSET=1 + TPU_VISIBLE_CHIPS 4-Chip Collective on v7x (RAY_TPU_RESOURCE_PER_CHIP=2) ===
  PASS Config 4 on v7x (RAY_TPU_RESOURCE_PER_CHIP=2): all 4 chips verified, sample={'rank': 3, 'accel_ids': ['6'], 'TPU_VISIBLE_CHIPS': '3', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '2,2,1', 'torch_tpu_device_count': 8, 'val': 40.0}

=== CONFIG 5: Simplified 1-Chip Collective (Ray-managed TPU_VISIBLE_CHIPS) on v7x ===
  PASS Config 5 on v7x: distinct chips ['0', '1', '2', '3'] preserved host_bounds=2,2,4

@ryanaoleary

ryanaoleary commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor Author

context for this change is in the discussion here: verl-project/verl#7849 (comment), the motivation is to avoid downstream frameworks like verl needing custom workarounds (such as ray_local_rank_override or resetting TPU env vars) because Ray previously overwrote TPU_HOST_BOUNDS during worker initialization and failed when resolving visible accelerator IDs for per-worker TPU_VISIBLE_CHIPS masks

@ryanaoleary

Copy link
Copy Markdown
Contributor Author

cc: @andrewsykim for review, related to the veRL work

@ryanaoleary
ryanaoleary marked this pull request as ready for review September 23, 2026 06:04
@ryanaoleary
ryanaoleary requested review from a team, andrewsykim and edoakes as code owners September 23, 2026 06:04

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request refactors TPU environment variable handling to correctly map physical chips and logical devices, manage sub-host bounds, and prevent index errors in worker accelerator ID assignment when the original visible IDs are narrower than the assigned IDs. Feedback on the changes identifies an issue in the full-node allocation check within tpu.py, where comparing len(visible_tpu_chips) (logical devices) against the physical chip count will fail when RAY_TPU_RESOURCE_PER_CHIP > 1; using len(physical_chips) is suggested instead.

Comment thread python/ray/_private/accelerators/tpu.py Resolved
@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Sep 23, 2026
@rueian rueian self-assigned this Sep 24, 2026
@rueian

rueian commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Can we try not to modify the os.environ? We had a hard time with that, bumping into env races and crashes multiple times.

@ryanaoleary

ryanaoleary commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Can we try not to modify the os.environ? We had a hard time with that, bumping into env races and crashes multiple times.

we discussed this offline a bit but I think this PR is necessary because it helps avoid runtime os.environ mutations wherever possible (which we're already doing with set_current_process_visible_accelerator_ids

os.environ.pop(TPU_HOST_BOUNDS_ENV_VAR, None)
since at least this commit: 16da484).

  1. When TPU workloads (such as ray.util.tpu or verl) pass TPU_VISIBLE_CHIPS, TPU_CHIPS_PER_HOST_BOUNDS, TPU_HOST_BOUNDS, and RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS via runtime_env={"env_vars": ...}, the Raylet sets those variables at worker process spawn time before any threads start, and set_current_process_visible_accelerator_ids returns immediately without touching os.environ.
  • Currently on master, that path fails with IndexError in worker.py whenever the TPU_VISIBLE_CHIPS passed in a runtime_env had fewer entries than the node TPU resource pool. The fix here unblocks that path.
  1. For standalone @ray.remote(resources={"TPU": 1}) tasks dispatched to already-running pooled workers without runtime_env, libtpu.so only accepts chip visibility and sub-host bounds via environment variables (through AcceleratorManager.set_current_process_visible_accelerator_ids, similar to CUDA_VISIBLE_DEVICES). Currently we are unconditionally calling os.environ.pop(...) (unsetenv) on every full-node TPU task and unconditionally calling os.environ[...] = ... (setenv) even when the environment variables already matched the target values. This PR avoids popping explicit startup bounds on full-node tasks and guards os.environ writes so setenv is only called when a value actually changes.

@askhat-g who worked on the veRL issue confirmed this PR fixes the crash seen in 1.

Comment thread python/ray/_private/worker.py Resolved
@rueian
rueian enabled auto-merge (squash) September 26, 2026 00:08
@github-actions github-actions Bot added the go add ONLY when ready to merge, run all tests label Sep 26, 2026
Comment on lines +826 to +831
stale_subhost_bounds = len(physical_chips) not in (1, 2) and os.environ.get(
TPU_CHIPS_PER_HOST_BOUNDS_ENV_VAR
) in (
TPU_CHIPS_PER_HOST_BOUNDS_1_CHIP_CONFIG,
TPU_CHIPS_PER_HOST_BOUNDS_2_CHIP_CONFIG,
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can you remind me why we consider these a special case for stale subhost bounds?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The logic we're changing here was originally added for Ray workers running multiple tasks that used a different number of chips. For a 4-chip node, if we first ran a 1-chip task (which would require TPU_CHIPS_PER_HOST_BOUNDS="1,1,1", TPU_PROCESS_BOUNDS="1,1,1") - if we'd then run subsequent 4-chip tasks they'd fail because the sub-host bounds were still there. Previously to fix this the below logic was added to unconditionally pop those two env vars for full node allocations:

os.environ.pop(TPU_CHIPS_PER_HOST_BOUNDS_ENV_VAR, None)
os.environ.pop(TPU_HOST_BOUNDS_ENV_VAR, None)

This unconditional pop doesn't work well though for sub-slicing since we mask TPU_CHIPS_PER_HOST_BOUNDS and TPU_PROCESS_BOUNDS in the runtime_env to enable that, it also breaks 1 chip or 2 chip nodes (i.e. v6e-1) which are full node allocations but natively have "1,1,1" / "1,2,1" bounds.

This PR just refines the check so that we're only popping those env vars when they'd actually cause the task to fail, If we're running a full node allocation with >2 chips then the subhost bounds set can't be valid and we should use the defaults.

Comment on lines +1159 to +1162
if all(i < len(original_ids) for i in assigned_ids):
assigned_ids = {str(original_ids[i]) for i in assigned_ids}
else:
assigned_ids = {str(x) for x in original_ids}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

From automated review, let me know if you agree

Falling back to all of original_ids when i >= len(original_ids) returns the wrong number of devices whenever len(original_ids) > len(assigned_ids):

With RAY_TPU_RESOURCE_PER_CHIP=2 and TPU_VISIBLE_CHIPS=str(chip) on a resources={"TPU": 1} actor, original_ids has 2 logical device IDs ([2*chip, 2*chip+1]). Actors assigned raylet slots 0 or 1 get 1 device ID, while actors assigned slots >= 2 hit the else branch and get 2 device IDs.

@ryanaoleary ryanaoleary Sep 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I believe this is a false positive and the same issue identified here: #66400 (comment) but taking a deeper look to make sure

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

nevermind this isn't the same issue linked in the comment above, it's actually the one from this discussion: #66400 (comment) with the fix being to slice to 1 Id which I removed in this commit: ac495ef

The finding is valid when we try to do ray.get_runtime_context().get_accelerator_ids()["TPU"] and also:

  1. RAY_TPU_RESOURCE_PER_CHIP=2,
  2. The caller also manually passes a narrowed TPU_VISIBLE_CHIPS=str(chip) in the actor's runtime_env, and
  3. The actor requests resources={"TPU": 1}.

With those conditions, get_accelerator_ids()["TPU"] returns 1 logical ID on raylet slots 0, 1 and 2 logical IDs (both belonging to the same physical chip) on raylet slots >= 2. However there's no functional bug here because TPUAcceleratorManager collapses logical IDs back to physical chips: Whether get_accelerator_ids()["TPU"] returns [2 * chip] (1 logical ID from the if branch) or [2 * chip, 2 * chip + 1] (both logical IDs of that chip from the else branch), set_current_process_visible_accelerator_ids maps them by doing int(device_id) // resource_per_chip, which results in the same TPU_VISIBLE_CHIPS=str(chip), TPU_CHIPS_PER_HOST_BOUNDS="1,1,1" either way

I could add back in original_ids[: len(assigned_ids)] in a follow-up if there's a preference - no code paths would actually touch this logic but len(ray.get_runtime_context().get_accelerator_ids()["TPU"]) would technically be incorrect (2 instead of 1). cc: @rueian

@rueian
rueian merged commit f7c8216 into ray-project:master Sep 28, 2026
8 checks passed
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…s worker tasks (ray-project#66400)

## Description

Ray's TPU worker initialization currently overwrites explicit PJRT
topology bounds and fails on per-worker chip masks, breaking both
per-chip PyTorch/TorchTPU frameworks (such as verl) and per-host
JAX/SPMD workloads:

- In verl (`PlatformTPU`) and TorchTPU, each Ray actor is scheduled on a
single TPU chip (`TPU=1`) with per-worker PJRT environment variables
(`TPU_CHIPS_PER_HOST_BOUNDS=1,1,1`, `TPU_HOST_BOUNDS` set to the
multi-worker topology, and `TPU_VISIBLE_CHIPS` set to the worker's local
chip rank alongside `RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1`).
During worker startup, Ray unconditionally overwrites `TPU_HOST_BOUNDS`
to `1,1,1` for 1-chip allocations and raises an `IndexError` in
`get_accelerator_ids_for_accelerator_resource` on non-zero local ranks
because the worker's initial visible chip list has length 1 while the
raylet assigns node-wide slot indices `0..N-1`.
- In multi-host and subslice JAX/SPMD workloads, each Ray actor
allocates an entire TPU host (`TPU=4`) and relies on
`TPU_CHIPS_PER_HOST_BOUNDS` and `TPU_HOST_BOUNDS` from the KubeRay TPU
webhook or the job's runtime environment. During worker startup, Ray
unconditionally deletes both variables whenever a worker allocates all
TPUs on a node.

This PR fixes these initialization bugs so per-chip TorchTPU/verl
collectives, full-host JAX/SPMD slices and subslices, and reused workers
preserve their intended topology and device mappings:

### Key Changes
- Preserve existing `TPU_CHIPS_PER_HOST_BOUNDS` and `TPU_HOST_BOUNDS` on
full-node TPU allocations instead of clearing them.
- Preserve existing `TPU_HOST_BOUNDS` when `TPU_CHIPS_PER_HOST_BOUNDS`
already matches the expected 1-chip or 2-chip sub-host configuration,
defaulting `TPU_HOST_BOUNDS` to `1,1,1` only when unset or when Ray
overrides chip bounds.
- Clear stale 1-chip or 2-chip sub-host bounds when a worker process is
reused for a CPU-only task or a larger TPU allocation (such as a 4-chip
task).
- Sort mapped physical chip IDs deterministically across all
`RAY_TPU_RESOURCE_PER_CHIP` configurations.
- Guard `original_visible_accelerator_ids` index lookups in `worker.py`
when a worker's runtime environment narrows visible accelerator IDs
below the node raylet's slot count.

## Related issues

- ray-project#64055
- Related verl PRs:
  - verl-project/verl-hardware-plugin#18
  - verl-project/verl#7849

## Testing

- Ran unit and integration tests in
`python/ray/tests/accelerators/test_tpu.py` (112 passed), covering
full-node, subslice, sub-host, 1-chip collective, worker process reuse
across 4- and 8-device nodes, and
`RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1` actor execution.
- Manually verified on TPU v6e and TPU v7x GKE clusters across
multi-host full-slice (4x4 and 2x2x4) and subslice (2x4 and 2x2x2) JAX
collectives, 1-chip and 2-chip sub-host tasks with same-PID worker
reuse, and 1-chip-per-worker verl / TorchTPU collectives.

---------

Signed-off-by: Ryan O'Leary <[email protected]>
rueian pushed a commit that referenced this pull request Nov 5, 2026
…er-device MPMD (#67029)

## Description

`TPUAcceleratorManager.set_current_process_visible_accelerator_ids`
currently collapses assigned TPU IDs by `RAY_TPU_RESOURCE_PER_CHIP` and
exports only `TPU_VISIBLE_CHIPS`. While `TPU_VISIBLE_CHIPS` is the
physical chip mask used by JAX/PJRT (libtpu), PyTorch/TorchTPU and
downstream RL frameworks such as veRL read `TPU_VISIBLE_DEVICES` for
per-device MPMD worker binding and platform detection:

- On dual-device TPU chips (Ironwood TPU with
`RAY_TPU_RESOURCE_PER_CHIP=2`), Ray schedules one `TPU` resource per
logical device, but two 1-device actors scheduled on the same physical
chip (`device_ids` `"0"` and `"1"`) both receive `TPU_VISIBLE_CHIPS="0"`
and no `TPU_VISIBLE_DEVICES`.
- When multiple MPMD worker groups share a host, TorchTPU falls back to
`LOCAL_RANK` when `TPU_VISIBLE_DEVICES` is unset, causing workers in
different groups to contend for the same `/dev/vfio/<rank>` devices.
- Downstream frameworks such as veRL check `"TPU_NAME" in os.environ or
"TPU_VISIBLE_DEVICES" in os.environ` to detect TPU workers.

This PR updates
`TPUAcceleratorManager.set_current_process_visible_accelerator_ids` and
the worker task save/restore path:
- Export `TPU_VISIBLE_DEVICES` with the uncollapsed logical device IDs
assigned to the worker, while keeping `TPU_VISIBLE_CHIPS` set to the
collapsed physical chip indices.
- Clear `TPU_VISIBLE_DEVICES` alongside `TPU_VISIBLE_CHIPS` on full-node
allocations.
- Save and restore all environment variables modified by
`set_current_process_visible_accelerator_ids` in
`ray._private.utils.set_visible_accelerator_ids` so reused workers
restore `TPU_VISIBLE_DEVICES` and pre-set container
`TPU_CHIPS_PER_HOST_BOUNDS` / `TPU_HOST_BOUNDS` after normal tasks
finish.
- Respect `RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1` (suppressing both
`TPU_VISIBLE_CHIPS` and `TPU_VISIBLE_DEVICES`) so framework-managed TPU
environment variables remain untouched.

Because `libtpu` prioritizes non-empty `TPU_VISIBLE_CHIPS` over
`TPU_VISIBLE_DEVICES`, existing JAX sub-host and SPMD behavior is
unchanged.

## Related issues

- Contributes to #64055
- Related PRs:
  - #65723
  - #66400
  - verl-project/verl-hardware-plugin#18
  - verl-project/verl#7849

## Additional information

- Ran unit and integration tests in
`python/ray/tests/accelerators/test_tpu.py` (113 passed),
`python/ray/tests/test_tpu.py` (186 passed), and
`python/ray/train/tests/test_torch_device_manager.py`.
- Manually verified on GKE TPU v6e (`2x4`) and TPU v7x (`2x2x2`)
clusters across `RAY_TPU_RESOURCE_PER_CHIP=1` and `2`, colocated MPMD
worker groups with overlapping `LOCAL_RANK`s, multi-host
`torch.distributed` collectives,
`RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1`, and JAX
sub-host/multi-host SPMD workloads. Manual testing comment below.

---------

Signed-off-by: Ryan O'Leary <[email protected]>
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 core Issues that should be addressed in Ray Core go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants