Skip to content

[Core][TPU] Order subslice hosts by physical topology and pin slice bundles to worker IDs - #66029

Merged
ryanaoleary merged 3 commits into
ray-project:masterfrom
ryanaoleary:tpu-worker-id-ordering
Nov 3, 2026
Merged

ryanaoleary merged 3 commits into
ray-project:masterfrom
ryanaoleary:tpu-worker-id-ordering

Conversation

@ryanaoleary

@ryanaoleary ryanaoleary commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Description

On GKE, TPU_WORKER_ID follows 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 bundle i to schedule on the host whose TPU_WORKER_ID matches its rank.

Key Changes

  • Pin bundle i of a multi-host SlicePlacementGroup to the node whose ray.io/tpu-worker-id label equals i // bundles_per_host (unless a worker ID selector is already provided), and raise ValueError when TPU resources per bundle do not evenly divide a host's logical devices.
  • Discover each host's physical chip coordinates with JAX inside a temporary full-slice placement group, store the worker-to-physical-ID map in internal KV, and compute contiguous subslice host membership on demand across all valid 2D and 3D topologies.
  • Size SubslicePlacementGroup bundles and per-process chip bounds from the subslice's chips per host rather than the parent host's total chips, and default subslice_placement_group strategy to SPREAD to support multiple bundles per host.
  • Add get_worker_addrs and get_jax_env_vars helpers for slice and subslice placement groups, with IPv6-safe address formatting, port stripping, and TPU_PROCESS_PORT export.
  • Treat omitted TPU keys in available_resources_per_node as zero available, filter dead nodes when resolving slice workers and bundle IPs, and normalize accelerator type strings in get_tpu_version_from_type.

Related issues

Part of #64055

Test commands run and results

  • Local unit tests:
    • pytest python/ray/tests/test_tpu.py -> 203 passed
    • pytest python/ray/tests/accelerators/test_tpu.py -> 132 passed
  • Live GKE TPU hardware verification:
    • Verified on GKE tpu7x (2x2x4 and 2x2x2 subslices) and v6e-16 clusters, confirming physical coordinate discovery, deterministic bundle pinning, address ordering, and distributed JAX/PJRT execution.

@ryanaoleary

Copy link
Copy Markdown
Contributor Author

Manual Testing

Step 1: Deploy a multi-host RayCluster

apiVersion: 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.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,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
done

Step 3: Run Verification

Multi-host SlicePlacementGroup, physical coordinate discovery, and run_on_slice dispatch (verify_spg_e2e.py)

import functools
import jax
import jax.numpy as jnp
import ray
from ray._private.accelerators.tpu import TPUAcceleratorManager
from ray.util.tpu import run_on_slice, slice_placement_group


@ray.remote
def tpu_work(coordinator_addr: str, num_hosts: int):
    # 1. Query physical chip coordinates directly from hardware via libtpu
    from libtpu import sdk

    chip_coords = sdk.slice.get_chip_coordinates()
    coords = [
        list(c.coordinates()) if hasattr(c, "coordinates") else list(c[2])
        for c in chip_coords
    ]

    # 2. Get hardware-discovered worker ID and Ray node label
    hw_worker_id = TPUAcceleratorManager.get_current_node_tpu_worker_id()
    node_labels = ray.get_runtime_context().get_node_labels()
    label_worker_id = int(node_labels.get("ray.io/tpu-worker-id", -1))

    # 3. Initialize JAX distributed runtime
    jax.distributed.initialize(
        coordinator_address=f"{coordinator_addr}:12345",
        num_processes=num_hosts,
        process_id=label_worker_id,
        initialization_timeout=90,
    )

    # 4. Collective computation: all-reduce sum across all 16 chips
    @functools.partial(jax.pmap, axis_name="i")
    def psum(x):
        return jax.lax.psum(x, axis_name="i")

    x = jnp.ones((jax.local_device_count(), 1024), dtype=jnp.float32)
    out = psum(x).block_until_ready()
    all_reduce_sum = float(out.addressable_data(0).flatten()[0])

    return {
        "worker_id": label_worker_id,
        "hw_worker_id": hw_worker_id,
        "coords": coords,
        "ip": ray.get_runtime_context().get_node_ip_address(),
        "devices": jax.device_count(),
        "all_reduce_sum": all_reduce_sum,
    }


