Repository navigation
[Core][TPU] Preserve explicit TPU bounds and visible chip masks across worker tasks - #66400
Conversation
…s worker tasks Signed-off-by: Ryan O'Leary <[email protected]>
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-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 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:/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"
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"],
)
# 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.pyStep 4: ResultsTPU v6e (
|
|
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 |
|
cc: @andrewsykim for review, related to the veRL work |
There was a problem hiding this comment.
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.
|
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 ray/python/ray/_private/accelerators/tpu.py Line 827 in f5bc8f6
@askhat-g who worked on the veRL issue confirmed this PR fixes the crash seen in 1. |
…visible_accelerator_ids Signed-off-by: Ryan O'Leary <[email protected]>
…nal_ids) Signed-off-by: Ryan O'Leary <[email protected]>
| 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, | ||
| ) |
There was a problem hiding this comment.
Can you remind me why we consider these a special case for stale subhost bounds?
There was a problem hiding this comment.
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.
| 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} |
There was a problem hiding this comment.
From automated review, let me know if you agree
Falling back to all of
original_idswheni >= len(original_ids)returns the wrong number of devices wheneverlen(original_ids) > len(assigned_ids):
With
RAY_TPU_RESOURCE_PER_CHIP=2andTPU_VISIBLE_CHIPS=str(chip)on aresources={"TPU": 1}actor,original_idshas 2 logical device IDs ([2*chip, 2*chip+1]). Actors assigned raylet slots0or1get 1 device ID, while actors assigned slots>= 2hit theelsebranch and get 2 device IDs.
There was a problem hiding this comment.
I believe this is a false positive and the same issue identified here: #66400 (comment) but taking a deeper look to make sure
There was a problem hiding this comment.
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:
- RAY_TPU_RESOURCE_PER_CHIP=2,
- The caller also manually passes a narrowed
TPU_VISIBLE_CHIPS=str(chip)in the actor's runtime_env, and - 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
…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]>
…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]>
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:
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_BOUNDSset to the multi-worker topology, andTPU_VISIBLE_CHIPSset to the worker's local chip rank alongsideRAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1). During worker startup, Ray unconditionally overwritesTPU_HOST_BOUNDSto1,1,1for 1-chip allocations and raises anIndexErroringet_accelerator_ids_for_accelerator_resourceon non-zero local ranks because the worker's initial visible chip list has length 1 while the raylet assigns node-wide slot indices0..N-1.TPU=4) and relies onTPU_CHIPS_PER_HOST_BOUNDSandTPU_HOST_BOUNDSfrom 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
TPU_CHIPS_PER_HOST_BOUNDSandTPU_HOST_BOUNDSon full-node TPU allocations instead of clearing them.TPU_HOST_BOUNDSwhenTPU_CHIPS_PER_HOST_BOUNDSalready matches the expected 1-chip or 2-chip sub-host configuration, defaultingTPU_HOST_BOUNDSto1,1,1only when unset or when Ray overrides chip bounds.RAY_TPU_RESOURCE_PER_CHIPconfigurations.original_visible_accelerator_idsindex lookups inworker.pywhen a worker's runtime environment narrows visible accelerator IDs below the node raylet's slot count.Related issues
Testing
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, andRAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1actor execution.