Skip to content

[Core][TPU] Set TPU_VISIBLE_DEVICES alongside TPU_VISIBLE_CHIPS for per-device MPMD - #67029

Merged
rueian merged 8 commits into
ray-project:masterfrom
ryanaoleary:tpu-visible-devices
Nov 5, 2026
Merged

rueian merged 8 commits into
ray-project:masterfrom
ryanaoleary:tpu-visible-devices

Conversation

@ryanaoleary

@ryanaoleary ryanaoleary commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

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

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_RANKs, multi-host torch.distributed collectives, RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1, and JAX sub-host/multi-host SPMD workloads. Manual testing comment below.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

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

@ryanaoleary

ryanaoleary commented Oct 14, 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-train:2.58.0-clean
  workerGroupSpecs:
    - groupName: tpu-v6e-group
      replicas: 1
      numOfHosts: 2
      rayStartParams: {}
      template:
        spec:
          nodeSelector:
            cloud.google.com/gke-tpu-accelerator: tpu-v6e-slice
            cloud.google.com/gke-tpu-topology: 2x4
          containers:
            - name: ray-worker
              image: us-central2-docker.pkg.dev/tpu-vm-gke-testing/tpu-repo/ray-torchtpu-train:2.58.0-clean
              resources:
                limits:
                  google.com/tpu: '4'
                requests:
                  google.com/tpu: '4'
    - groupName: v7x-multihost-group
      replicas: 1
      numOfHosts: 2
      rayStartParams: {}
      template:
        spec:
          nodeSelector:
            cloud.google.com/gke-tpu-accelerator: tpu7x
            cloud.google.com/gke-tpu-topology: 2x2x2
          containers:
            - name: ray-worker
              image: us-central2-docker.pkg.dev/tpu-vm-gke-testing/tpu-repo/ray-torchtpu-train:2.58.0-clean
              env:
                - name: RAY_TPU_RESOURCE_PER_CHIP
                  value: '2'
              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:$(kubectl exec "$pod" -- python3 -c 'import ray._private.accelerators.tpu as m; print(m.__file__)')"
done

Step 3: Run End-to-End Verification Script

Save the following script as run_tpu_visible_devices_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"],
)
host0_ip = pods[0]["ip"]


# 1. Colocated MPMD worker groups on the same host with overlapping LOCAL_RANKs
@ray.remote(resources={"TPU": 1}, num_cpus=0.5)
class ColocatedGroupWorker:
    def run_group_all_reduce(self, group_name: str, local_rank: int, group_size: int, base_port: int, scale: float):
        import torch
        import torch.distributed as dist
        import torch_tpu  # noqa: F401

        os.environ.update(
            {
                "LOCAL_RANK": str(local_rank),
                "RANK": str(local_rank),
                "WORLD_SIZE": str(group_size),
                "LOCAL_WORLD_SIZE": str(group_size),
                "MASTER_ADDR": "127.0.0.1",
                "MASTER_PORT": str(base_port + 50),
            }
        )
        dist.init_process_group(backend="tpu_dist", rank=local_rank, world_size=group_size)
        t = torch.ones(4, device="tpu:0") * scale
        dist.all_reduce(t, op=dist.ReduceOp.SUM)
        res = t.cpu().tolist()
        dist.destroy_process_group()
        return {
            "group": group_name,
            "RANK": local_rank,
            "LOCAL_RANK": os.environ.get("LOCAL_RANK"),
            "TPU_VISIBLE_DEVICES": os.environ.get("TPU_VISIBLE_DEVICES"),
            "TPU_VISIBLE_CHIPS": os.environ.get("TPU_VISIBLE_CHIPS"),
            "all_reduce_sum": res,
        }


# 2. Multi-host TorchTPU tpu_dist collective across all logical devices
@ray.remote(resources={"TPU": 1}, num_cpus=0.5)
class MultiHostDistWorker:
    def get_info(self):
        return {
            "worker_id": int(os.environ.get("TPU_WORKER_ID", "0")),
            "dev_id": int(os.environ["TPU_VISIBLE_DEVICES"]),
            "ip": ray.util.get_node_ip_address(),
        }

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

        os.environ.update(
            {
                "LOCAL_RANK": "0",
                "RANK": str(rank),
                "WORLD_SIZE": str(world_size),
                "MASTER_ADDR": master_ip,
                "MASTER_PORT": str(base_port + 100),
            }
        )
        dist.init_process_group(backend="tpu_dist", rank=rank, world_size=world_size)
        t = torch.ones(4, device="tpu:0")
        dist.all_reduce(t, op=dist.ReduceOp.SUM)
        res = t.cpu().tolist()
        dist.destroy_process_group()
        return {
            "rank": rank,
            "worker_id": os.environ.get("TPU_WORKER_ID"),
            "LOCAL_RANK_set_to": os.environ.get("LOCAL_RANK"),
            "TPU_VISIBLE_DEVICES": os.environ.get("TPU_VISIBLE_DEVICES"),
            "TPU_VISIBLE_CHIPS": os.environ.get("TPU_VISIBLE_CHIPS"),
            "all_reduce_sum": res,
        }

Copy the script to the head pod and execute:

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

Step 4: Results

TPU v6e (2x4 slice, RAY_TPU_RESOURCE_PER_CHIP=1)

=== Test 1A: 4 Concurrent Single-Device torch_tpu MPMD Actors on Host 0 (WITHOUT LOCAL_RANK or RANK) ===
  MPMD Actor (no RANK/LOCAL_RANK) dev=0: {'pid': 35886, 'TPU_VISIBLE_DEVICES': '0', 'TPU_VISIBLE_CHIPS': '0', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '1,1,1', 'LOCAL_RANK': None, 'RANK': None, 'vfio_fds': ['/dev/vfio/0', '/dev/vfio/vfio', 'anon_inode:[vfio-device]'], 'matrix': [[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]}
  MPMD Actor (no RANK/LOCAL_RANK) dev=1: {'pid': 35887, 'TPU_VISIBLE_DEVICES': '1', 'TPU_VISIBLE_CHIPS': '1', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '1,1,1', 'LOCAL_RANK': None, 'RANK': None, 'vfio_fds': ['/dev/vfio/1', '/dev/vfio/vfio', 'anon_inode:[vfio-device]'], 'matrix': [[2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0]]}
  MPMD Actor (no RANK/LOCAL_RANK) dev=2: {'pid': 35888, 'TPU_VISIBLE_DEVICES': '2', 'TPU_VISIBLE_CHIPS': '2', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '1,1,1', 'LOCAL_RANK': None, 'RANK': None, 'vfio_fds': ['/dev/vfio/2', '/dev/vfio/vfio', 'anon_inode:[vfio-device]'], 'matrix': [[3.0, 3.0, 3.0, 3.0], [3.0, 3.0, 3.0, 3.0], [3.0, 3.0, 3.0, 3.0], [3.0, 3.0, 3.0, 3.0]]}
  MPMD Actor (no RANK/LOCAL_RANK) dev=3: {'pid': 35889, 'TPU_VISIBLE_DEVICES': '3', 'TPU_VISIBLE_CHIPS': '3', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '1,1,1', 'LOCAL_RANK': None, 'RANK': None, 'vfio_fds': ['/dev/vfio/3', '/dev/vfio/vfio', 'anon_inode:[vfio-device]'], 'matrix': [[4.0, 4.0, 4.0, 4.0], [4.0, 4.0, 4.0, 4.0], [4.0, 4.0, 4.0, 4.0], [4.0, 4.0, 4.0, 4.0]]}

=== Test 1B: Two Separate 2-Actor Groups on Same v6e Host Both Setting LOCAL_RANK='0','1' ===
  Group A (2-chip tpu_dist + LOCAL_RANK) result: {'mode': 'tpu_dist_world_size_2_with_LOCAL_RANK', 'group': 'GroupA', 'LOCAL_RANK': '0', 'RANK': '0', 'WORLD_SIZE': '2', 'TPU_VISIBLE_DEVICES': '0', 'TPU_VISIBLE_CHIPS': '0', 'c_TPU_VISIBLE_DEVICES': '0', 'c_TPU_VISIBLE_CHIPS': '0', 'vfio_fds': ['/dev/vfio/0', '/dev/vfio/vfio', 'anon_inode:[vfio-device]'], 'all_reduce_sum': 3.0}
  Group A (2-chip tpu_dist + LOCAL_RANK) result: {'mode': 'tpu_dist_world_size_2_with_LOCAL_RANK', 'group': 'GroupA', 'LOCAL_RANK': '1', 'RANK': '1', 'WORLD_SIZE': '2', 'TPU_VISIBLE_DEVICES': '1', 'TPU_VISIBLE_CHIPS': '1', 'c_TPU_VISIBLE_DEVICES': '1', 'c_TPU_VISIBLE_CHIPS': '1', 'vfio_fds': ['/dev/vfio/1', '/dev/vfio/vfio', 'anon_inode:[vfio-device]'], 'all_reduce_sum': 3.0}
  Group B (2-chip tpu_dist + LOCAL_RANK) result: {'mode': 'tpu_dist_world_size_2_with_LOCAL_RANK', 'group': 'GroupB', 'LOCAL_RANK': '0', 'RANK': '0', 'WORLD_SIZE': '2', 'TPU_VISIBLE_DEVICES': '2', 'TPU_VISIBLE_CHIPS': '2', 'c_TPU_VISIBLE_DEVICES': '2', 'c_TPU_VISIBLE_CHIPS': '2', 'vfio_fds': ['/dev/vfio/2', '/dev/vfio/vfio', 'anon_inode:[vfio-device]'], 'all_reduce_sum': 30.0}
  Group B (2-chip tpu_dist + LOCAL_RANK) result: {'mode': 'tpu_dist_world_size_2_with_LOCAL_RANK', 'group': 'GroupB', 'LOCAL_RANK': '1', 'RANK': '1', 'WORLD_SIZE': '2', 'TPU_VISIBLE_DEVICES': '3', 'TPU_VISIBLE_CHIPS': '3', 'c_TPU_VISIBLE_DEVICES': '3', 'c_TPU_VISIBLE_CHIPS': '3', 'vfio_fds': ['/dev/vfio/3', '/dev/vfio/vfio', 'anon_inode:[vfio-device]'], 'all_reduce_sum': 30.0}

=== Test 2: Multi-Host torch.distributed (backend='tpu_dist') Collective Across All 8 v6e Chips (2 Hosts x 4 Chips) ===
  Multi-Host tpu_dist rank=0: {'rank': 0, 'host_rank': 0, 'local_rank': 0, 'hostname': 'tpu-v6e-group-0-0', 'TPU_VISIBLE_DEVICES': '0', 'TPU_VISIBLE_CHIPS': '0', 'all_reduce_sum': 36.0}
  Multi-Host tpu_dist rank=1: {'rank': 1, 'host_rank': 0, 'local_rank': 1, 'hostname': 'tpu-v6e-group-0-0', 'TPU_VISIBLE_DEVICES': '1', 'TPU_VISIBLE_CHIPS': '1', 'all_reduce_sum': 36.0}
  Multi-Host tpu_dist rank=2: {'rank': 2, 'host_rank': 0, 'local_rank': 2, 'hostname': 'tpu-v6e-group-0-0', 'TPU_VISIBLE_DEVICES': '2', 'TPU_VISIBLE_CHIPS': '2', 'all_reduce_sum': 36.0}
  Multi-Host tpu_dist rank=3: {'rank': 3, 'host_rank': 0, 'local_rank': 3, 'hostname': 'tpu-v6e-group-0-0', 'TPU_VISIBLE_DEVICES': '3', 'TPU_VISIBLE_CHIPS': '3', 'all_reduce_sum': 36.0}
  Multi-Host tpu_dist rank=4: {'rank': 4, 'host_rank': 1, 'local_rank': 0, 'hostname': 'tpu-v6e-group-0-1', 'TPU_VISIBLE_DEVICES': '0', 'TPU_VISIBLE_CHIPS': '0', 'all_reduce_sum': 36.0}
  Multi-Host tpu_dist rank=5: {'rank': 5, 'host_rank': 1, 'local_rank': 1, 'hostname': 'tpu-v6e-group-0-1', 'TPU_VISIBLE_DEVICES': '1', 'TPU_VISIBLE_CHIPS': '1', 'all_reduce_sum': 36.0}
  Multi-Host tpu_dist rank=6: {'rank': 6, 'host_rank': 1, 'local_rank': 2, 'hostname': 'tpu-v6e-group-0-1', 'TPU_VISIBLE_DEVICES': '2', 'TPU_VISIBLE_CHIPS': '2', 'all_reduce_sum': 36.0}
  Multi-Host tpu_dist rank=7: {'rank': 7, 'host_rank': 1, 'local_rank': 3, 'hostname': 'tpu-v6e-group-0-1', 'TPU_VISIBLE_DEVICES': '3', 'TPU_VISIBLE_CHIPS': '3', 'all_reduce_sum': 36.0}

=== Test 3: JAX Sub-Host (TPU:1, TPU:2), Worker Reuse to Full-Host (TPU:4), and Multi-Host (TPU:4 x 2) SPMD ===
  JAX TPU:1 sub-host result: {'pid': 48284, 'TPU_VISIBLE_DEVICES': '2', 'TPU_VISIBLE_CHIPS': '2', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '1,1,1', 'local_device_count': 1, 'device_count': 1, 'result': [112.0]}
  JAX TPU:2 sub-host result: {'pid': 48529, 'TPU_VISIBLE_DEVICES': '2,3', 'TPU_VISIBLE_CHIPS': '2,3', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,2,1', 'TPU_HOST_BOUNDS': '1,1,1', 'local_device_count': 2, 'device_count': 2, 'result': [21, 21]}
  Before worker reuse (TPU:1 task): {'pid': 50154, 'TPU_VISIBLE_DEVICES': '0', 'TPU_VISIBLE_CHIPS': '0', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '1,1,1'}
  After worker reuse (TPU:4 full-host JAX task, same_pid=True): {'pid': 50154, 'accel_ids': ['0', '1', '2', '3'], 'TPU_VISIBLE_DEVICES': None, 'TPU_VISIBLE_CHIPS': None, 'TPU_CHIPS_PER_HOST_BOUNDS': None, 'TPU_HOST_BOUNDS': None, 'local_device_count': 4, 'device_count': 4, 'psum': [46, 46, 46, 46]}
  Multi-Host JAX (TPU:4 x 2) proc_id=0: {'proc_id': 0, 'TPU_VISIBLE_DEVICES': None, 'TPU_VISIBLE_CHIPS': None, 'TPU_CHIPS_PER_HOST_BOUNDS': '2,2,1', 'TPU_HOST_BOUNDS': '1,2,1', 'local_device_count': 4, 'device_count': 8, 'psum': [36, 36, 36, 36]}
  Multi-Host JAX (TPU:4 x 2) proc_id=1: {'proc_id': 1, 'TPU_VISIBLE_DEVICES': None, 'TPU_VISIBLE_CHIPS': None, 'TPU_CHIPS_PER_HOST_BOUNDS': '2,2,1', 'TPU_HOST_BOUNDS': '1,2,1', 'local_device_count': 4, 'device_count': 8, 'psum': [36, 36, 36, 36]}

TPU v7x (2x2x2 slice, RAY_TPU_RESOURCE_PER_CHIP=2 and 1)

--- Test A.3 (4-worker tpu_dist all_reduce in GroupA and GroupB concurrently on worker 0 with overlapping LOCAL_RANK=0..3, RAY_TPU_RESOURCE_PER_CHIP=2) ---
  {'group': 'GroupA', 'RANK': 0, 'LOCAL_RANK': '0', 'TPU_VISIBLE_DEVICES': '0', 'TPU_VISIBLE_CHIPS': '0', 'all_reduce_sum': [4.0, 4.0, 4.0, 4.0]}
  {'group': 'GroupA', 'RANK': 1, 'LOCAL_RANK': '1', 'TPU_VISIBLE_DEVICES': '1', 'TPU_VISIBLE_CHIPS': '0', 'all_reduce_sum': [4.0, 4.0, 4.0, 4.0]}
  {'group': 'GroupA', 'RANK': 2, 'LOCAL_RANK': '2', 'TPU_VISIBLE_DEVICES': '2', 'TPU_VISIBLE_CHIPS': '1', 'all_reduce_sum': [4.0, 4.0, 4.0, 4.0]}
  {'group': 'GroupA', 'RANK': 3, 'LOCAL_RANK': '3', 'TPU_VISIBLE_DEVICES': '3', 'TPU_VISIBLE_CHIPS': '1', 'all_reduce_sum': [4.0, 4.0, 4.0, 4.0]}
  {'group': 'GroupB', 'RANK': 0, 'LOCAL_RANK': '0', 'TPU_VISIBLE_DEVICES': '4', 'TPU_VISIBLE_CHIPS': '2', 'all_reduce_sum': [40.0, 40.0, 40.0, 40.0]}
  {'group': 'GroupB', 'RANK': 1, 'LOCAL_RANK': '1', 'TPU_VISIBLE_DEVICES': '5', 'TPU_VISIBLE_CHIPS': '2', 'all_reduce_sum': [40.0, 40.0, 40.0, 40.0]}
  {'group': 'GroupB', 'RANK': 2, 'LOCAL_RANK': '2', 'TPU_VISIBLE_DEVICES': '6', 'TPU_VISIBLE_CHIPS': '3', 'all_reduce_sum': [40.0, 40.0, 40.0, 40.0]}
  {'group': 'GroupB', 'RANK': 3, 'LOCAL_RANK': '3', 'TPU_VISIBLE_DEVICES': '7', 'TPU_VISIBLE_CHIPS': '3', 'all_reduce_sum': [40.0, 40.0, 40.0, 40.0]}

--- Test A.4: 16-worker multi-host torch.distributed (tpu_dist) all_reduce across 2x2x2 (RAY_TPU_RESOURCE_PER_CHIP=2) ---
  {'rank': 0, 'worker_id': '0', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '0', 'TPU_VISIBLE_CHIPS': '0', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 1, 'worker_id': '0', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '1', 'TPU_VISIBLE_CHIPS': '0', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 2, 'worker_id': '0', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '2', 'TPU_VISIBLE_CHIPS': '1', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 3, 'worker_id': '0', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '3', 'TPU_VISIBLE_CHIPS': '1', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 4, 'worker_id': '0', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '4', 'TPU_VISIBLE_CHIPS': '2', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 5, 'worker_id': '0', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '5', 'TPU_VISIBLE_CHIPS': '2', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 6, 'worker_id': '0', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '6', 'TPU_VISIBLE_CHIPS': '3', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 7, 'worker_id': '0', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '7', 'TPU_VISIBLE_CHIPS': '3', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 8, 'worker_id': '1', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '0', 'TPU_VISIBLE_CHIPS': '0', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 9, 'worker_id': '1', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '1', 'TPU_VISIBLE_CHIPS': '0', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 10, 'worker_id': '1', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '2', 'TPU_VISIBLE_CHIPS': '1', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 11, 'worker_id': '1', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '3', 'TPU_VISIBLE_CHIPS': '1', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 12, 'worker_id': '1', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '4', 'TPU_VISIBLE_CHIPS': '2', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 13, 'worker_id': '1', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '5', 'TPU_VISIBLE_CHIPS': '2', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 14, 'worker_id': '1', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '6', 'TPU_VISIBLE_CHIPS': '3', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}
  {'rank': 15, 'worker_id': '1', 'LOCAL_RANK_set_to': '0', 'TPU_VISIBLE_DEVICES': '7', 'TPU_VISIBLE_CHIPS': '3', 'all_reduce_sum': [16.0, 16.0, 16.0, 16.0]}

--- Test B.2 & B.3: Default RAY_TPU_RESOURCE_PER_CHIP=1 Legacy JAX Sub-Host (TPU:1, TPU:2) & Multi-Host SPMD (2x2x2) ---
  {'TPU_VISIBLE_CHIPS': '0', 'TPU_VISIBLE_DEVICES': '0', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,1,1', 'TPU_HOST_BOUNDS': '1,1,1', 'jax_local_device_count': 2, 'jax_device_count': 2, 'pmap_sum': [[2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0]]}
  {'TPU_VISIBLE_CHIPS': '0,1', 'TPU_VISIBLE_DEVICES': '0,1', 'TPU_CHIPS_PER_HOST_BOUNDS': '1,2,1', 'TPU_HOST_BOUNDS': '1,1,1', 'jax_local_device_count': 4, 'jax_device_count': 4, 'pmap_sum_0': [4.0, 4.0, 4.0, 4.0]}
  {'worker_id': '0', 'assigned_ids': ['0', '1', '2', '3'], 'TPU_VISIBLE_CHIPS': '0,1,2,3', 'TPU_VISIBLE_DEVICES': '0,1,2,3', 'TPU_CHIPS_PER_HOST_BOUNDS': '2,2,1', 'TPU_HOST_BOUNDS': '1,1,2', 'jax_local_device_count': 8, 'jax_device_count': 16, 'pmap_psum': [16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0]}
  {'worker_id': '1', 'assigned_ids': ['0', '1', '2', '3'], 'TPU_VISIBLE_CHIPS': '0,1,2,3', 'TPU_VISIBLE_DEVICES': '0,1,2,3', 'TPU_CHIPS_PER_HOST_BOUNDS': '2,2,1', 'TPU_HOST_BOUNDS': '1,1,2', 'jax_local_device_count': 8, 'jax_device_count': 16, 'pmap_psum': [16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0]}

@ryanaoleary
ryanaoleary marked this pull request as ready for review October 14, 2026 21:49
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

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

@ryanaoleary

Copy link
Copy Markdown
Contributor Author

cc: @rueian @andrewsykim related to the previous change for TPU_VISIBLE_CHIPS and is part of the veRL integration

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Fix All in Cursor

Reviewed by Cursor Bugbot for commit d35d72f. Configure here.

Comment thread python/ray/_private/accelerators/tpu.py Resolved
@ryanaoleary
ryanaoleary requested a review from a team as a code owner October 15, 2026 00:11
@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Oct 15, 2026
@rueian rueian self-assigned this Oct 23, 2026
@rueian rueian added the go add ONLY when ready to merge, run all tests label Oct 23, 2026
@ryanaoleary
ryanaoleary enabled auto-merge (squash) October 23, 2026 22:17
@github-actions
github-actions Bot disabled auto-merge October 23, 2026 23:50
@ryanaoleary
ryanaoleary enabled auto-merge (squash) October 27, 2026 01:42
@rueian
rueian disabled auto-merge October 28, 2026 17:15
@rueian
rueian enabled auto-merge (squash) October 28, 2026 17:15
@rueian

rueian commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

cc @edoakes to merge 🙏

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]>
@rueian
rueian merged commit 9c1c295 into ray-project:master Nov 5, 2026
8 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 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