Repository navigation
[Core][TPU] Set TPU_VISIBLE_DEVICES alongside TPU_VISIBLE_CHIPS for per-device MPMD - #67029
Merged
Merged
Conversation
…er-device MPMD Signed-off-by: Ryan O'Leary <[email protected]>
Contributor
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
Contributor
Author
Manual Testing StepsStep 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 Podsfor 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__)')"
doneStep 3: Run End-to-End Verification ScriptSave the following script as 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.pyStep 4: ResultsTPU v6e (
|
ryanaoleary
marked this pull request as ready for review
October 14, 2026 21:49
Contributor
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
Contributor
Author
|
cc: @rueian @andrewsykim related to the previous change for TPU_VISIBLE_CHIPS and is part of the veRL integration |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit d35d72f. Configure here.
…n docstring Signed-off-by: Ryan O'Leary <[email protected]>
ryanaoleary
force-pushed
the
tpu-visible-devices
branch
from
October 15, 2026 01:53
57983d9 to
93b6795
Compare
rueian
approved these changes
Oct 23, 2026
rueian
approved these changes
Oct 23, 2026
ryanaoleary
enabled auto-merge (squash)
October 23, 2026 22:17
ryanaoleary
enabled auto-merge (squash)
October 27, 2026 01:42
rueian
disabled auto-merge
October 28, 2026 17:15
rueian
enabled auto-merge (squash)
October 28, 2026 17:15
Contributor
|
cc @edoakes to merge 🙏 |
This was referenced Oct 30, 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]>
andrewsykim
approved these changes
Nov 5, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Description
TPUAcceleratorManager.set_current_process_visible_accelerator_idscurrently collapses assigned TPU IDs byRAY_TPU_RESOURCE_PER_CHIPand exports onlyTPU_VISIBLE_CHIPS. WhileTPU_VISIBLE_CHIPSis the physical chip mask used by JAX/PJRT (libtpu), PyTorch/TorchTPU and downstream RL frameworks such as veRL readTPU_VISIBLE_DEVICESfor per-device MPMD worker binding and platform detection:RAY_TPU_RESOURCE_PER_CHIP=2), Ray schedules oneTPUresource per logical device, but two 1-device actors scheduled on the same physical chip (device_ids"0"and"1") both receiveTPU_VISIBLE_CHIPS="0"and noTPU_VISIBLE_DEVICES.LOCAL_RANKwhenTPU_VISIBLE_DEVICESis unset, causing workers in different groups to contend for the same/dev/vfio/<rank>devices."TPU_NAME" in os.environ or "TPU_VISIBLE_DEVICES" in os.environto detect TPU workers.This PR updates
TPUAcceleratorManager.set_current_process_visible_accelerator_idsand the worker task save/restore path:TPU_VISIBLE_DEVICESwith the uncollapsed logical device IDs assigned to the worker, while keepingTPU_VISIBLE_CHIPSset to the collapsed physical chip indices.TPU_VISIBLE_DEVICESalongsideTPU_VISIBLE_CHIPSon full-node allocations.set_current_process_visible_accelerator_idsinray._private.utils.set_visible_accelerator_idsso reused workers restoreTPU_VISIBLE_DEVICESand pre-set containerTPU_CHIPS_PER_HOST_BOUNDS/TPU_HOST_BOUNDSafter normal tasks finish.RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1(suppressing bothTPU_VISIBLE_CHIPSandTPU_VISIBLE_DEVICES) so framework-managed TPU environment variables remain untouched.Because
libtpuprioritizes non-emptyTPU_VISIBLE_CHIPSoverTPU_VISIBLE_DEVICES, existing JAX sub-host and SPMD behavior is unchanged.Related issues
Additional information
python/ray/tests/accelerators/test_tpu.py(113 passed),python/ray/tests/test_tpu.py(186 passed), andpython/ray/train/tests/test_torch_device_manager.py.2x4) and TPU v7x (2x2x2) clusters acrossRAY_TPU_RESOURCE_PER_CHIP=1and2, colocated MPMD worker groups with overlappingLOCAL_RANKs, multi-hosttorch.distributedcollectives,RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1, and JAX sub-host/multi-host SPMD workloads. Manual testing comment below.