def main():
    ray.init(address="auto")

    # Reserve 1 slice of TPU v6e-16 (4 hosts, 4x4 topology)
    spg = slice_placement_group(topology="4x4", accelerator_version="v6e")
    ray.get(spg.placement_group.ready(), timeout=60)

    print(f"Master address: {spg.master_addr}")
    print(f"Worker addresses: {spg.worker_addrs}\n")

    # Verify bundle pinning: bundle i maps to physical worker i
    nodes_by_ip = {
        n["NodeManagerAddress"]: n.get("Labels", {}).get("ray.io/tpu-worker-id")
        for n in ray.nodes()
        if n["Alive"]
    }
    print("Bundle to physical worker mapping:")
    for i, ip in enumerate(spg.worker_addrs):
        worker_id = nodes_by_ip.get(ip)
        print(f"  Bundle {i} -> {ip} (ray.io/tpu-worker-id: {worker_id})")
        assert str(i) == str(worker_id)

    # Dispatch to every host using Ray's TPU dispatch API
    print("\nDispatching tasks with run_on_slice...")
    refs = run_on_slice(
        tpu_work,
        spg.master_addr,
        spg.num_hosts,
        tpu_slice=spg,
    )
    results = ray.get(refs, timeout=120)

    # Validate each worker's physical chip coordinates and computation
    print("\nWorker physical topology & computation results:")
    for res in sorted(results, key=lambda r: r["worker_id"]):
        wid = res["worker_id"]
        hw_id = res["hw_worker_id"]
        ip = res["ip"]
        coords = res["coords"]
        dev_cnt = res["devices"]
        sum_val = res["all_reduce_sum"]

        # Calculate bounding box of physical chips on this VM
        min_x = min(c[0] for c in coords)
        min_y = min(c[1] for c in coords)
        print(f"Worker {wid} (Host IP: {ip}):")
        print(f"  Physical chip coords: {coords}")
        print(f"  Physical grid origin: ({min_x}, {min_y}) -> mapped to worker_id {hw_id}")
        print(f"  Devices: {dev_cnt}, All-reduce sum: {sum_val}")

        assert wid == hw_id
        assert dev_cnt == 16
        assert sum_val == 16.0

    spg.shutdown()
    print("\nAll 4 workers verified: physical hardware coordinates match assigned worker IDs and JAX collectives succeeded.")


if __name__ == "__main__":
    main()

Copy script and run:

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 verify_spg_e2e.py $HEAD_POD:/tmp/verify_spg_e2e.py -c ray-head
kubectl exec $HEAD_POD -c ray-head -- python3 /tmp/verify_spg_e2e.py

Step 4: Results

Multi-host TPU v6e-16 (4 hosts, 16 chips, 4x4 topology)

Master address: 10.228.10.7
Worker addresses: ['10.228.10.7', '10.228.12.7', '10.228.11.7', '10.228.13.7']

Bundle to physical worker mapping:
  Bundle 0 -> 10.228.10.7 (ray.io/tpu-worker-id: 0)
  Bundle 1 -> 10.228.12.7 (ray.io/tpu-worker-id: 1)
  Bundle 2 -> 10.228.11.7 (ray.io/tpu-worker-id: 2)
  Bundle 3 -> 10.228.13.7 (ray.io/tpu-worker-id: 3)

Dispatching tasks with run_on_slice...
Worker physical topology & computation results:
Worker 0 (Host IP: 10.228.10.7):
  Physical chip coords: [[0, 0], [0, 1], [1, 0], [1, 1]]
  Physical grid origin: (0, 0) -> mapped to worker_id 0
  Devices: 16, All-reduce sum: 16.0
Worker 1 (Host IP: 10.228.12.7):
  Physical chip coords: [[2, 0], [2, 1], [3, 0], [3, 1]]
  Physical grid origin: (2, 0) -> mapped to worker_id 1
  Devices: 16, All-reduce sum: 16.0
