Skip to content

[Train][TPU] Sort TPU workers within each slice by host worker ID and device ID - #67575

Merged
ryanaoleary merged 4 commits into
ray-project:masterfrom
ryanaoleary:train-tpu-local-rank-sort
Nov 5, 2026
Merged

ryanaoleary merged 4 commits into
ray-project:masterfrom
ryanaoleary:train-tpu-local-rank-sort

Conversation

@ryanaoleary

@ryanaoleary ryanaoleary commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

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:

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

Related issue number

Contributes to [Core][Train] Support Torch runtime with TPUs (ray#64055).
Related to Set TPU_VISIBLE_DEVICES alongside TPU_VISIBLE_CHIPS for per-device MPMD (ray#67029), Order subslice hosts by physical topology and pin slice bundles to worker IDs (ray#66029), and Wait for worker TPU VFIO devices before distributed init (ray#67756).

Checks

@ryanaoleary

ryanaoleary commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Manual Testing Steps

Step 1: Deploy a TPU v7x RayCluster (2x2x1, 8 logical TPU devices per node with RAY_TPU_RESOURCE_PER_CHIP=2)

apiVersion: ray.io/v1
kind: RayCluster
metadata:
  name: ray-tpu-rank-sort
spec:
  headGroupSpec:
    rayStartParams:
      num-cpus: "0"
    template:
      spec:
        containers:
          - name: ray-head
            image: us-central1-docker.pkg.dev/tpu-vm-gke-testing/ray-torchtpu/ray-torchtpu:latest
            env:
              - name: RAY_TPU_RESOURCE_PER_CHIP
                value: "2"
  workerGroupSpecs:
    - groupName: tpu-group
      replicas: 2
      numOfHosts: 1
      rayStartParams:
        resources: '"{\"TPU\": 8}"'
      template:
        spec:
          nodeSelector:
            cloud.google.com/gke-tpu-accelerator: tpu7x
            cloud.google.com/gke-tpu-topology: 2x2x1
          containers:
            - name: ray-worker
              image: us-central1-docker.pkg.dev/tpu-vm-gke-testing/ray-torchtpu/ray-torchtpu:latest
              env:
                - name: RAY_TPU_RESOURCE_PER_CHIP
                  value: "2"
              resources:
                limits:
                  google.com/tpu: "4"
                requests:
                  google.com/tpu: "4"

Step 2: Apply PR Changes to Cluster Pods

Patch worker_group.py from this PR (stacked with tpu.py and utils.py from Set TPU_VISIBLE_DEVICES alongside TPU_VISIBLE_CHIPS (ray#67029) so TPU_VISIBLE_DEVICES is exported for sub-host workers):

for pod in $(kubectl get pods -l ray.io/cluster=ray-tpu-rank-sort -o jsonpath='{.items[*].metadata.name}'); do
  kubectl cp python/ray/train/v2/_internal/execution/worker_group/worker_group.py \
    "$pod:$(kubectl exec "$pod" -- python3 -c 'import ray.train.v2._internal.execution.worker_group.worker_group as m; print(m.__file__)')"
done

Step 3: Run End-to-End Verification Script

Save the following script as run_tpu_worker_rank_sort_manual_test.py:

import contextlib
import os
import sys
import time
import types
import numpy as np
import ray
from ray.train import RunConfig, ScalingConfig
from ray.train.torch import TorchTrainer
from ray.train.v2.api.data_parallel_trainer import DataParallelTrainer
from ray.train.v2.jax import JaxTrainer
from ray.train.v2._internal.execution.callback import WorkerGroupCallback
from ray.train.v2._internal.execution.worker_group import WorkerGroup

SCRAMBLED_BUNDLE_ORDER = [5, 2, 7, 0, 4, 1, 6, 3]
SCRAMBLED_4WORKER_BUNDLES = [2, 0, 3, 1]


class ScrambleBundleOrderCallback(WorkerGroupCallback):
    """Forces initial worker creation across placement group bundles in a specified
    scrambled order and logs worker order before and after _assign_worker_ranks.
    """

    def __init__(self, label: str, bundle_order: list[int]):
        self.label = label
        self.bundle_order = list(bundle_order)

    @contextlib.contextmanager
    def on_worker_group_start(self):
        orig_create_workers = WorkerGroup._create_workers
        orig_assign_worker_ranks = WorkerGroup._assign_worker_ranks
        label = self.label
        bundle_order = self.bundle_order

        def wrapped_create_workers(
            wg_self,
            num_workers,
            placement_group,
            resources_per_worker,
            placement_group_bundle_indices=None,
            starting_world_rank=0,
            world_size=None,
            replica_group_size=None,
        ):
            if placement_group_bundle_indices is None and num_workers == len(bundle_order):
                placement_group_bundle_indices = bundle_order
            return orig_create_workers(
                wg_self,
                num_workers,
                placement_group,
                resources_per_worker,
                placement_group_bundle_indices=placement_group_bundle_indices,
                starting_world_rank=starting_world_rank,
                world_size=world_size,
                replica_group_size=replica_group_size,
            )

        @staticmethod
        def wrapped_assign_worker_ranks(
            workers,
            starting_world_rank=0,
            world_size=None,
            replica_group_size=None,
        ):
            unsorted_tpu_ids = [w.metadata.accelerator_ids.get("TPU", []) for w in workers]
            print(
                f"[{label} Controller BEFORE _assign_worker_ranks] "
                f"unsorted accelerator_ids['TPU'] = {unsorted_tpu_ids}",
                flush=True,
            )
            sorted_workers = orig_assign_worker_ranks(
                workers, starting_world_rank, world_size, replica_group_size
            )
            sorted_summary = [
                (
                    w.distributed_context.world_rank,
                    w.distributed_context.local_rank,
                    w.metadata.accelerator_ids.get("TPU", []),
                )
                for w in sorted_workers
            ]
            print(
                f"[{label} Controller AFTER _assign_worker_ranks] "
                f"(world_rank, local_rank, accelerator_ids['TPU']) = {sorted_summary}",
                flush=True,
            )
            return sorted_workers

        WorkerGroup._create_workers = wrapped_create_workers
        WorkerGroup._assign_worker_ranks = wrapped_assign_worker_ranks
        try:
            yield
        finally:
            WorkerGroup._create_workers = orig_create_workers
            WorkerGroup._assign_worker_ranks = orig_assign_worker_ranks


# Test 1: Single-host full-slice scrambled scheduling (8 workers x TPU:1) + DLRM-DCNv2 SparseCoreTrainPipeline
def train_test1(cfg):
    sys.modules.setdefault("tensorflow", types.ModuleType("tensorflow"))
    import torch
    from torch import nn
    import torch.distributed as dist
    from torch_tpu_embedding.datasets.dataloader import PrefetchDataLoader
    from torch_tpu_embedding.datasets.input_preprocessing import SparseCoreInputPreprocessor
    from torch_tpu_embedding.examples.models.dlrm import config as dlrm_config
    from torch_tpu_embedding.examples.models.dlrm import dataset as dlrm_dataset
    from torch_tpu_embedding.examples.models.dlrm.model import DLRM
    from torch_tpu_embedding.modules.embedding_configs import SparseCoreEmbeddingConfig
    from torch_tpu_embedding.pipelining.train_pipeline import SparseCoreTrainPipeline
    from torchrec.modules.embedding_configs import EmbeddingBagConfig, PoolingType

    os.environ.setdefault("TORCH_LOGS", "-all")
    ctx = ray.train.get_context()
    world_rank = ctx.get_world_rank()
    local_rank = ctx.get_local_rank()
    node_rank = ctx.get_node_rank()
    world_size = ctx.get_world_size()

    ray_tpu_ids = ray.get_runtime_context().get_accelerator_ids().get("TPU", [])
    vis_devs = os.environ.get("TPU_VISIBLE_DEVICES", "<unset>")
    vis_chips = os.environ.get("TPU_VISIBLE_CHIPS", "<unset>")
    assert world_rank == local_rank == int(vis_devs)

    if not dist.is_initialized():
        dist.init_process_group("tpu")

    device = ray.train.torch.get_device()
    _ = torch.zeros(1, device=device)

    line = (
        f"[Test 1 Worker] world_rank={world_rank} local_rank={local_rank} "
        f"node_rank={node_rank} accelerator_ids['TPU']={ray_tpu_ids} "
        f"TPU_VISIBLE_DEVICES={vis_devs} TPU_VISIBLE_CHIPS={vis_chips}"
    )
    gathered = [None] * world_size
    dist.all_gather_object(gathered, line)
    if world_rank == 0:
        for l in gathered:
            print(l, flush=True)

    num_steps = 30
    vocab_sizes = [65536] * 26
    embedding_size = 64
    d_cfg = dlrm_config.Config(
        vocab_sizes=vocab_sizes,
        multi_hot_sizes=dlrm_config.MULTI_HOT_SIZES,
        global_batch_size=2048,
        local_batch_size=2048 // world_size,
        embedding_size=embedding_size,
        bottom_mlp_dims=[512, 256, embedding_size],
        top_mlp_dims=[1024, 1024, 512, 256, 1],
        num_steps=num_steps,
        log_frequency=10,
        loss_reset_frequency=10,
        dcn_layers=3,
        projection_dim=512,
        learning_rate=0.01,
        rank=world_rank,
        world_size=world_size,
        device=device,
        num_sc_per_device=2,
        max_ids_per_partition=8192,
        max_unique_ids_per_partition=4096,
        optimizer_type="adagrad",
        use_synthetic_data=True,
        constant_init=True,
        auto_stack=True,
    )
    tables = [
        SparseCoreEmbeddingConfig(
            config=EmbeddingBagConfig(
                name=f"{i}",
                embedding_dim=embedding_size,
                num_embeddings=v,
                feature_names=[f"{i}"],
                pooling=PoolingType.SUM,
            ),
            max_ids_per_partition=8192,
            max_unique_ids_per_partition=4096,
            suggested_coo_buffer_size_per_device=131072,
        )
        for i, v in enumerate(vocab_sizes)
    ]
    torch.manual_seed(42 + world_rank)
    model = DLRM(d_cfg, tables).to(device)
    model.embedding_layer._use_custom_embedding_formatting = False
    model.init_embedding_optimizers(d_cfg.learning_rate)
    preprocessor = SparseCoreInputPreprocessor(
        tables=tables,
        batch_size=d_cfg.local_batch_size,
        global_device_count=d_cfg.world_size,
        num_sc_per_device=d_cfg.num_sc_per_device,
        allow_id_dropping=d_cfg.allow_id_dropping,
        auto_stack=d_cfg.auto_stack,
        activation_mem_bytes_limit=d_cfg.activation_mem_bytes_limit,
    )
    emb_param_set = set(model.embedding_layer.parameters())
    dense_params = [p for p in model.parameters() if p not in emb_param_set and p.requires_grad]
    dense_opt = torch.optim.Adagrad(dense_params, lr=d_cfg.learning_rate, initial_accumulator_value=0.1, eps=1e-8)
    pipeline = SparseCoreTrainPipeline(model=model, optimizer=dense_opt, criterion=nn.BCEWithLogitsLoss(), compile=True)
    batches = dlrm_dataset.get_batches(
        d_cfg.local_batch_size, d_cfg.vocab_sizes, d_cfg.multi_hot_sizes, num_steps, torch.device("cpu")
    )

    step_times_ms, losses = [], []
    with PrefetchDataLoader(dataloader=batches, preprocessor=preprocessor, device=device, max_steps=num_steps) as pf:
        t_prev = time.perf_counter()
        for _, loss in enumerate(pipeline.iterate(pf)):
            torch.accelerator.synchronize()
            t_now = time.perf_counter()
            step_times_ms.append((t_now - t_prev) * 1000.0)
            t_prev = t_now
            losses.append(float(loss.item()))

    steady = np.array(step_times_ms[5:-2], dtype=np.float64)
    if world_rank == 0:
        print(
            f"[Test 1 DLRM-DCNv2 30 Steps] total_steps={len(step_times_ms)} "
            f"steady_mean={np.mean(steady):.4f} ms | steady_p50={np.percentile(steady, 50):.4f} ms | "
            f"steady_min={np.min(steady):.4f} ms | steady_p99={np.percentile(steady, 99):.4f} ms | "
            f"loss[0]={losses[0]:.6f} -> loss[-1]={losses[-1]:.6f}",
            flush=True,
        )


# Test 2A: Multi-device-per-worker (4 workers x TPU:2)
def train_test2a_multi_device(cfg):
    os.environ["JAX_PLATFORMS"] = "tpu"
    import jax
    import jax.numpy as jnp

    ctx = ray.train.get_context()
    world_rank, local_rank, world_size = ctx.get_world_rank(), ctx.get_local_rank(), ctx.get_world_size()
    ray_tpu_ids = sorted(ray.get_runtime_context().get_accelerator_ids().get("TPU", []), key=int)
    vis_devs = os.environ.get("TPU_VISIBLE_DEVICES", "<unset>")
    vis_chips = os.environ.get("TPU_VISIBLE_CHIPS", "<unset>")
    chip_bounds = os.environ.get("TPU_CHIPS_PER_HOST_BOUNDS", "<unset>")
    host_bounds = os.environ.get("TPU_HOST_BOUNDS", "<unset>")
    assert vis_devs == f"{2 * local_rank},{2 * local_rank + 1}" and vis_chips == str(local_rank)

    local_devs = jax.local_devices()
    psum_val = jax.pmap(lambda x: jax.lax.psum(x, "i"), axis_name="i")(
        jnp.ones(len(local_devs), dtype=jnp.float32) * (local_rank + 1)
    )
    print(
        f"[Test 2A Worker] world_rank={world_rank}/{world_size} local_rank={local_rank} "
        f"accelerator_ids['TPU']={ray_tpu_ids} TPU_VISIBLE_DEVICES={vis_devs} "
        f"TPU_VISIBLE_CHIPS={vis_chips} TPU_CHIPS_PER_HOST_BOUNDS={chip_bounds} "
        f"TPU_HOST_BOUNDS={host_bounds} jax_local_devices={len(local_devs)} "
        f"chip_psum={[float(v) for v in psum_val]}",
        flush=True,
    )


# Test 2B: JaxTrainer on single-host tpu7x 2x2x1 (8 devices)
def train_test2b_jax_trainer(cfg):
    import jax
    import jax.numpy as jnp

    ctx = ray.train.get_context()
    world_rank, local_rank, world_size = ctx.get_world_rank(), ctx.get_local_rank(), ctx.get_world_size()
    vis_devs = os.environ.get("TPU_VISIBLE_DEVICES", "<unset>")
    vis_chips = os.environ.get("TPU_VISIBLE_CHIPS", "<unset>")
    total_devs = jax.device_count()
    local_devs = jax.local_device_count()

    x = jnp.arange(1, local_devs + 1, dtype=jnp.float32) + (world_rank * local_devs)
    psum_out = jax.pmap(lambda v: jax.lax.psum(v, "d"), axis_name="d")(x)
    expected_sum = float(total_devs * (total_devs + 1) // 2)
    actual_sum = float(psum_out[0])
    assert actual_sum == expected_sum

    print(
        f"[Test 2B JaxTrainer] world_rank={world_rank}/{world_size} local_rank={local_rank} "
        f"TPU_VISIBLE_DEVICES={vis_devs} TPU_VISIBLE_CHIPS={vis_chips} "
        f"jax.device_count()={total_devs} jax.local_device_count()={local_devs} "
        f"pmap_psum={actual_sum} (expected {expected_sum})",
        flush=True,
    )


if __name__ == "__main__":
    os.environ["RAY_DEDUP_LOGS"] = "0"
    ray.init(address="auto", runtime_env={"env_vars": {"RAY_TPU_RESOURCE_PER_CHIP": "2"}})

    print("=" * 80, flush=True)
    print("TEST 1: Single-Host Full-Slice Scrambled Scheduling Stress Test (8 tpu7x Workers)", flush=True)
    print("=" * 80, flush=True)
    res_1 = TorchTrainer(
        train_loop_per_worker=train_test1,
        scaling_config=ScalingConfig(
            num_workers=8, use_tpu=True, topology="2x2x1", accelerator_type="TPU-V7X", resources_per_worker={"TPU": 1}
        ),
        run_config=RunConfig(
            name="test1_single_host_scrambled",
            callbacks=[ScrambleBundleOrderCallback("Test 1", SCRAMBLED_BUNDLE_ORDER)],
        ),
    ).fit()
    print(f"[Test 1 PASS] Final metrics: {res_1.metrics}", flush=True)

    print("=" * 80, flush=True)
    print("TEST 2A: Single-Host Multi-Device-Per-Worker (4 Workers x TPU:2 -> 0,1 / 2,3 / 4,5 / 6,7)", flush=True)
    print("=" * 80, flush=True)
    res_2a = DataParallelTrainer(
        train_loop_per_worker=train_test2a_multi_device,
        scaling_config=ScalingConfig(
            num_workers=4, use_tpu=True, topology="2x2x1", accelerator_type="TPU-V7X", resources_per_worker={"TPU": 2}
        ),
        run_config=RunConfig(
            name="test2a_multi_device_per_worker",
            callbacks=[ScrambleBundleOrderCallback("Test 2A", SCRAMBLED_4WORKER_BUNDLES)],
        ),
    ).fit()
    print(f"[Test 2A PASS] Final metrics: {res_2a.metrics}\n", flush=True)

    print("=" * 80, flush=True)
    print("TEST 2B: JaxTrainer on Single-Host tpu7x 2x2x1 (8 Devices, TPU_VISIBLE_DEVICES=0..7)", flush=True)
    print("=" * 80, flush=True)
    res_2b = JaxTrainer(
        train_loop_per_worker=train_test2b_jax_trainer,
        scaling_config=ScalingConfig(
            num_workers=1, use_tpu=True, topology="2x2x1", accelerator_type="TPU-V7X", resources_per_worker={"TPU": 8}
        ),
        run_config=RunConfig(name="test2b_jax_single_slice"),
    ).fit()
    print(f"[Test 2B Single-Slice PASS] Final metrics: {res_2b.metrics}", flush=True)

Copy the script to the head pod and execute:

HEAD_POD=$(kubectl get pods -l ray.io/node-type=head,ray.io/cluster=ray-tpu-rank-sort -o jsonpath='{.items[0].metadata.name}')
kubectl cp run_tpu_worker_rank_sort_manual_test.py "$HEAD_POD:/tmp/run_tpu_worker_rank_sort_manual_test.py"
kubectl exec "$HEAD_POD" -- python3 -u /tmp/run_tpu_worker_rank_sort_manual_test.py

Step 4: Results

1. Single-Host Full-Slice Scrambled Scheduling (8 × TPU: 1 on tpu7x 2x2x1, DLRM-DCNv2 SparseCoreTrainPipeline)

================================================================================
TEST 1: Single-Host Full-Slice Scrambled Scheduling Stress Test (8 tpu7x Workers)
================================================================================
(TrainController pid=5909) [Test 1 Controller BEFORE _assign_worker_ranks] unsorted accelerator_ids['TPU'] = [['5'], ['2'], ['7'], ['0'], ['4'], ['1'], ['6'], ['3']]
(TrainController pid=5909) [Test 1 Controller AFTER _assign_worker_ranks] (world_rank, local_rank, accelerator_ids['TPU']) = [(0, 0, ['0']), (1, 1, ['1']), (2, 2, ['2']), (3, 3, ['3']), (4, 4, ['4']), (5, 5, ['5']), (6, 6, ['6']), (7, 7, ['7'])]
(TrainController pid=5909) Started training worker group of size 8: 
(TrainController pid=5909) - (ip=10.228.2.9, pid=13809) world_rank=0, local_rank=0, node_rank=0
(TrainController pid=5909) - (ip=10.228.2.9, pid=13807) world_rank=1, local_rank=1, node_rank=0
(TrainController pid=5909) - (ip=10.228.2.9, pid=13806) world_rank=2, local_rank=2, node_rank=0
(TrainController pid=5909) - (ip=10.228.2.9, pid=13811) world_rank=3, local_rank=3, node_rank=0
(TrainController pid=5909) - (ip=10.228.2.9, pid=13813) world_rank=4, local_rank=4, node_rank=0
(TrainController pid=5909) - (ip=10.228.2.9, pid=13808) world_rank=5, local_rank=5, node_rank=0
(TrainController pid=5909) - (ip=10.228.2.9, pid=13812) world_rank=6, local_rank=6, node_rank=0
(TrainController pid=5909) - (ip=10.228.2.9, pid=13810) world_rank=7, local_rank=7, node_rank=0
(RayTrainWorker pid=13809, ip=10.228.2.9) [Test 1 Worker] world_rank=0 local_rank=0 node_rank=0 accelerator_ids['TPU']=['0'] TPU_VISIBLE_DEVICES=0 TPU_VISIBLE_CHIPS=0
(RayTrainWorker pid=13809, ip=10.228.2.9) [Test 1 Worker] world_rank=1 local_rank=1 node_rank=0 accelerator_ids['TPU']=['1'] TPU_VISIBLE_DEVICES=1 TPU_VISIBLE_CHIPS=0
(RayTrainWorker pid=13809, ip=10.228.2.9) [Test 1 Worker] world_rank=2 local_rank=2 node_rank=0 accelerator_ids['TPU']=['2'] TPU_VISIBLE_DEVICES=2 TPU_VISIBLE_CHIPS=1
(RayTrainWorker pid=13809, ip=10.228.2.9) [Test 1 Worker] world_rank=3 local_rank=3 node_rank=0 accelerator_ids['TPU']=['3'] TPU_VISIBLE_DEVICES=3 TPU_VISIBLE_CHIPS=1
(RayTrainWorker pid=13809, ip=10.228.2.9) [Test 1 Worker] world_rank=4 local_rank=4 node_rank=0 accelerator_ids['TPU']=['4'] TPU_VISIBLE_DEVICES=4 TPU_VISIBLE_CHIPS=2
(RayTrainWorker pid=13809, ip=10.228.2.9) [Test 1 Worker] world_rank=5 local_rank=5 node_rank=0 accelerator_ids['TPU']=['5'] TPU_VISIBLE_DEVICES=5 TPU_VISIBLE_CHIPS=2
(RayTrainWorker pid=13809, ip=10.228.2.9) [Test 1 Worker] world_rank=6 local_rank=6 node_rank=0 accelerator_ids['TPU']=['6'] TPU_VISIBLE_DEVICES=6 TPU_VISIBLE_CHIPS=3
(RayTrainWorker pid=13809, ip=10.228.2.9) [Test 1 Worker] world_rank=7 local_rank=7 node_rank=0 accelerator_ids['TPU']=['7'] TPU_VISIBLE_DEVICES=7 TPU_VISIBLE_CHIPS=3
(RayTrainWorker pid=13809, ip=10.228.2.9) [Test 1 DLRM-DCNv2 30 Steps] total_steps=30 steady_mean=6.1043 ms | steady_p50=5.9054 ms | steady_min=5.1178 ms | steady_p99=7.3474 ms | loss[0]=0.693840 -> loss[-1]=0.693942
[Test 1 PASS] Final metrics: None

2. Multi-Device-Per-Worker (4 × TPU: 2 on tpu7x 2x2x1) and JaxTrainer (1 × TPU: 8)

================================================================================
TEST 2A: Single-Host Multi-Device-Per-Worker (4 Workers x TPU:2 -> 0,1 / 2,3 / 4,5 / 6,7)
================================================================================
(TrainController pid=6442) [Test 2A Controller BEFORE _assign_worker_ranks] unsorted accelerator_ids['TPU'] = [['4', '5'], ['0', '1'], ['6', '7'], ['2', '3']]
(TrainController pid=6442) [Test 2A Controller AFTER _assign_worker_ranks] (world_rank, local_rank, accelerator_ids['TPU']) = [(0, 0, ['0', '1']), (1, 1, ['2', '3']), (2, 2, ['4', '5']), (3, 3, ['6', '7'])]
(TrainController pid=6442) Started training worker group of size 4: 
(TrainController pid=6442) - (ip=10.228.2.9, pid=23959) world_rank=0, local_rank=0, node_rank=0
(TrainController pid=6442) - (ip=10.228.2.9, pid=23960) world_rank=1, local_rank=1, node_rank=0
(TrainController pid=6442) - (ip=10.228.2.9, pid=23957) world_rank=2, local_rank=2, node_rank=0
(TrainController pid=6442) - (ip=10.228.2.9, pid=23958) world_rank=3, local_rank=3, node_rank=0
(RayTrainWorker pid=23959, ip=10.228.2.9) [Test 2A Worker] world_rank=0/4 local_rank=0 accelerator_ids['TPU']=['0', '1'] TPU_VISIBLE_DEVICES=0,1 TPU_VISIBLE_CHIPS=0 TPU_CHIPS_PER_HOST_BOUNDS=1,1,1 TPU_HOST_BOUNDS=1,1,1 jax_local_devices=2 chip_psum=[2.0, 2.0]
(RayTrainWorker pid=23960, ip=10.228.2.9) [Test 2A Worker] world_rank=1/4 local_rank=1 accelerator_ids['TPU']=['2', '3'] TPU_VISIBLE_DEVICES=2,3 TPU_VISIBLE_CHIPS=1 TPU_CHIPS_PER_HOST_BOUNDS=1,1,1 TPU_HOST_BOUNDS=1,1,1 jax_local_devices=2 chip_psum=[4.0, 4.0]
(RayTrainWorker pid=23957, ip=10.228.2.9) [Test 2A Worker] world_rank=2/4 local_rank=2 accelerator_ids['TPU']=['4', '5'] TPU_VISIBLE_DEVICES=4,5 TPU_VISIBLE_CHIPS=2 TPU_CHIPS_PER_HOST_BOUNDS=1,1,1 TPU_HOST_BOUNDS=1,1,1 jax_local_devices=2 chip_psum=[6.0, 6.0]
[Test 2A PASS] Final metrics: None
================================================================================
TEST 2B: JaxTrainer on Single-Host tpu7x 2x2x1 (8 Devices, TPU_VISIBLE_DEVICES=0..7)
================================================================================
(TrainController pid=6878) Started training worker group of size 1: 
(TrainController pid=6878) - (ip=10.228.7.8, pid=10058) world_rank=0, local_rank=0, node_rank=0
(RayTrainWorker pid=10058, ip=10.228.7.8) [Test 2B JaxTrainer] world_rank=0/1 local_rank=0 TPU_VISIBLE_DEVICES=<unset> TPU_VISIBLE_CHIPS=<unset> jax.device_count()=8 jax.local_device_count()=8 pmap_psum=36.0 (expected 36.0)
[Test 2B Single-Slice PASS] Final metrics: None

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

@ryanaoleary

Copy link
Copy Markdown
Contributor Author

TPU v7x Performance Impact

Benchmarks on GKE TPU v7x (2x2x1, 8 TPU devices per host) comparing sorted vs. unsorted worker ranks:

1. Per-Host Rank Contiguity (2 Hosts, 16 Workers)

TorchRec's intra-node process groups group consecutive blocks of 8 global ranks. Grouping each host's workers into contiguous ranks (0..7 on host 0, 8..15 on host 1) keeps intra-node collectives on local TPU tray interconnect (ICI) instead of crossing hosts over the network (DCN):

Workload (16 Workers across 2 Hosts) Contiguous Ranks (Local ICI) Interleaved Ranks (Cross-Host DCN) Impact of Unsorted Ranks
Intra-node 16 MB all_to_all_single 0.49 ms 6.74 ms 13.8× slower
Intra-node 16 MB all_reduce 0.54 ms 4.67 ms 8.7× slower
TorchRec TWRW Training Step (batch_size=4096) 27.40 ms/step 41.06 ms/step +49.9% slower step time

2. Intra-Host Device Ordering (1 Host, 8 Workers)

When TPU_VISIBLE_DEVICES is set per worker (ray#67029), sorting workers on each host by assigned device ID maps local_rank 0..7 to sequential TPU devices 0..7 instead of scrambled device order:

Workload (8 Workers on 1 Host) Sorted Devices (0..7) Scrambled Devices (5, 2, 7, 0, ...) Impact of Unsorted Ranks
TorchRec DLRM-DCNv2 Training Step (mean) 6.26 ms/step 7.50 ms/step +19.7% slower
TorchRec DLRM-DCNv2 Training Step (p50) 6.18 ms/step 7.78 ms/step +25.9% slower

@ryanaoleary
ryanaoleary marked this pull request as ready for review October 31, 2026 01:48
@ryanaoleary
ryanaoleary requested a review from a team as a code owner October 31, 2026 01:48
@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!

@ryanaoleary
ryanaoleary requested review from a team as code owners October 31, 2026 01:48
@ray-gardener ray-gardener Bot added train Ray Train Related Issue community-contribution Contributed by the community labels Oct 31, 2026
@ryanaoleary ryanaoleary added the go add ONLY when ready to merge, run all tests label Nov 5, 2026
@ryanaoleary
ryanaoleary merged commit 9e3dc03 into ray-project:master Nov 5, 2026
7 checks passed
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 go add ONLY when ready to merge, run all tests train Ray Train Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants