Repository navigation
[Core][TPU] Order subslice hosts by physical topology and pin slice bundles to worker IDs - #66029
Conversation
Manual TestingStep 1: Deploy a multi-host RayClusterapiVersion: ray.io/v1
kind: RayCluster
metadata:
name: ray-tpu-v6e-cluster
spec:
headGroupSpec:
rayStartParams: {}
template:
spec:
containers:
- name: ray-head
image: us-central2-docker.pkg.dev/tpu-vm-gke-testing/tpu-repo/ray-torch-tpu:2.55.0-v6
imagePullPolicy: IfNotPresent
resources:
limits:
cpu: "4"
memory: 16Gi
requests:
cpu: "2"
memory: 8Gi
workerGroupSpecs:
- groupName: tpu-multihost-group
replicas: 1
minReplicas: 1
maxReplicas: 1
numOfHosts: 4
template:
spec:
nodeSelector:
cloud.google.com/gke-tpu-accelerator: tpu-v6e-slice
cloud.google.com/gke-tpu-topology: 4x4
tolerations:
- key: google.com/tpu
operator: Exists
effect: NoSchedule
containers:
- name: ray-worker
image: us-central2-docker.pkg.dev/tpu-vm-gke-testing/tpu-repo/ray-torch-tpu:2.55.0-v6
imagePullPolicy: IfNotPresent
resources:
limits:
google.com/tpu: "4"
requests:
google.com/tpu: "4"Deploy the cluster: kubectl apply -f v6e_cluster.yamlStep 2: Patch in local changes from this PR to running RayCluster podsCLUSTER_NAME="ray-tpu-v6e-cluster"
PODS=($(kubectl get pods -l ray.io/cluster=$CLUSTER_NAME,ray.io/group=tpu-multihost-group -o jsonpath='{.items[*].metadata.name}'))
HEAD_POD=$(kubectl get pods -l ray.io/cluster=$CLUSTER_NAME,ray.io/node-type=head -o jsonpath='{.items[0].metadata.name}')
# Patch head pod
kubectl cp python/ray/util/tpu.py $HEAD_POD:/usr/local/lib/python3.12/site-packages/ray/util/tpu.py -c ray-head
kubectl cp python/ray/_private/accelerators/tpu.py $HEAD_POD:/usr/local/lib/python3.12/site-packages/ray/_private/accelerators/tpu.py -c ray-head
# Patch worker pods
for POD in "${PODS[@]}"; do
kubectl cp python/ray/util/tpu.py $POD:/usr/local/lib/python3.12/site-packages/ray/util/tpu.py -c ray-worker
kubectl cp python/ray/_private/accelerators/tpu.py $POD:/usr/local/lib/python3.12/site-packages/ray/_private/accelerators/tpu.py -c ray-worker
doneStep 3: Run VerificationMulti-host SlicePlacementGroup, physical coordinate discovery, and
|
e359e8b to
366b0de
Compare
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
366b0de to
3808b92
Compare
|
cc: @spencer-p this PR should be ready for review I've been considering whether it's worth adding this hardware discovery to Ray, or delegating it to downstream frameworks at runtime or attempting to refactor the GKE scheduling side so that Pods created have the |
spencer-p
left a comment
There was a problem hiding this comment.
Looks good, some details are not clear but I am guessing there are simple explanations we can leave in comments
|
@spencer-p pushed the changes we talked about offline, I think this PR should be in its final state @andrewsykim @rueian this PR needs core or codeowner review if you have bandwidth |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 7aedfe6. Configure here.
|
cc: @spencer-p simplified this PR significantly based on our discussions offline, primarily in this commit: dead499 This PR still orders bundles by worker ID, adds a |
Manual testing (re-ran after refactor)Verified on GKE TPU clusters across four configurations:
1. Multi-host v6e 4x4 (JAX subslices and full slice)RayCluster: apiVersion: ray.io/v1
kind: RayCluster
metadata:
name: ray-v6e-4x4
spec:
headGroupSpec:
rayStartParams: {}
template:
spec:
containers:
- name: ray-head
image: <Ray image with JAX and libtpu>
workerGroupSpecs:
- groupName: v6e-worker-group
replicas: 1
numOfHosts: 4
rayStartParams: {}
template:
spec:
containers:
- name: ray-worker
image: <Ray image with JAX and libtpu>
resources:
limits:
google.com/tpu: "4"
nodeSelector:
cloud.google.com/gke-tpu-accelerator: tpu-v6e-slice
cloud.google.com/gke-tpu-topology: 4x4Test script ( import os
import jax
import jax.numpy as jnp
import ray
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
from ray.util.tpu import slice_placement_group, subslice_placement_group
ray.init(log_to_driver=False)
@ray.remote(num_cpus=1, resources={"TPU": 4}, max_calls=1)
def run_jax_psum(env_vars: dict) -> dict:
gke_worker_id = os.environ.get("TPU_WORKER_ID")
os.environ.update(env_vars)
psum_fn = jax.pmap(lambda x: jax.lax.psum(x, "i"), axis_name="i")
total = float(psum_fn(jnp.ones(jax.local_device_count())).addressable_data(0).item())
coords = sorted(tuple(d.coords) for d in jax.local_devices())
return {
"gke_worker_id": gke_worker_id,
"jax_worker_id": os.environ["TPU_WORKER_ID"],
"process_bounds": os.environ.get("TPU_PROCESS_BOUNDS"),
"chip_bounds": os.environ.get("TPU_CHIPS_PER_PROCESS_BOUNDS"),
"devices": jax.device_count(),
"coords": f"{coords[0]}..{coords[-1]}",
"psum": total,
}
def launch_on_pg(handle, pg) -> list:
ray.get(pg.ready())
return [
run_jax_psum.options(
scheduling_strategy=PlacementGroupSchedulingStrategy(
placement_group=pg,
placement_group_bundle_index=i,
)
).remote(handle.get_jax_env_vars(worker_id=i))
for i in range(handle.num_hosts)
]
# 1. Two concurrent 2x4 subslices (live coordinate discovery + KV cache reuse)
sub_a = subslice_placement_group("2x4", "v6e")
sub_b = subslice_placement_group("2x4", "v6e")
refs_a = launch_on_pg(sub_a, sub_a.placement_group)
refs_b = launch_on_pg(sub_b, sub_b.placement_group)
res_a, res_b = ray.get(refs_a), ray.get(refs_b)
for name, handle, res in [("subslice A", sub_a, res_a), ("subslice B", sub_b, res_b)]:
print(f"=== {name} (2x4, index={handle.subslice_index}, addrs={handle.get_worker_addrs()}) ===")
for i, r in enumerate(res):
print(f" bundle {i}: {r}")
assert all(r["psum"] == 8.0 for r in res)
sub_a.shutdown()
sub_b.shutdown()
# 2. Full 4x4 slice (bundle i pinned to ray.io/tpu-worker-id == str(i))
full = slice_placement_group("4x4", "v6e")
full_res = ray.get(launch_on_pg(full, full.slice_placement_group))
print("=== full slice (4x4) ===")
for i, r in enumerate(full_res):
print(f" bundle {i}: {r}")
assert [r["gke_worker_id"] for r in full_res] == ["0", "1", "2", "3"]
assert all(r["psum"] == 16.0 for r in full_res)
full.shutdown()Output: 2. Single-host tpu7x 2x2x1 (JAX)RayCluster: apiVersion: ray.io/v1
kind: RayCluster
metadata:
name: ray-tpu-v7x-2x2x1-verify
spec:
headGroupSpec:
rayStartParams: {}
template:
spec:
containers:
- name: ray-head
image: <Ray image with JAX and libtpu>
workerGroupSpecs:
- groupName: v7x-singlehost-group
replicas: 1
numOfHosts: 1
rayStartParams: {}
template:
spec:
containers:
- name: ray-worker
image: <Ray image with JAX and libtpu>
resources:
limits:
google.com/tpu: "4"
nodeSelector:
cloud.google.com/gke-tpu-accelerator: tpu7x
cloud.google.com/gke-tpu-topology: 2x2x1Test script ( import os
import jax
import jax.numpy as jnp
import ray
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
from ray.util.tpu import slice_placement_group
ray.init(log_to_driver=False)
@ray.remote(num_cpus=1, resources={"TPU": 4}, max_calls=1)
def run_jax_psum(env_vars: dict) -> dict:
os.environ.update(env_vars)
psum_fn = jax.pmap(lambda x: jax.lax.psum(x, "i"), axis_name="i")
total = float(psum_fn(jnp.ones(jax.local_device_count()))[0])
return {
"devices": jax.device_count(),
"visible_chips": os.environ.get("TPU_VISIBLE_CHIPS"),
"chip_bounds": os.environ.get("TPU_CHIPS_PER_HOST_BOUNDS"),
"host_bounds": os.environ.get("TPU_HOST_BOUNDS"),
"psum": total,
}
handle = slice_placement_group("2x2x1", "tpu7x")
pg = handle.slice_placement_group
ray.get(pg.ready())
result = ray.get(
run_jax_psum.options(
scheduling_strategy=PlacementGroupSchedulingStrategy(
placement_group=pg,
placement_group_bundle_index=0,
)
).remote(handle.get_jax_env_vars(worker_id=0))
)
print(f"bundle_label_selector={handle.bundle_label_selector}, result={result}")
assert handle.bundle_label_selector == [{}]
assert result["psum"] == 8.0
handle.shutdown()Output: 3. Multi-host tpu7x 2x2x4 (JAX subslices and full slice, RAY_TPU_RESOURCE_PER_CHIP=1)RayCluster: apiVersion: ray.io/v1
kind: RayCluster
metadata:
name: tpu-multi-host
spec:
headGroupSpec:
rayStartParams: {}
template:
spec:
containers:
- name: ray-head
image: <Ray image with JAX, TorchTPU, and libtpu>
workerGroupSpecs:
- groupName: v7x-multihost-group
replicas: 1
numOfHosts: 4
rayStartParams: {}
template:
spec:
containers:
- name: ray-worker
image: <Ray image with JAX, TorchTPU, and libtpu>
resources:
limits:
google.com/tpu: "4"
nodeSelector:
cloud.google.com/gke-tpu-accelerator: tpu7x
cloud.google.com/gke-tpu-topology: 2x2x4Test script ( import os
import jax
import jax.numpy as jnp
import ray
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
from ray.util.tpu import slice_placement_group, subslice_placement_group
ray.init(log_to_driver=False)
@ray.remote(num_cpus=1, resources={"TPU": 4}, max_calls=1)
def run_jax_psum(env_vars: dict) -> dict:
gke_worker_id = os.environ.get("TPU_WORKER_ID")
os.environ.update(env_vars)
psum_fn = jax.pmap(lambda x: jax.lax.psum(x, "i"), axis_name="i")
total = float(psum_fn(jnp.ones(jax.local_device_count()))[0])
coords = sorted(tuple(d.coords) for d in jax.local_devices())
return {
"gke_worker_id": gke_worker_id,
"jax_worker_id": os.environ["TPU_WORKER_ID"],
"process_bounds": os.environ.get("TPU_PROCESS_BOUNDS"),
"host_bounds": os.environ.get("TPU_HOST_BOUNDS"),
"devices": jax.device_count(),
"coords": f"{coords[0]}..{coords[-1]}",
"psum": total,
}
def launch_on_pg(handle, pg) -> list:
ray.get(pg.ready())
return [
run_jax_psum.options(
scheduling_strategy=PlacementGroupSchedulingStrategy(
placement_group=pg,
placement_group_bundle_index=i,
)
).remote(handle.get_jax_env_vars(worker_id=i))
for i in range(handle.num_hosts)
]
# 1. Two concurrent 2x2x2 subslices (live 3D coordinate discovery + KV cache reuse)
sub_a = subslice_placement_group("2x2x2", "tpu7x")
sub_b = subslice_placement_group("2x2x2", "tpu7x")
refs_a = launch_on_pg(sub_a, sub_a.placement_group)
refs_b = launch_on_pg(sub_b, sub_b.placement_group)
res_a, res_b = ray.get(refs_a), ray.get(refs_b)
for name, handle, res in [("subslice A", sub_a, res_a), ("subslice B", sub_b, res_b)]:
print(f"=== {name} (2x2x2, index={handle.subslice_index}, addrs={handle.get_worker_addrs()}) ===")
for i, r in enumerate(res):
print(f" bundle {i}: {r}")
assert all(r["psum"] == 16.0 for r in res)
sub_a.shutdown()
sub_b.shutdown()
# 2. Full 2x2x4 slice (bundle i pinned to ray.io/tpu-worker-id == str(i))
full = slice_placement_group("2x2x4", "tpu7x")
full_res = ray.get(launch_on_pg(full, full.slice_placement_group))
print("=== full slice (2x2x4) ===")
for i, r in enumerate(full_res):
print(f" bundle {i}: {r}")
assert [r["gke_worker_id"] for r in full_res] == ["0", "1", "2", "3"]
assert all(r["psum"] == 32.0 for r in full_res)
full.shutdown()Output: 4. Multi-host tpu7x 2x2x4 (TorchTPU 16-rank subslices, RAY_TPU_RESOURCE_PER_CHIP=2)With Test script ( import os
import torch
import torch.nn as nn
import torch.distributed as dist
import torch_tpu # noqa: F401
import ray
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
from ray.util.tpu import subslice_placement_group
ray.init(log_to_driver=False)
@ray.remote(num_cpus=1, resources={"TPU": 1}, max_calls=1)
def run_torchtpu_allreduce(
host_rank: int, world_size: int, addrs: list, base_port: int, master_port: int
) -> dict:
local_rank = int(ray.get_runtime_context().get_accelerator_ids()["TPU"][0])
rank = host_rank * 8 + local_rank
os.environ.update(
{
"RANK": str(rank),
"LOCAL_RANK": str(local_rank),
"WORLD_SIZE": str(world_size),
"LOCAL_WORLD_SIZE": "8",
"NNODES": str(len(addrs)),
"NODE_RANK": str(host_rank),
"MASTER_ADDR": addrs[0],
"MASTER_PORT": str(master_port),
"TORCH_TPU_TOPOLOGY": "2,2,2,2",
"TORCH_TPU_SLICEBUILDER_ADDRESSES": ",".join(
f"{host}:{base_port + lr}" for host in addrs for lr in range(8)
),
}
)
dist.init_process_group(backend="tpu_dist", rank=rank, world_size=world_size)
tensor = torch.tensor([float(rank + 1)], dtype=torch.float32, device="tpu")
dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
total = float(tensor.cpu().item())
torch.manual_seed(42)
model = nn.Sequential(
nn.Linear(64, 64, bias=False),
nn.ReLU(),
nn.Linear(64, 16, bias=False),
).to("tpu")
x = torch.ones((4, 64), dtype=torch.float32, device="tpu") * float(rank + 1)
loss = (model(x) ** 2).sum()
loss.backward()
for p in model.parameters():
dist.all_reduce(p.grad, op=dist.ReduceOp.SUM)
grad_norm = float(sum(p.grad.norm().cpu().item() for p in model.parameters()))
dist.destroy_process_group()
return {
"rank": rank,
"host_rank": host_rank,
"local_rank": local_rank,
"gke_worker_id": os.environ.get("TPU_WORKER_ID"),
"visible_chips": os.environ.get("TPU_VISIBLE_CHIPS"),
"allreduce_sum": total,
"grad_norm": round(grad_norm, 4),
}
def launch_subslice(handle, base_port: int, master_port: int) -> list:
pg = handle.placement_group
ray.get(pg.ready())
addrs = handle.get_worker_addrs()
world_size = len(pg.bundle_specs)
return [
run_torchtpu_allreduce.options(
scheduling_strategy=PlacementGroupSchedulingStrategy(
placement_group=pg,
placement_group_bundle_index=b,
)
).remote(b // 8, world_size, addrs, base_port, master_port)
for b in range(world_size)
]
sub_a = subslice_placement_group("2x2x2", "tpu7x", resources_per_bundle={"TPU": 1})
sub_b = subslice_placement_group("2x2x2", "tpu7x", resources_per_bundle={"TPU": 1})
refs_a = launch_subslice(sub_a, base_port=8600, master_port=29600)
refs_b = launch_subslice(sub_b, base_port=8700, master_port=29700)
res_a = sorted(ray.get(refs_a), key=lambda r: r["rank"])
res_b = sorted(ray.get(refs_b), key=lambda r: r["rank"])
for name, handle, res in [("subslice A", sub_a, res_a), ("subslice B", sub_b, res_b)]:
print(
f"=== {name} (2x2x2, index={handle.subslice_index}, "
f"addrs={handle.get_worker_addrs()}, bundles={len(res)}) ==="
)
print(f" rank 0: {res[0]}")
print(f" rank 8: {res[8]}")
assert all(r["allreduce_sum"] == 136.0 for r in res)
assert len({r["grad_norm"] for r in res}) == 1 and res[0]["grad_norm"] > 0
sub_a.shutdown()
sub_b.shutdown()Output: |
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
|
not stale, I will fix conflicts and I believe @spencer-p was reviewing the diff after their approval since I refactored a bit |
…rker IDs Signed-off-by: Ryan O'Leary <[email protected]>
7aedfe6 to
8eded85
Compare
…slice cache Signed-off-by: Ryan O'Leary <[email protected]>
… 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]>

Description
On GKE,
TPU_WORKER_IDfollows pod creation order rather than a host's physical position in the TPU slice topology. Subslices require physical host ordering so each subslice forms a contiguous sub-torus, and multi-host slice placement groups require bundleito schedule on the host whoseTPU_WORKER_IDmatches its rank.Key Changes
iof a multi-hostSlicePlacementGroupto the node whoseray.io/tpu-worker-idlabel equalsi // bundles_per_host(unless a worker ID selector is already provided), and raiseValueErrorwhen TPU resources per bundle do not evenly divide a host's logical devices.SubslicePlacementGroupbundles and per-process chip bounds from the subslice's chips per host rather than the parent host's total chips, and defaultsubslice_placement_groupstrategy toSPREADto support multiple bundles per host.get_worker_addrsandget_jax_env_varshelpers for slice and subslice placement groups, with IPv6-safe address formatting, port stripping, andTPU_PROCESS_PORTexport.TPUkeys inavailable_resources_per_nodeas zero available, filter dead nodes when resolving slice workers and bundle IPs, and normalize accelerator type strings inget_tpu_version_from_type.Related issues
Part of #64055
Test commands run and results
pytest python/ray/tests/test_tpu.py-> 203 passedpytest python/ray/tests/accelerators/test_tpu.py-> 132 passedtpu7x(2x2x4and2x2x2subslices) andv6e-16clusters, confirming physical coordinate discovery, deterministic bundle pinning, address ordering, and distributed JAX/PJRT execution.