Worker 2 (Host IP: 10.228.11.7):
  Physical chip coords: [[0, 2], [0, 3], [1, 2], [1, 3]]
  Physical grid origin: (0, 2) -> mapped to worker_id 2
  Devices: 16, All-reduce sum: 16.0
Worker 3 (Host IP: 10.228.13.7):
  Physical chip coords: [[2, 2], [2, 3], [3, 2], [3, 3]]
  Physical grid origin: (2, 2) -> mapped to worker_id 3
  Devices: 16, All-reduce sum: 16.0

All 4 workers verified: physical hardware coordinates match assigned worker IDs and JAX collectives succeeded.

@ryanaoleary
ryanaoleary force-pushed the tpu-worker-id-ordering branch 2 times, most recently from e359e8b to 366b0de Compare September 19, 2026 01:01
@ryanaoleary
ryanaoleary marked this pull request as ready for review September 19, 2026 01:09
@ryanaoleary
ryanaoleary requested review from a team, andrewsykim and edoakes as code owners September 19, 2026 01:09
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@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.

Stale Bugbot comment from a previous run.

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 Sep 19, 2026
@ryanaoleary
ryanaoleary force-pushed the tpu-worker-id-ordering branch from 366b0de to 3808b92 Compare September 19, 2026 01:50

@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.

Stale Bugbot comment from a previous run.

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

Copy link
Copy Markdown
Contributor Author

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 TPU_WORKER_ID env var set synchronously to begin with based on their actual physical locations in the mesh, but I haven't found a good way to do so that's supportive of Autopilot/NAP.

Comment thread python/ray/_private/accelerators/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.

Looks good, some details are not clear but I am guessing there are simple explanations we can leave in comments

Comment thread python/ray/_private/accelerators/tpu.py Resolved
@ryanaoleary
ryanaoleary requested a review from a team as a code owner September 24, 2026 09:40

@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.

Stale Bugbot comment from a previous run.

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

Copy link
Copy Markdown
Contributor Author

@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

@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.

Stale Bugbot comment from a previous run.

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

@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.

Stale Bugbot comment from a previous run.

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

@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.

Stale Bugbot comment from a previous run.

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
@ryanaoleary ryanaoleary changed the title [Core][TPU] Support physical worker ID hardware discovery and deterministic bundle pinning for multi-host slices [Core][TPU] Order subslice hosts by physical topology and pin slice bundles to worker IDs Sep 30, 2026

@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.

Stale Bugbot comment from a previous run.

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

@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 using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 7aedfe6. Configure here.

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

Copy link
Copy Markdown
Contributor Author

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 get_jax_env_vars API, and enables subslicing through that API and physical coordinate location discovery. In the future if GKE publishes more informative slice labels on TPU nodes we'll consume those labels here and skip any JAX calls.

@ryanaoleary

ryanaoleary commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Manual testing (re-ran after refactor)

Verified on GKE TPU clusters across four configurations:

  • 4-host v6e 4x4 slice: ran two concurrent 2x4 JAX subslices followed by a full 4x4 slice
  • Single-host tpu7x 2x2x1 node: ran a whole-host slice_placement_group (bundle_label_selector == [{}]) with an 8-TensorCore JAX psum collective
  • 4-host tpu7x 2x2x4 slice (RAY_TPU_RESOURCE_PER_CHIP=1): ran two concurrent 2x2x2 JAX subslices on physically contiguous host pairs followed by a full 2x2x4 slice
  • 4-host tpu7x 2x2x4 slice (RAY_TPU_RESOURCE_PER_CHIP=2): ran two concurrent 16-rank 2x2x2 TorchTPU subslices (resources_per_bundle={"TPU": 1}) executing dist.all_reduce and an MLP forward/backward + gradient all_reduce step

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: 4x4

Test script (test_v6e_4x4.py):

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:

