Repository navigation
[TPU] Add PyTorch TPU environment variable APIs to Slice and Subslice placement groups - #65221
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces support for PyTorch/XLA TPU environment variables and runtime environments in Ray, adding utilities to normalize TPU topologies and retrieve TPU custom resources per chip. It also exposes methods to configure TORCH_TPU_TOPOLOGY and TORCH_TPU_SLICEBUILDER_ADDRESSES on placement groups. The review feedback highlights several critical improvements: expanding DUAL_DEVICE_TPU_TYPES to support GKE-style 'tpu7' prefixes, setting num_cpus=0 on the remote helper task to avoid deadlocks, strengthening address list length checks for multi-host sub-slices to prevent incomplete address slicing, and stripping spaces during topology parsing to ensure robustness.
Manual Testing StepsStep 1: Deploy a multi-host RayClusterA. v6e-16 / 4x4 topology, 16 chips across 4 nodesapiVersion: ray.io/v1
kind: RayCluster
metadata:
name: ray-tpu-v6e-cluster
spec:
headGroupSpec:
rayStartParams: {}
template:
spec:
containers:
- image: us-central2-docker.pkg.dev/tpu-vm-gke-testing/tpu-repo/ray-torch-tpu:2.55.0-v6
imagePullPolicy: IfNotPresent
name: ray-head
ports:
- containerPort: 8265
protocol: TCP
- containerPort: 10001
protocol: TCP
- containerPort: 8888
protocol: TCP
- containerPort: 8000
protocol: TCP
resources:
limits:
cpu: "4"
memory: 16Gi
requests:
cpu: "4"
memory: 16Gi
serviceAccountName: ray-ksa
workerGroupSpecs:
- groupName: tpu-v6e-group
maxReplicas: 8
minReplicas: 0
numOfHosts: 4
rayStartParams: {}
replicas: 1
template:
spec:
containers:
- image: us-central2-docker.pkg.dev/tpu-vm-gke-testing/tpu-repo/ray-torch-tpu:2.55.0-v6
imagePullPolicy: IfNotPresent
name: ray-worker
resources:
limits:
google.com/tpu: "4"
requests:
cpu: "4"
google.com/tpu: "4"
memory: 16Gi
nodeSelector:
cloud.google.com/gke-tpu-accelerator: tpu-v6e-slice
cloud.google.com/gke-tpu-topology: 4x4
serviceAccountName: ray-ksaB. v7x-16 / 2x2x2 topology, 8 physical chips (16 logical devices) across 2 nodesapiVersion: ray.io/v1
kind: RayCluster
metadata:
name: ray-tpu-multihost-cluster
spec:
headGroupSpec:
rayStartParams: {}
template:
spec:
containers:
- image: us-central2-docker.pkg.dev/tpu-vm-gke-testing/tpu-repo/ray-torch-tpu:2.55.0-v6
imagePullPolicy: IfNotPresent
name: ray-head
ports:
- containerPort: 8265
protocol: TCP
- containerPort: 10001
protocol: TCP
- containerPort: 8888
protocol: TCP
- containerPort: 8000
protocol: TCP
resources:
limits:
cpu: "4"
memory: 16Gi
requests:
cpu: "4"
memory: 16Gi
serviceAccountName: ray-ksa
workerGroupSpecs:
- groupName: tpu-multihost-group
maxReplicas: 8
minReplicas: 0
numOfHosts: 2
rayStartParams: {}
replicas: 1
template:
spec:
containers:
- image: us-central2-docker.pkg.dev/tpu-vm-gke-testing/tpu-repo/ray-torch-tpu:2.55.0-v6
imagePullPolicy: IfNotPresent
name: ray-worker
resources:
limits:
google.com/tpu: "4"
requests:
cpu: "4"
google.com/tpu: "4"
memory: 16Gi
nodeSelector:
cloud.google.com/gke-tpu-accelerator: tpu7x
cloud.google.com/gke-tpu-topology: 2x2x2
serviceAccountName: ray-ksaDeploy the desired 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 -o jsonpath='{.items[*].metadata.name}'))
for POD in "${PODS[@]}"; do
kubectl cp python/ray/util/tpu.py $POD:/home/ray/anaconda3/lib/python3.12/site-packages/ray/util/tpu.py
kubectl cp python/ray/_private/accelerators/tpu.py $POD:/home/ray/anaconda3/lib/python3.12/site-packages/ray/_private/accelerators/tpu.py
doneStep 3: Run Subslice PyTorch TPU Training Scriptimport os
import time
import ray
import torch
import torch.nn as nn
import torch.optim as optim
import torch.distributed as dist
from ray.util.tpu import subslice_placement_group
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc1 = nn.Linear(10, 32)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(32, 1)
def forward(self, x):
return self.fc2(self.relu(self.fc1(x)))
@ray.remote
def worker_task(rank: int, world_size: int, local_rank: int, local_world_size: int, master_addr: str, master_port: str):
topo_env = os.environ.get("TORCH_TPU_TOPOLOGY")
print(f"[Worker {rank}/{world_size}] TORCH_TPU_TOPOLOGY = {topo_env}")
addrs_env = os.environ.get("TORCH_TPU_SLICEBUILDER_ADDRESSES", "")
print(f"[Worker {rank}/{world_size}] TORCH_TPU_SLICEBUILDER_ADDRESSES = {addrs_env}")
os.environ["MASTER_ADDR"] = master_addr
os.environ["MASTER_PORT"] = master_port
os.environ["RANK"] = str(rank)
os.environ["WORLD_SIZE"] = str(world_size)
os.environ["LOCAL_RANK"] = str(local_rank)
os.environ["LOCAL_WORLD_SIZE"] = str(local_world_size)
os.environ["GROUP_RANK"] = str(rank)
os.environ["GROUP_WORLD_SIZE"] = str(world_size)
os.environ["ROLE_RANK"] = str(rank)
os.environ["ROLE_WORLD_RANK"] = str(rank)
os.environ["ROLE_WORLD_SIZE"] = str(world_size)
try:
import torch_tpu._loader
torch_tpu._loader.load()
except Exception as e:
print(f"[Worker {rank}] Note: torch_tpu._loader.load() -> {e}")
dist.init_process_group(backend="tpu_dist", init_method="env://")
device = torch.device("tpu")
model = SimpleModel().to(device)
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.05)
torch.manual_seed(42 + rank)
inputs = torch.randn(128, 10, device=device)
targets = inputs.sum(dim=1, keepdim=True)
print(f"[Worker {rank}] Starting 5 training epochs on sub-slice...")
initial_loss = None
final_loss = None
for epoch in range(5):
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
dist.all_reduce(loss, op=dist.ReduceOp.SUM)
avg_loss = (loss / world_size).item()
if epoch == 0:
initial_loss = avg_loss
final_loss = avg_loss
if rank == 0:
print(f"Epoch {epoch + 1:2d}/5 | Loss: {avg_loss:.6f}")
if rank == 0:
print(f"Sub-slice Training Complete! Initial Loss: {initial_loss:.6f} -> Final Loss: {final_loss:.6f}")
assert final_loss < initial_loss, "Expected training loss to decrease!"
dist.destroy_process_group()
return f"Rank {rank} finished successfully!"
@ray.remote
def get_worker_ip():
return ray.util.get_node_ip_address()
def main():
ray.init("auto")
print("\n--- 1. Creating Subslice Placement Group (2x4 on v6e / 4x4 parent) ---")
subslice_handle = subslice_placement_group(
subslice_topology="2x4",
parent_topology="4x4",
accelerator_version="v6e",
)
print(f"Subslice hosts: {subslice_handle.num_hosts}, chips per host: {subslice_handle.chips_per_host}")
runtime_env = subslice_handle.get_tpu_runtime_env()
print("Generated Subslice RuntimeEnv:", runtime_env)
print("\n--- 2. Scheduling tasks on the Subslice Placement Group ---")
pg = subslice_handle.placement_group
ray.get(pg.ready())
print("Subslice Placement Group is READY!")
rank_0_ip = ray.get(
get_worker_ip.options(
num_cpus=0,
scheduling_strategy=PlacementGroupSchedulingStrategy(
placement_group=pg,
placement_group_bundle_index=0,
)
).remote()
)
print(f"Resolved rank 0 rendezvous IP: {rank_0_ip}")
total_workers = subslice_handle.num_hosts * subslice_handle.chips_per_host
futures = []
for i in range(total_workers):
host_idx = i // subslice_handle.chips_per_host
local_rank = i % subslice_handle.chips_per_host
scheduling_strategy = PlacementGroupSchedulingStrategy(
placement_group=pg,
placement_group_bundle_index=host_idx,
)
task = worker_task.options(
num_cpus=0,
scheduling_strategy=scheduling_strategy,
runtime_env=runtime_env,
resources={"TPU": 1},
).remote(
rank=i,
world_size=total_workers,
local_rank=local_rank,
local_world_size=subslice_handle.chips_per_host,
master_addr=rank_0_ip,
master_port="29500",
)
futures.append(task)
results = ray.get(futures)
print("\n--- 3. Execution Results ---")
for res in results:
print(" ->", res)
if __name__ == "__main__":
main()Copy script and submit job: HEAD_POD=$(kubectl get pods -l ray.io/node-type=head,ray.io/cluster=ray-tpu-v6e-cluster -o jsonpath='{.items[0].metadata.name}')
kubectl cp test_torchtpu_subslice_e2e.py $HEAD_POD:/home/ray/test_torchtpu_subslice_e2e.py
kubectl exec $HEAD_POD -- python3 /home/ray/test_torchtpu_subslice_e2e.pyStep 4: ResultsA. Multi-host TPU v6e Sub-slice (2x4 subslice on 4x4 parent, 8 workers across 2 hosts)B. Multi-host TPU7x Ironwood Sub-slice (2x2x1 subslice on 2x2x2 parent, 4D topology
|
|
cc: @spencer-p for review since this changes |
06d995f to
a37a053
Compare
spencer-p
left a comment
There was a problem hiding this comment.
LGTM with some thoughts:
- For deriving TORCH_TPU_SLICEBUILDER_ADDRESSES with SSPG, it seems the common case will be the CPU head needing to run a job on rank 0's TPU to get the original env var value. Since the SSPG builder already runs a job on the parent slice to read the coords, it might be nice to have env var collection go through that job and be cached for later.
- I wonder if the placement groups should expose a property or something for the master_addr to eliminate the rank_0_ip boilerplate.
3b63b7a to
62b9cb3
Compare
@spencer-p did a pretty big refactor based on your comments so this is worth another review. This PR now:
I also made some changes not explicitly for TorchTPU support, but to fix small issues I found when implementing the above:
I can separate out the above 3 if the other changes take a while to get merged, but leaving them in for now. |
62b9cb3 to
7c2ca72
Compare
|
cc: @spencer-p all comments should be resolved now |
…PU chips (ray-project#65723) ## Description On GKE, the TPU device plugin explicitly injects `TPU_VISIBLE_CHIPS="0,1,2,3"` for privileged containers (`securityContext.privileged: true`), while leaving it unset for non-privileged containers. On dual-device TPUs (TPU7x), this injected physical chip mask causes Ray to clamp the node to 4 logical resources instead of the 8 detected from hardware (or explicitly set with`--resources='{"TPU": 8}', causing startup validation failures. Previously, `TPUAcceleratorManager` handled `TPU_VISIBLE_CHIPS` without translation: 1. `get_current_process_visible_accelerator_ids()` returned physical chip counts resource accounting to fail when auto-detecting or explicitly requesting all logical devices. 2. `set_current_process_visible_accelerator_ids()` passed logical device IDs directly into `TPU_VISIBLE_CHIPS`, setting out-of-bounds physical chip indices for worker processes. This PR changes: - `get_current_process_visible_accelerator_ids()`: Expands physical chip indices to logical device IDs (e.g. `["0", "1", "2", "3"]` -> `["0", ..., "7"]`). - `set_current_process_visible_accelerator_ids()`: Maps logical device IDs back to physical chip indices (`device_id // resource_per_chip`) before exporting `TPU_VISIBLE_CHIPS` - `get_tpu_resource_per_chip()`: A single validated accessor for `RAY_TPU_RESOURCE_PER_CHIP`, replacing five copies of `int(os.environ.get(...))` in `ray/util/tpu.py` where a non-positive value silently produced zero TPU resources per slice. - `normalize_tpu_accelerator_type()`: A single helper for the canonical `v{gen}` spelling, replacing three inlined variants. This also fixes `is_valid_tpu_accelerator_topology()`, which split `TPU-V6E` on `-` before parsing the generation and so rejected every `TPU-`-prefixed version. Both masking directions are gated on `RAY_TPU_RESOURCE_PER_CHIP` (default `1`), so per-device accounting is opt-in and the default host-level behavior is unchanged. The above change is required to get `TPU_VISIBLE_CHIPS` set correctly for both legacy SPMD behavior (workloads request all TPU chips on a host) and with frameworks that run a process per TPU device (i.e. PyTorch). ## Related issues Contributes to: ray-project#64055 ## Additional information There is some overlap in this PR with: ray-project#65221 in terms of the `RAY_TPU_RESOURCE_PER_CHIP_ENV_VAR` change and getter. --------- Signed-off-by: Ryan O'Leary <[email protected]>
|
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, just pending based on #66029 |
…rker IDs Signed-off-by: Ryan O'Leary <[email protected]>
…ment groups Signed-off-by: Ryan O'Leary <[email protected]>
630c322 to
f25728f
Compare
Signed-off-by: Ryan O'Leary <[email protected]>
…slice cache Signed-off-by: Ryan O'Leary <[email protected]>
…chtpu-subslice-support Signed-off-by: Ryan O'Leary <[email protected]>
Signed-off-by: Ryan O'Leary <[email protected]>
…chtpu-subslice-support Signed-off-by: Ryan O'Leary <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit bc0a343. Configure here.
…-support Signed-off-by: Ryan O'Leary <[email protected]>
spencer-p
left a comment
There was a problem hiding this comment.
LGTM overall, some small comments.
Signed-off-by: Ryan O'Leary <[email protected]>
…mentGroup (#67878) ## Why are these changes needed? Follows up on #65221. In a multi-slice PyTorch/TPU MegaScale job (`WORLD_SIZE > len(TORCH_TPU_SLICEBUILDER_ADDRESSES)`), `TORCH_TPU_SLICEBUILDER_ADDRESSES` and `TPU_WORKER_HOSTNAMES` stay slice-local while PyTorch's `c10d::TCPStore` (`init_method="env://"`) roots on global rank 0 (slice 0, host 0). Previously, `SlicePlacementGroup.get_torchtpu_env_vars(worker_id, slice_index=s)` resolved `worker_hostnames` for slice `s` and passed `master_addr=None` through to `get_torchtpu_env_vars`, causing slice `s > 0` to default `MASTER_ADDR` to its own slice's host 0 instead of slice 0's host 0. When `master_addr` is omitted and `slice_index > 0`, resolve `MASTER_ADDR` from `self.get_worker_addrs(0)[0]`. Callers running independent single-slice worlds can still pass `master_addr=spg.get_worker_addrs(s)[0]` explicitly. Verified locally across `python/ray/tests/test_tpu.py` and end-to-end with `torch.distributed.init_process_group("tpu")` + cross-slice `all_reduce` across two physical `2x4` `v6e-8` slices (16 chips). ## Related issue number Part of #64055 (follows up on #65221) ## 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 Tune, 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 - [ ] Release tests - [ ] This PR is not tested :( --------- Signed-off-by: Ryan O'Leary <[email protected]>

Why are these changes needed?
Adds helper APIs to generate the environment variables required by
torch_tpufor TPU slices and sub-slices:ray.util.tpu.get_torchtpu_env_vars(): normalizes 2D, 3D, and 4D TPU topology strings into comma-separatedTORCH_TPU_TOPOLOGYvalues — such as"4x4"to"4,4,1"and"2x2x4"on dual-devicev7xto"2,2,4,2"— and generates per-deviceTORCH_TPU_SLICEBUILDER_ADDRESSES,TPU_WORKER_HOSTNAMES,MASTER_ADDR, andTPU_WORKER_ID.SlicePlacementGroup.get_torchtpu_env_vars()andSubslicePlacementGroup.get_torchtpu_env_vars(): resolve placed worker host IPs inTPU_WORKER_IDorder viaget_worker_addrs()and delegate toget_torchtpu_env_vars(), settingTPU_TOPOLOGYto the sub-slice topology onSubslicePlacementGroup.Related issue number
Contributes to [Core][Train] Support Torch runtime with TPUs (ray#64055).
Checks
git commit -s) in this PR.scripts/format.shto lint the changes in this PR.