Skip to content

[TPU] Add PyTorch TPU environment variable APIs to Slice and Subslice placement groups - #65221

Merged
andrewsykim merged 10 commits into
ray-project:masterfrom
ryanaoleary:torchtpu-subslice-support
Nov 5, 2026
Merged

andrewsykim merged 10 commits into
ray-project:masterfrom
ryanaoleary:torchtpu-subslice-support

Conversation

@ryanaoleary

@ryanaoleary ryanaoleary commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Adds helper APIs to generate the environment variables required by torch_tpu for TPU slices and sub-slices:

  • ray.util.tpu.get_torchtpu_env_vars(): normalizes 2D, 3D, and 4D TPU topology strings into comma-separated TORCH_TPU_TOPOLOGY values — such as "4x4" to "4,4,1" and "2x2x4" on dual-device v7x to "2,2,4,2" — and generates per-device TORCH_TPU_SLICEBUILDER_ADDRESSES, TPU_WORKER_HOSTNAMES, MASTER_ADDR, and TPU_WORKER_ID.
  • SlicePlacementGroup.get_torchtpu_env_vars() and SubslicePlacementGroup.get_torchtpu_env_vars(): resolve placed worker host IPs in TPU_WORKER_ID order via get_worker_addrs() and delegate to get_torchtpu_env_vars(), setting TPU_TOPOLOGY to the sub-slice topology on SubslicePlacementGroup.

Related issue number

Contributes to [Core][Train] Support Torch runtime with TPUs (ray#64055).

Checks

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread python/ray/_private/accelerators/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/_private/accelerators/tpu.py Resolved
@ryanaoleary

Copy link
Copy Markdown
Contributor Author

Manual Testing Steps

Step 1: Deploy a multi-host RayCluster

A. v6e-16 / 4x4 topology, 16 chips across 4 nodes

apiVersion: 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-ksa

B. v7x-16 / 2x2x2 topology, 8 physical chips (16 logical devices) across 2 nodes

apiVersion: 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-ksa

Deploy the desired cluster:

kubectl apply -f v6e_cluster.yaml

Step 2: Patch in local changes from this PR to running RayCluster pods

CLUSTER_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
done

Step 3: Run Subslice PyTorch TPU Training Script

import 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.py

Step 4: Results

A. Multi-host TPU v6e Sub-slice (2x4 subslice on 4x4 parent, 8 workers across 2 hosts)

2026-08-03 23:26:10,153 INFO tpu.py:1597 -- Subslice discovery complete for slice 'tpu-multihost-group-0' (4x4). Found 4 workers.
...
Generated Subslice RuntimeEnv: {'env_vars': {'TORCH_TPU_TOPOLOGY': '2,4,1', 'TORCH_TPU_SLICEBUILDER_ADDRESSES': 'tpu-multihost-group-0-2.tpu-multi-host-headless:8471,tpu-multihost-group-0-2.tpu-multi-host-headless:8472,tpu-multihost-group-0-2.tpu-multi-host-headless:8473,tpu-multihost-group-0-2.tpu-multi-host-headless:8474,tpu-multihost-group-0-3.tpu-multi-host-headless:8471,tpu-multihost-group-0-3.tpu-multi-host-headless:8472,tpu-multihost-group-0-3.tpu-multi-host-headless:8473,tpu-multihost-group-0-3.tpu-multi-host-headless:8474'}}
...
(worker_task pid=588, ip=10.228.9.7) [Worker 0/2] TORCH_TPU_TOPOLOGY = 2,4,1
(worker_task pid=576, ip=10.228.15.7) [Worker 1/2] TORCH_TPU_TOPOLOGY = 2,4,1
...
(worker_task pid=588, ip=10.228.9.7) Successfully renamed PrivateUse1 backend to 'tpu'. Device: device(type='tpu')
...
(pid=, ip=10.228.16.7) I0803 23:26:07.158917     388 session_master.cc:307] Successfully started ICI network session with session id: f14728952699dc38
...
(worker_task pid=588, ip=10.228.9.7) [Worker 0/2] Starting 5 training epochs on sub-slice...
(worker_task pid=588, ip=10.228.9.7) Epoch  1/5 | Loss: 11.452031
(worker_task pid=588, ip=10.228.9.7) Epoch  2/5 | Loss: 9.871104
(worker_task pid=588, ip=10.228.9.7) Epoch  3/5 | Loss: 7.912445
(worker_task pid=588, ip=10.228.9.7) Epoch  4/5 | Loss: 5.612988
(worker_task pid=588, ip=10.228.9.7) Epoch  5/5 | Loss: 3.204519
(worker_task pid=588, ip=10.228.9.7) Sub-slice Training Complete! Initial Loss: 11.452031 -> Final Loss: 3.204519
(worker_task pid=588, ip=10.228.9.7) Rank 0 finished successfully!
(worker_task pid=576, ip=10.228.15.7) Rank 1 finished successfully!

B. Multi-host TPU7x Ironwood Sub-slice (2x2x1 subslice on 2x2x2 parent, 4D topology 2,2,1,2)

--- 1. Creating Subslice Placement Group (2x2x1 on v7x / 2x2x2 parent) ---
Subslice hosts: 2, chips per host: 4
Generated Subslice RuntimeEnv: {'env_vars': {'TORCH_TPU_TOPOLOGY': '2,2,1,2', 'TORCH_TPU_SLICEBUILDER_ADDRESSES': '10.228.16.13:8471,10.228.16.13:8472,10.228.16.13:8473,10.228.16.13:8474,10.228.17.13:8471,10.228.17.13:8472,10.228.17.13:8473,10.228.17.13:8474'}}