2026-11-03 02:46:29,150	INFO tpu.py:1593 -- Running TPU subslice topology discovery for 4x4 (v6e)...
2026-11-03 02:46:38,415	INFO tpu.py:1725 -- Subslice discovery complete for slice 'v6e-worker-group-0' (4x4). Found 4 workers.
=== subslice A (2x4, index=0, addrs=['10.72.13.22', '10.72.2.22']) ===
  bundle 0: {'gke_worker_id': '2', 'jax_worker_id': '0', 'process_bounds': '1,2,1', 'chip_bounds': '2,2,1', 'devices': 8, 'coords': '(0, 0, 0)..(1, 1, 0)', 'psum': 8.0}
  bundle 1: {'gke_worker_id': '3', 'jax_worker_id': '1', 'process_bounds': '1,2,1', 'chip_bounds': '2,2,1', 'devices': 8, 'coords': '(0, 2, 0)..(1, 3, 0)', 'psum': 8.0}
=== subslice B (2x4, index=1, addrs=['10.72.15.22', '10.72.3.22']) ===
  bundle 0: {'gke_worker_id': '0', 'jax_worker_id': '0', 'process_bounds': '1,2,1', 'chip_bounds': '2,2,1', 'devices': 8, 'coords': '(0, 0, 0)..(1, 1, 0)', 'psum': 8.0}
  bundle 1: {'gke_worker_id': '1', 'jax_worker_id': '1', 'process_bounds': '1,2,1', 'chip_bounds': '2,2,1', 'devices': 8, 'coords': '(0, 2, 0)..(1, 3, 0)', 'psum': 8.0}
=== full slice (4x4) ===
  bundle 0: {'gke_worker_id': '0', 'jax_worker_id': '0', 'process_bounds': None, 'chip_bounds': None, 'devices': 16, 'coords': '(2, 0, 0)..(3, 1, 0)', 'psum': 16.0}
  bundle 1: {'gke_worker_id': '1', 'jax_worker_id': '1', 'process_bounds': None, 'chip_bounds': None, 'devices': 16, 'coords': '(2, 2, 0)..(3, 3, 0)', 'psum': 16.0}
  bundle 2: {'gke_worker_id': '2', 'jax_worker_id': '2', 'process_bounds': None, 'chip_bounds': None, 'devices': 16, 'coords': '(0, 0, 0)..(1, 1, 0)', 'psum': 16.0}
  bundle 3: {'gke_worker_id': '3', 'jax_worker_id': '3', 'process_bounds': None, 'chip_bounds': None, 'devices': 16, 'coords': '(0, 2, 0)..(1, 3, 0)', 'psum': 16.0}

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: 2x2x1

Test script (test_tpu7x_2x2x1_jax.py):

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:

bundle_label_selector=[{}], result={'devices': 8, 'visible_chips': '0,1,2,3', 'chip_bounds': '2,2,1', 'host_bounds': '1,1,1', 'psum': 8.0}

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: 2x2x4

Test script (test_tpu7x_2x2x4_jax.py):

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:

2026-11-02 18:48:17,255	INFO tpu.py:1593 -- Running TPU subslice topology discovery for 2x2x4 (v7x)...
2026-11-02 18:48:22,797	INFO tpu.py:1725 -- Subslice discovery complete for slice 'v7x-multihost-group-0' (2x2x4). Found 4 workers.
=== subslice A (2x2x2, index=0, addrs=['10.4.8.104', '10.4.8.72']) ===
  bundle 0: {'gke_worker_id': '3', 'jax_worker_id': '0', 'process_bounds': '1,1,2', 'host_bounds': '1,1,4', 'devices': 16, 'coords': '(0, 0, 0)..(1, 1, 0)', 'psum': 16.0}
  bundle 1: {'gke_worker_id': '1', 'jax_worker_id': '1', 'process_bounds': '1,1,2', 'host_bounds': '1,1,4', 'devices': 16, 'coords': '(0, 0, 1)..(1, 1, 1)', 'psum': 16.0}
=== subslice B (2x2x2, index=1, addrs=['10.4.8.40', '10.4.8.8']) ===
  bundle 0: {'gke_worker_id': '2', 'jax_worker_id': '0', 'process_bounds': '1,1,2', 'host_bounds': '1,1,4', 'devices': 16, 'coords': '(0, 0, 0)..(1, 1, 0)', 'psum': 16.0}
  bundle 1: {'gke_worker_id': '0', 'jax_worker_id': '1', 'process_bounds': '1,1,2', 'host_bounds': '1,1,4', 'devices': 16, 'coords': '(0, 0, 1)..(1, 1, 1)', 'psum': 16.0}
=== full slice (2x2x4) ===
  bundle 0: {'gke_worker_id': '0', 'jax_worker_id': '0', 'process_bounds': None, 'host_bounds': '1,1,4', 'devices': 32, 'coords': '(0, 0, 3)..(1, 1, 3)', 'psum': 32.0}
  bundle 1: {'gke_worker_id': '1', 'jax_worker_id': '1', 'process_bounds': None, 'host_bounds': '1,1,4', 'devices': 32, 'coords': '(0, 0, 1)..(1, 1, 1)', 'psum': 32.0}
  bundle 2: {'gke_worker_id': '2', 'jax_worker_id': '2', 'process_bounds': None, 'host_bounds': '1,1,4', 'devices': 32, 'coords': '(0, 0, 2)..(1, 1, 2)', 'psum': 32.0}
  bundle 3: {'gke_worker_id': '3', 'jax_worker_id': '3', 'process_bounds': None, 'host_bounds': '1,1,4', 'devices': 32, 'coords': '(0, 0, 0)..(1, 1, 0)', 'psum': 32.0}

4. Multi-host tpu7x 2x2x4 (TorchTPU 16-rank subslices, RAY_TPU_RESOURCE_PER_CHIP=2)

With RAY_TPU_RESOURCE_PER_CHIP=2 set on head and worker containers and rayStartParams.resources: '"{\"TPU\": 8}"' on the worker group:

Test script (test_tpu7x_2x2x4_torchtpu.py):

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:

2026-11-02 18:51:02,273	INFO tpu.py:1593 -- Running TPU subslice topology discovery for 2x2x4 (v7x)...
2026-11-02 18:51:07,788	INFO tpu.py:1725 -- Subslice discovery complete for slice 'v7x-multihost-group-0' (2x2x4). Found 4 workers.
=== subslice A (2x2x2, index=0, addrs=['10.4.8.106', '10.4.8.74'], bundles=16) ===
  rank 0: {'rank': 0, 'host_rank': 0, 'local_rank': 0, 'gke_worker_id': '2', 'visible_chips': '0', 'allreduce_sum': 136.0, 'grad_norm': 65630.2109}
  rank 8: {'rank': 8, 'host_rank': 1, 'local_rank': 0, 'gke_worker_id': '0', 'visible_chips': '0', 'allreduce_sum': 136.0, 'grad_norm': 65630.2109}
=== subslice B (2x2x2, index=1, addrs=['10.4.8.42', '10.4.8.10'], bundles=16) ===
  rank 0: {'rank': 0, 'host_rank': 0, 'local_rank': 0, 'gke_worker_id': '1', 'visible_chips': '0', 'allreduce_sum': 136.0, 'grad_norm': 65630.2109}
  rank 8: {'rank': 8, 'host_rank': 1, 'local_rank': 0, 'gke_worker_id': '3', 'visible_chips': '0', 'allreduce_sum': 136.0, 'grad_norm': 65630.2109}

@ryanaoleary ryanaoleary added the go add ONLY when ready to merge, run all tests label Oct 2, 2026
@github-actions

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 16, 2026
@ryanaoleary

Copy link
Copy Markdown
Contributor Author

not stale, I will fix conflicts and I believe @spencer-p was reviewing the diff after their approval since I refactored a bit

@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 17, 2026
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 November 3, 2026 03:35
@ryanaoleary
ryanaoleary enabled auto-merge (squash) November 3, 2026 20:05
@ryanaoleary
ryanaoleary merged commit fb5b554 into ray-project:master Nov 3, 2026
6 of 7 checks passed
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]>
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