--- 2. Scheduling tasks on the Subslice Placement Group ---
Subslice Placement Group is READY!
Resolved rank 0 rendezvous IP: 10.228.16.13
[Worker 0/8] TORCH_TPU_TOPOLOGY = 2,2,1,2
[Worker 0/8] TORCH_TPU_SLICEBUILDER_ADDRESSES = 10.228.16.13:8471,10.228.16.13:8472,10.228.16.13:8473,10.228.16.13:8474,10.228.17.13:8471,10.228.17.13:8472,10.228.17.13:8473,10.228.17.13:8474
[Worker 0] Starting 5 training epochs on sub-slice...
Epoch  1/5 | Loss: 9.340121
Epoch  2/5 | Loss: 7.120534
Epoch  3/5 | Loss: 4.881203
Epoch  4/5 | Loss: 2.710492
Epoch  5/5 | Loss: 1.109384
Sub-slice Training Complete! Initial Loss: 9.340121 -> Final Loss: 1.109384

--- 3. Execution Results ---
  -> Rank 0 finished successfully!
  -> Rank 1 finished successfully!
  ... [repeated across all 8 sub-slice workers on 2 hosts]

The multi-host test on Ironwood was done with the changes from this PR patched in to verify sub-slice address resolution.

@ryanaoleary

Copy link
Copy Markdown
Contributor Author

cc: @spencer-p for review since this changes SubSlicePlacementGroup

Comment thread python/ray/_private/accelerators/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
@ryanaoleary
ryanaoleary force-pushed the torchtpu-subslice-support branch from 06d995f to a37a053 Compare August 5, 2026 05:11
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/_private/accelerators/tpu.py Resolved
@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Aug 5, 2026

@spencer-p spencer-p left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM with some thoughts:

  1. 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.
  2. I wonder if the placement groups should expose a property or something for the master_addr to eliminate the rank_0_ip boilerplate.

Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
@ryanaoleary
ryanaoleary force-pushed the torchtpu-subslice-support branch from 3b63b7a to 62b9cb3 Compare August 14, 2026 02:53
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
@ryanaoleary

ryanaoleary commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor Author

LGTM with some thoughts:

  1. 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.
  2. I wonder if the placement groups should expose a property or something for the master_addr to eliminate the rank_0_ip boilerplate.

@spencer-p did a pretty big refactor based on your comments so this is worth another review. This PR now:

  1. Added get_torchtpu_env_vars() and normalize_torchtpu_topology() to generate TorchTPU environment variables (TORCH_TPU_TOPOLOGY, TORCH_TPU_SLICEBUILDER_ADDRESSES) for all TPU gens.
  2. Added get_tpu_env_vars() and get_tpu_runtime_env() helper methods to SlicePlacementGroup and SubslicePlacementGroup for passing runtime environments directly to tasks and actors.
  3. Added per-host slicebuilder address discovery and internal KV caching during subslice init
  4. Added master_addr property to SubslicePlacementGroup and SlicePlacementGroup (along with master_addrs and get_master_addr(slice_index)) to resolve the bundle 0 node IP for workloads like PyTorch that use it.
  5. Added subslice_index parameter to subslice_placement_group() to allow targeting a specific subslice index within a parent slice. Edit: this was implemented in a separate PR so is not done here any longer

I also made some changes not explicitly for TorchTPU support, but to fix small issues I found when implementing the above:

  1. For SubslicePlacementGroup, added get_tpu_resource_per_chip() and devices_per_host to dynamically support dual-device TPU architectures (v7x) and the RAY_TPU_RESOURCE_PER_CHIP environment override.
  2. Enforced ray.io/accelerator-type label selectors on single-host TPU placement groups to prevent mis-scheduling across accelerator versions in heterogeneous clusters.
  3. Removed non-existent 2x8 from the list of supported topologies.

I can separate out the above 3 if the other changes take a while to get merged, but leaving them in for now.

@ryanaoleary
ryanaoleary force-pushed the torchtpu-subslice-support branch from 62b9cb3 to 7c2ca72 Compare August 14, 2026 04:00
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/tests/test_tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/_private/accelerators/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/_private/accelerators/tpu.py Resolved
@ryanaoleary
ryanaoleary requested a review from spencer-p August 19, 2026 00:28
Comment thread python/ray/_private/accelerators/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
@ryanaoleary
ryanaoleary requested a review from spencer-p August 21, 2026 00:19
@ryanaoleary

Copy link
Copy Markdown
Contributor Author

cc: @spencer-p all comments should be resolved now

Comment thread python/ray/_private/accelerators/tpu.py Resolved
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…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]>
@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

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.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 9, 2026
@ryanaoleary

Copy link
Copy Markdown
Contributor Author

not stale, just pending based on #66029

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 10, 2026
@ryanaoleary
ryanaoleary force-pushed the torchtpu-subslice-support branch from 630c322 to f25728f Compare October 26, 2026 20:06

@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 bc0a343. Configure here.

Comment thread python/ray/util/tpu.py Resolved

@spencer-p spencer-p left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM overall, some small comments.

Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
Comment thread python/ray/util/tpu.py Resolved
@ryanaoleary ryanaoleary added the go add ONLY when ready to merge, run all tests label Nov 5, 2026
@andrewsykim
andrewsykim merged commit e01975b into ray-project:master Nov 5, 2026
7 checks passed
ryanaoleary added a commit that referenced this pull request Nov 11, 2026
…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]>
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 unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants