← Back to Pull requests

[single_controller] feat: discover TPU resource in Ray #7849

Merged
askhat-g merged 5 files (189 lines) on Sep 20, 2026 03:09 UTC
View on GitHub
askhat-g askhat-g commented on Sep 11, 2026 21:53 UTC
Author

What does this PR do?

Makes Ray resource discovery and worker placement ask the active platform instead of
assuming NVIDIA, and fixes two places that assume a shape Ray does not guarantee.

This is the in-tree half of out-of-tree platform support. PlatformTPU itself lives in
verl-hardware-plugin#18
(merged); until the call sites here land, that plugin is inert because verl never consults it.

Checklist Before Starting

  • Search for similar PRs: https://github.com/verl-project/verl/pulls?q=is%3Apr+single_controller+platform+resource

  • Format the PR title as [{modules}] {type}: {description}
  • Test

    tests/single_controller/test_device_agnostic_resources_on_cpu.py (new, 14 cases) covers both
    bug fixes and the colocation cap with a stub platform. Runs on CPU, no accelerator and no Ray
    cluster required. Eight of the fourteen fail against current main; the other six are
    regression guards for existing GPU/NPU behaviour and pass either way.

    pytest tests/single_controller/test_device_agnostic_resources_on_cpu.py   # 14 passed
    ruff check verl/ && ruff format --check verl/                             # clean
    python tests/special_sanity/check_license.py --directories verl tests     # exit 0
    python tests/special_sanity/check_device_api_usage.py --directory verl    # exit 0
    

    Broader tests/single_controller/ + tests/plugin/ failure set is byte-identical before and
    after this change. Cross-checked against the merged plugin with VERL_PLATFORM=tpu: the
    colocation cap applies and the TPU branch resolves.

    API and Usage Example

    No user-facing API change. Two new PlatformBase hooks, both defaulting to current behaviour:

    class PlatformBase:
        def supports_colocated_worker_groups(self) -> bool:
            return True   # False caps colocation at one WorkerGroup
    
        def ray_local_rank_override(self) -> Optional[str]:
            return None   # None keeps Ray's get_accelerator_ids() path
    

    Design & Code Changes

    New hooks

  • supports_colocated_worker_groups() — applied in both RayResourcePool and

  • ResourcePoolManager so the bundle CPU count matches the pool actually created. Left at 3
    for an exclusive device, the placement group requests 3 CPUs per chip and never schedules.
  • ray_local_rank_override() — for platforms whose devices Ray does not enumerate via

  • get_accelerator_ids().

    get_worker_env_vars was previously a third hook. Per review it is no longer on
    PlatformBase: RayWorkerGroup calls it behind an explicit device_name == "tpu" branch, so
    the only platform needing placement-group-derived mesh environment is the only one carrying it.

    Deferred, not silently dropped

  • is_tpu_available in verl/utils/device.py — unshippable out-of-tree. verl/__init__.py

  • imports verl.utils.device at line 33, freezing the module-level flag; entry-point plugins
    load at line 74, so torch_tpu is imported strictly after the flag is evaluated and the flag
    is always False, including on a real TPU host.
  • The TPU early return in set_numa_affinity — belongs behind a vendor-neutral

  • supports_numa_affinity() hook paired with a plugin change. The NVML failure it avoided is
    already caught and non-fatal.

    Docs: docs/hardware/multi_chip_support.rst moves TPU from the built-in list to the
    verl-hardware-plugin list.

    Checklist Before Submitting

  • Read the Contribute Guide.

  • Apply pre-commit checks — pre-commit not available in this environment; ruff check

  • and ruff format --check run directly and clean, plus the tests/special_sanity/ hooks.
  • Add / Update the documentation.

  • Add unit test(s) — tests/single_controller/test_device_agnostic_resources_on_cpu.py,

  • CPU-only so it runs in existing CI.
  • Send a message in the ci-request channel.

  • Not related to the recipe submodule.
  • Diff: 189 lines (+179 / -10) across 5 files Reviewer: jialei777 Review duration: 11836m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.40) × (1 − Review Confidence (0.82)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.40 · 189 lines diff across 5 files
    0.40
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.79 · 5 substantive comment(s)
    0.79
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    81%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.314
    Real PR Conversation Timeline
    28 items
    CLAassistant CLAassistant commented on Sep 11, 2026 21:53 UTC
    Contributor

    ![CLA assistant check](https://cla-assistant.io/verl-project/verl?pullRequest=7849) <br/>Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.<br/><sub>You have signed the CLA already but the status is still pending? Let us recheck it.</sub>

    vlasenkoalexey vlasenkoalexey commented on code on Sep 14, 2026 23:12 UTC
    Code Review
    verl/plugin/platform/platform_tpu.py:1
    @@ -0,0 +1,433 @@
    +# Copyright (c) 2026 BAAI. All rights reserved.

    I'm not sure what Copyright (c) 2026 BAAI. All rights reserved. here means, previous new files were attributed to ByDance.

    Should all new added files be attributed to Google?

    vlasenkoalexey vlasenkoalexey commented on code on Sep 14, 2026 23:15 UTC
    Code Review
    verl/plugin/platform/platform_tpu.py:1
    @@ -0,0 +1,433 @@
    +# Copyright (c) 2026 BAAI. All rights reserved.
    +# Copyright (c) 2026 Google LLC. All rights reserved.
    +#
    +# Licensed under the Apache License, Version 2.0 (the "License");
    +# you may not use this file except in compliance with the License.
    +# You may obtain a copy of the License at
    +#
    +#     http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +"""Google TPU platform implementation.
    +
    +**Experimental: TPU support is under development and cannot run training end to end yet.**
    +This module registers the platform and provides the device abstraction plus the Ray resource
    +and worker-environment plumbing. The training engine, the generation engine and the
    +weight-transfer path are still to come.
    +
    +``torch_tpu`` reuses the NVIDIA device API surface, so most of ``PlatformCUDA`` works
    +unchanged. This class subclasses it and overrides device-specific environment configuration,
    +resource options, and memory management proxies.
    +"""
    +
    +import logging
    +import os
    +from typing import Any, Optional
    +
    +import ray
    +import torch
    +
    +from .platform_cuda import PlatformCUDA
    +from .platform_manager import PlatformRegistry
    +
    +logger = logging.getLogger(__file__)
    +logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
    +
    +
    +def _ensure_torch_tpu() -> bool:
    +    """Try to import torch_tpu, which registers the ``tpu_dist`` distributed backend.
    +
    +    Returns True if the TPU runtime is usable after the attempt.
    +    """
    +    if hasattr(torch, "tpu"):

    should it be if not hasattr ... return false?

    vlasenkoalexey vlasenkoalexey commented on code on Sep 14, 2026 23:15 UTC
    Code Review
    verl/plugin/platform/platform_tpu.py:1
    @@ -0,0 +1,433 @@
    +# Copyright (c) 2026 BAAI. All rights reserved.
    +# Copyright (c) 2026 Google LLC. All rights reserved.
    +#
    +# Licensed under the Apache License, Version 2.0 (the "License");
    +# you may not use this file except in compliance with the License.
    +# You may obtain a copy of the License at
    +#
    +#     http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +"""Google TPU platform implementation.
    +
    +**Experimental: TPU support is under development and cannot run training end to end yet.**
    +This module registers the platform and provides the device abstraction plus the Ray resource
    +and worker-environment plumbing. The training engine, the generation engine and the
    +weight-transfer path are still to come.
    +
    +``torch_tpu`` reuses the NVIDIA device API surface, so most of ``PlatformCUDA`` works
    +unchanged. This class subclasses it and overrides device-specific environment configuration,
    +resource options, and memory management proxies.
    +"""
    +
    +import logging
    +import os
    +from typing import Any, Optional
    +
    +import ray
    +import torch
    +
    +from .platform_cuda import PlatformCUDA
    +from .platform_manager import PlatformRegistry
    +
    +logger = logging.getLogger(__file__)
    +logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
    +
    +
    +def _ensure_torch_tpu() -> bool:
    +    """Try to import torch_tpu, which registers the ``tpu_dist`` distributed backend.
    +
    +    Returns True if the TPU runtime is usable after the attempt.
    +    """
    +    if hasattr(torch, "tpu"):
    +        return True
    +    try:
    +        import torch_tpu  # noqa: F401
    +
    +        return hasattr(torch, "tpu")

    should this be torch.tpu.is_available() instead or you want to import torch_tpu explicitly to trigger distributed init?

    vlasenkoalexey vlasenkoalexey commented on code on Sep 14, 2026 23:21 UTC
    Code Review
    verl/plugin/platform/platform_tpu.py:1
    @@ -0,0 +1,433 @@
    +# Copyright (c) 2026 BAAI. All rights reserved.
    +# Copyright (c) 2026 Google LLC. All rights reserved.
    +#
    +# Licensed under the Apache License, Version 2.0 (the "License");
    +# you may not use this file except in compliance with the License.
    +# You may obtain a copy of the License at
    +#
    +#     http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +"""Google TPU platform implementation.
    +
    +**Experimental: TPU support is under development and cannot run training end to end yet.**
    +This module registers the platform and provides the device abstraction plus the Ray resource
    +and worker-environment plumbing. The training engine, the generation engine and the
    +weight-transfer path are still to come.
    +
    +``torch_tpu`` reuses the NVIDIA device API surface, so most of ``PlatformCUDA`` works
    +unchanged. This class subclasses it and overrides device-specific environment configuration,
    +resource options, and memory management proxies.
    +"""
    +
    +import logging
    +import os
    +from typing import Any, Optional
    +
    +import ray
    +import torch
    +
    +from .platform_cuda import PlatformCUDA
    +from .platform_manager import PlatformRegistry
    +
    +logger = logging.getLogger(__file__)
    +logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
    +
    +
    +def _ensure_torch_tpu() -> bool:
    +    """Try to import torch_tpu, which registers the ``tpu_dist`` distributed backend.
    +
    +    Returns True if the TPU runtime is usable after the attempt.
    +    """
    +    if hasattr(torch, "tpu"):
    +        return True
    +    try:
    +        import torch_tpu  # noqa: F401
    +
    +        return hasattr(torch, "tpu")
    +    except Exception as e:
    +        logger.debug("The current machine has no torch.tpu, because: %s", e)
    +    return False
    +
    +
    +_ensure_torch_tpu()  # Attempt at module load time so availability checks are faster later
    +
    +# Base port for the TPU distributed slice builder mesh. Each local rank takes ``base + local_rank``.
    +TPU_PROCESS_BASE_PORT = 8471
    +
    +# TPU chip HBM capacities in bytes
    +HBM_BYTES_TPU_V5P = 95 * 1024 * 1024 * 1024  # 95 GB
    +HBM_BYTES_TPU_V6E = 32 * 1024 * 1024 * 1024  # 32 GB
    +HBM_BYTES_TPU_V7X = 192 * 1024 * 1024 * 1024  # 192 GB
    +
    +TPU_HBM_BYTES_MAP = {
    +    "v5p": HBM_BYTES_TPU_V5P,
    +    "v6e": HBM_BYTES_TPU_V6E,
    +    "v7x": HBM_BYTES_TPU_V7X,
    +}
    +
    +# Fallback HBM capacity when the chip generation cannot be determined.
    +HBM_BYTES_TPU_DEFAULT = HBM_BYTES_TPU_V6E
    +
    +# TPU default 3D mesh topology mappings by pod type or total chips
    +TPU_TOPOLOGY_MAP = {
    +    "v6e-32": "4,8,1",
    +    "v6e-8": "2,4,1",
    +    "v6e-4": "2,2,1",
    +    32: "4,8,1",
    +    8: "2,4,1",
    +    4: "2,2,1",
    +}
    +
    +
    +def get_tpu_chip_hbm_bytes() -> int:
    +    """Detects the TPU chip generation from Ray node labels or environment variables and returns its HBM capacity."""
    +    tpu_type = ""
    +
    +    # Query Ray cluster node labels for TPU resource type
    +    try:
    +        if ray.is_initialized():
    +            tpu_nodes = [node for node in ray.nodes() if "TPU" in node.get("Resources", {}) and node.get("Alive")]
    +            if tpu_nodes:
    +                labels = tpu_nodes[0].get("Labels", {})
    +                tpu_type = (labels.get("ray.io/accelerator-type") or labels.get("ray.io/tpu-pod-type") or "").lower()
    +    except Exception as e:
    +        logger.warning(f"Unable to query Ray node labels for TPU chip type: {e}")
    +
    +    # Fallback to environment variables
    +    if not tpu_type:
    +        tpu_type = (
    +            os.environ.get("TPU_ACCELERATOR_TYPE")
    +            or os.environ.get("ACCELERATOR_TYPE")
    +            or os.environ.get("TPU_TYPE")
    +            or ""
    +        ).lower()
    +
    +    for chip_gen, hbm_bytes in TPU_HBM_BYTES_MAP.items():
    +        if chip_gen in tpu_type:
    +            return hbm_bytes
    +
    +    logger.warning(f"Unable to determine TPU chip HBM bytes for tpu_type='{tpu_type}'. Returning -1.")
    +    return -1
    +
    +
    +class DummyTpuDeviceModule:
    +    """Fallback device module for CPU-only nodes and driver processes.
    +
    +    Provides no-op implementations for torch.tpu APIs on processes where torch_tpu is not imported
    +    or no TPU devices are attached.
    +    """
    +
    +    def is_available(self) -> bool:
    +        return False
    +
    +    def set_device(self, device_index: Any) -> None:
    +        pass
    +
    +    def current_device(self) -> int:
    +        return 0
    +
    +    def device_count(self) -> int:
    +        return 0
    +
    +    def synchronize(self) -> None:
    +        pass
    +
    +    def manual_seed(self, seed: int) -> None:
    +        torch.manual_seed(seed)
    +
    +    def manual_seed_all(self, seed: int) -> None:
    +        torch.manual_seed(seed)
    +
    +
    +class TPUDeviceModuleProxy:
    +    """Proxy wrapper for torch.tpu to emulate the PyTorch NVIDIA memory management APIs.
    +
    +    Provides default fallback implementations for memory tracking methods
    +    (e.g. memory_reserved, memory_allocated, get_device_properties) that are called throughout verl's codebase
    +    but not natively provided by torch_tpu.
    +    """
    +
    +    def __init__(self, original_module):
    +        self.__dict__["_original_module"] = original_module
    +
    +    def __getattr__(self, name):
    +        if name == "set_device":
    +            return self.set_device
    +
    +        if hasattr(self._original_module, name):
    +            return getattr(self._original_module, name)
    +
    +        if name == "memory_reserved":
    +            return lambda *args, **kwargs: 0
    +        elif name == "memory_allocated":
    +            return lambda *args, **kwargs: 0
    +        elif name == "max_memory_reserved":
    +            return lambda *args, **kwargs: 0
    +        elif name == "max_memory_allocated":
    +            return lambda *args, **kwargs: 0
    +        elif name == "reset_peak_memory_stats":
    +            return lambda *args, **kwargs: None
    +        elif name == "get_device_properties":
    +
    +            class DummyDeviceProperties:
    +                def __init__(self, total_memory=HBM_BYTES_TPU_DEFAULT):
    +                    self.total_memory = total_memory
    +                    self.name = "Google TPU"
    +                    self.major = 1
    +                    self.minor = 0
    +
    +            hbm_bytes = get_tpu_chip_hbm_bytes()
    +            total_mem = hbm_bytes if hbm_bytes > 0 else HBM_BYTES_TPU_DEFAULT
    +            return lambda *args, **kwargs: DummyDeviceProperties(total_memory=total_mem)
    +        elif name == "mem_get_info":
    +            hbm_bytes = get_tpu_chip_hbm_bytes()
    +            total_mem = hbm_bytes if hbm_bytes > 0 else HBM_BYTES_TPU_DEFAULT
    +            return lambda *args, **kwargs: (total_mem, total_mem)
    +
    +        raise AttributeError(f"'TPUDeviceModuleProxy' object has no attribute '{name}'")
    +
    +    def __setattr__(self, name, value):
    +        if name.startswith("_"):
    +            super().__setattr__(name, value)
    +        else:
    +            setattr(self._original_module, name, value)
    +
    +    def is_available(self) -> bool:
    +        if hasattr(self._original_module, "is_available"):
    +            try:
    +                return self._original_module.is_available()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.is_available() check failed: {e}")
    +                return False
    +        return False
    +
    +    def set_device(self, device_index: Any) -> None:
    +        pass
    +
    +    def current_device(self) -> int:
    +        if hasattr(self._original_module, "current_device"):
    +            try:
    +                return self._original_module.current_device()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.current_device() failed: {e}")
    +                return 0
    +        return 0
    +
    +    def device_count(self) -> int:
    +        if hasattr(self._original_module, "device_count"):
    +            try:
    +                return self._original_module.device_count()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.device_count() failed: {e}")
    +                return 0
    +        return 0
    +
    +    def synchronize(self, device_index: int | None = None) -> None:
    +        if hasattr(self._original_module, "synchronize"):
    +            try:
    +                self._original_module.synchronize()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.synchronize() failed: {e}")
    +
    +    def empty_cache(self) -> None:
    +        if hasattr(self._original_module, "_clear_cache"):
    +            try:
    +                self._original_module._clear_cache()
    +            except Exception as e:
    +                logger.warning(f"Failed to clear TPU cache: {e}")
    +
    +
    +@PlatformRegistry.register(platform="tpu")
    +class PlatformTPU(PlatformCUDA):
    +    """Platform backend for Google TPUs (subclasses PlatformCUDA for API compatibility).
    +
    +    Experimental: see the module docstring. Registering this platform does not make verl
    +    runnable on TPU on its own -- the engine backends are still to come.
    +    """
    +
    +    def __init__(self):
    +        super().__init__()
    +        original_tpu = getattr(torch, "tpu", DummyTpuDeviceModule())
    +        self._device_module = TPUDeviceModuleProxy(original_tpu)
    +
    +    @property
    +    def vendor_name(self) -> str:
    +        return "google"
    +
    +    @property
    +    def device_name(self) -> str:
    +        return "tpu"
    +
    +    @property
    +    def device_module(self):
    +        return self._device_module
    +
    +    def current_device(self) -> int:
    +        return self.device_module.current_device()
    +
    +    def device_count(self) -> int:
    +        return self.device_module.device_count()
    +
    +    def set_device(self, device_index: int) -> None:
    +        self.device_module.set_device(device_index)
    +
    +    def synchronize(self, device_index: int | None = None) -> None:
    +        self.device_module.synchronize()
    +
    +    def manual_seed(self, seed: int) -> None:
    +        torch.manual_seed(seed)
    +
    +    def manual_seed_all(self, seed: int) -> None:
    +        self.device_module.manual_seed_all(seed)
    +
    +    def is_available(self) -> bool:
    +        if hasattr(torch, "tpu"):
    +            try:
    +                return torch.tpu.is_available()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.is_available() check failed: {e}")
    +        return False
    +
    +    def is_platform_available(self, use_smi_check=False) -> bool:
    +        if os.environ.get("VERL_PLATFORM") == "tpu":
    +            return True
    +        if "TPU_NAME" in os.environ or "TPU_VISIBLE_DEVICES" in os.environ:
    +            return True
    +        # The env vars come first because a CPU-only Ray driver process has no chip attached
    +        # yet still belongs to a TPU job. Falling back to the runtime lets a plain TPU VM,
    +        # where nothing sets TPU_NAME, detect itself instead of defaulting to CUDA.
    +        return self.is_available()
    +
    +    def ray_resource_name(self) -> str:
    +        return "TPU"
    +
    +    def ray_resource_options(self, num_gpus: float) -> dict[str, Any]:
    +        tpu_chips = int(num_gpus)
    +        return {"resources": {"TPU": tpu_chips}} if tpu_chips >= 1 else {}
    +
    +    def communication_backend_name(self) -> str:
    +        return "tpu_dist"
    +
    +    def ray_noset_envvars(self) -> list[str]:
    +        return super().ray_noset_envvars() + [
    +            "RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS",
    +        ]
    +
    +    def ray_local_rank_override(self) -> Optional[str]:
    +        # Ray does not enumerate TPU chips, so the index comes from TPU_VISIBLE_CHIPS, which
    +        # get_worker_env_vars() sets when the worker is created.
    +        return os.environ.get("TPU_VISIBLE_CHIPS", "0")
    +
    +    def supports_colocated_worker_groups(self) -> bool:
    +        # A TPU chip belongs to one process and cannot be shared between colocated WorkerGroups.
    +        return False
    +
    +    def get_tpu_env_vars(
    +        self,
    +        rank: int,
    +        world_size: int,
    +        local_rank: int,
    +        local_world_size: int,
    +        name_prefix: str,
    +        pgs: list,
    +    ) -> dict[str, str]:
    +        """Generates TPU-specific distributed environment variables for PJRT mesh initialization."""
    +        node_ip_map = {node["NodeID"]: node["NodeManagerAddress"] for node in ray.nodes() if node.get("Alive", False)}
    +        bundle_ips = []
    +        local_ip = ray.util.get_node_ip_address()
    +        clean_prefix = name_prefix.lower().split("_")[0] if name_prefix else ""
    +        matching_pgs = []
    +
    +        # 1. Primary filter: Select placement group containing current worker's node IP
    +        for p in pgs:
    +            specs = ray._private.state.state.placement_group_table(p.id)
    +            if specs.get("state") != "CREATED":
    +                continue
    +            bundles_map = specs.get("bundles_to_node_id", {})
    +            pg_ips = [node_ip_map[node_id] for b_idx, node_id in sorted(bundles_map.items()) if node_id in node_ip_map]
    +            if local_ip in pg_ips:
    +                matching_pgs.append(p)
    +
    +        # 2. Secondary fallback: Filter by clean_prefix if placement group names are explicitly set
    +        if not matching_pgs and clean_prefix:
    +            for p in pgs:
    +                p_name = ray._private.state.state.placement_group_table(p.id).get("name", "").lower()
    +                if clean_prefix in p_name:
    +                    matching_pgs.append(p)
    +
    +        target_pgs = matching_pgs if matching_pgs else pgs
    +
    +        for pg in target_pgs:
    +            specs = ray._private.state.state.placement_group_table(pg.id)
    +            if specs.get("state") != "CREATED":
    +                continue
    +            bundles_map = specs.get("bundles_to_node_id", {})
    +            for b_idx in sorted(bundles_map.keys()):
    +                node_id = bundles_map[b_idx]
    +                if node_id in node_ip_map:
    +                    bundle_ips.append(node_ip_map[node_id])
    +
    +        base_port = TPU_PROCESS_BASE_PORT
    +        sb_addresses = [f"{ip}:{base_port + (b_idx % local_world_size)}" for b_idx, ip in enumerate(bundle_ips)]
    +
    +        # Extract unique worker hostnames preserving rank order
    +        unique_hostnames = list(dict.fromkeys(bundle_ips))
    +
    +        env_vars = {
    +            "TORCH_TPU_SLICEBUILDER_ADDRESSES": ",".join(sb_addresses),
    +            "TPU_PROCESS_ADDRESSES": ",".join(sb_addresses),
    +            "TPU_PROCESS_PORT": str(base_port + local_rank),
    +            "CLOUD_TPU_TASK_ID": str(rank // local_world_size),
    +            "TPU_WORKER_HOSTNAMES": ",".join(unique_hostnames),
    +            "TPU_VISIBLE_CHIPS": str(local_rank),
    +        }
    +
    +        # Apply TPU topology and host bounds based on TPU pod type or world size
    +        tpu_nodes = [node for node in ray.nodes() if "TPU" in node.get("Resources", {}) and node.get("Alive")]
    +        tpu_type = tpu_nodes[0].get("Labels", {}).get("ray.io/tpu-pod-type", "") if tpu_nodes else ""
    +
    +        topo = TPU_TOPOLOGY_MAP.get(tpu_type, TPU_TOPOLOGY_MAP.get(world_size, "1,1,1"))

    can we read it from TORCH_TPU_TOPOLOGY (it will be different from TPU_TOPOLOGY, but I think it is guaranteed to be set for distributed runs, and should be the right one for environment to use

    askhat-g askhat-g commented on code on Sep 14, 2026 23:31 UTC
    Code Review
    verl/plugin/platform/platform_tpu.py:1
    @@ -0,0 +1,433 @@
    +# Copyright (c) 2026 BAAI. All rights reserved.

    Ah, it should be Google. This slipped the check. Thanks for pointing out

    wuxibin89 wuxibin89 commented on Sep 15, 2026 02:55 UTC
    Contributor

    @askhat-g We prefer to support verl TPU integration as out-of-tree in verl-project/verl-hardware-plugin, once it matures we can move it as in-tree.

    askhat-g askhat-g commented on Sep 17, 2026 00:30 UTC
    Author

    @askhat-g We prefer to support verl TPU integration as out-of-tree in verl-project/verl-hardware-plugin, once it matures we can move it as in-tree.

    Thank you @wuxibin89 , started a new PR here https://github.com/verl-project/verl-hardware-plugin/pull/18

    wuxibin89 wuxibin89 commented on Sep 17, 2026 02:42 UTC
    Contributor

    > @askhat-g We prefer to support verl TPU integration as out-of-tree in verl-project/verl-hardware-plugin, once it matures we can move it as in-tree.

    > Thank you @wuxibin89 , started a new PR here verl-project/verl-hardware-plugin#18

    @askhat-g https://github.com/verl-project/verl-hardware-plugin/pull/18 merged, please strip platform_tpu.py and keep single-controller changes in this PR.

    jialei777 jialei777 commented on code on Sep 17, 2026 03:55 UTC
    Code Review
    verl/plugin/platform/platform_base.py:1
    @@ -230,6 +230,37 @@ def ray_resource_options(self, num_gpus: float) -> dict[str, Any]:
                 return {"num_gpus": num_gpus}
             return {"resources": {resource_name: num_gpus}}
     
    +    def supports_colocated_worker_groups(self) -> bool:
    +        """Whether several WorkerGroups can share one accelerator.
    +
    +        ``False`` where a device is claimed exclusively by a single process, which caps
    +        colocation at one WorkerGroup.
    +        """
    +        return True
    +
    +    def get_worker_env_vars(

    should we keep this method only for tpu platform? It is actually a bit confusing for platforms other than TPU

    jialei777 jialei777 commented on code on Sep 17, 2026 03:57 UTC
    Code Review
    verl/plugin/platform/platform_tpu.py:1
    @@ -0,0 +1,432 @@
    +# Copyright (c) 2026 Google LLC. All rights reserved.
    +#
    +# Licensed under the Apache License, Version 2.0 (the "License");
    +# you may not use this file except in compliance with the License.
    +# You may obtain a copy of the License at
    +#
    +#     http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +"""Google TPU platform implementation.
    +
    +**Experimental: TPU support is under development and cannot run training end to end yet.**
    +This module registers the platform and provides the device abstraction plus the Ray resource
    +and worker-environment plumbing. The training engine, the generation engine and the
    +weight-transfer path are still to come.
    +
    +``torch_tpu`` reuses the NVIDIA device API surface, so most of ``PlatformCUDA`` works
    +unchanged. This class subclasses it and overrides device-specific environment configuration,
    +resource options, and memory management proxies.
    +"""
    +
    +import logging
    +import os
    +from typing import Any, Optional
    +
    +import ray
    +import torch
    +
    +from .platform_cuda import PlatformCUDA
    +from .platform_manager import PlatformRegistry
    +
    +logger = logging.getLogger(__file__)
    +logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
    +
    +
    +def _ensure_torch_tpu() -> bool:
    +    """Try to import torch_tpu, which registers the ``tpu_dist`` distributed backend.
    +
    +    Returns True if the TPU runtime is usable after the attempt.
    +    """
    +    if hasattr(torch, "tpu"):
    +        return True
    +    try:
    +        import torch_tpu  # noqa: F401
    +
    +        return hasattr(torch, "tpu")
    +    except Exception as e:
    +        logger.debug("The current machine has no torch.tpu, because: %s", e)
    +    return False
    +
    +
    +_ensure_torch_tpu()  # Attempt at module load time so availability checks are faster later
    +
    +# Base port for the TPU distributed slice builder mesh. Each local rank takes ``base + local_rank``.
    +TPU_PROCESS_BASE_PORT = 8471
    +
    +# TPU chip HBM capacities in bytes
    +HBM_BYTES_TPU_V5P = 95 * 1024 * 1024 * 1024  # 95 GB
    +HBM_BYTES_TPU_V6E = 32 * 1024 * 1024 * 1024  # 32 GB
    +HBM_BYTES_TPU_V7X = 192 * 1024 * 1024 * 1024  # 192 GB
    +
    +TPU_HBM_BYTES_MAP = {
    +    "v5p": HBM_BYTES_TPU_V5P,
    +    "v6e": HBM_BYTES_TPU_V6E,
    +    "v7x": HBM_BYTES_TPU_V7X,

    just be clear: we have only tested v6e right? maybe have a comment mentioning that.

    jialei777 jialei777 commented on code on Sep 17, 2026 04:01 UTC
    Code Review
    verl/plugin/platform/platform_tpu.py:1
    @@ -0,0 +1,433 @@
    +# Copyright (c) 2026 BAAI. All rights reserved.
    +# Copyright (c) 2026 Google LLC. All rights reserved.
    +#
    +# Licensed under the Apache License, Version 2.0 (the "License");
    +# you may not use this file except in compliance with the License.
    +# You may obtain a copy of the License at
    +#
    +#     http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +"""Google TPU platform implementation.
    +
    +**Experimental: TPU support is under development and cannot run training end to end yet.**
    +This module registers the platform and provides the device abstraction plus the Ray resource
    +and worker-environment plumbing. The training engine, the generation engine and the
    +weight-transfer path are still to come.
    +
    +``torch_tpu`` reuses the NVIDIA device API surface, so most of ``PlatformCUDA`` works
    +unchanged. This class subclasses it and overrides device-specific environment configuration,
    +resource options, and memory management proxies.
    +"""
    +
    +import logging
    +import os
    +from typing import Any, Optional
    +
    +import ray
    +import torch
    +
    +from .platform_cuda import PlatformCUDA
    +from .platform_manager import PlatformRegistry
    +
    +logger = logging.getLogger(__file__)
    +logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
    +
    +
    +def _ensure_torch_tpu() -> bool:
    +    """Try to import torch_tpu, which registers the ``tpu_dist`` distributed backend.
    +
    +    Returns True if the TPU runtime is usable after the attempt.
    +    """
    +    if hasattr(torch, "tpu"):
    +        return True
    +    try:
    +        import torch_tpu  # noqa: F401
    +
    +        return hasattr(torch, "tpu")
    +    except Exception as e:
    +        logger.debug("The current machine has no torch.tpu, because: %s", e)
    +    return False
    +
    +
    +_ensure_torch_tpu()  # Attempt at module load time so availability checks are faster later
    +
    +# Base port for the TPU distributed slice builder mesh. Each local rank takes ``base + local_rank``.
    +TPU_PROCESS_BASE_PORT = 8471
    +
    +# TPU chip HBM capacities in bytes
    +HBM_BYTES_TPU_V5P = 95 * 1024 * 1024 * 1024  # 95 GB
    +HBM_BYTES_TPU_V6E = 32 * 1024 * 1024 * 1024  # 32 GB
    +HBM_BYTES_TPU_V7X = 192 * 1024 * 1024 * 1024  # 192 GB
    +
    +TPU_HBM_BYTES_MAP = {
    +    "v5p": HBM_BYTES_TPU_V5P,
    +    "v6e": HBM_BYTES_TPU_V6E,
    +    "v7x": HBM_BYTES_TPU_V7X,
    +}
    +
    +# Fallback HBM capacity when the chip generation cannot be determined.
    +HBM_BYTES_TPU_DEFAULT = HBM_BYTES_TPU_V6E
    +
    +# TPU default 3D mesh topology mappings by pod type or total chips
    +TPU_TOPOLOGY_MAP = {
    +    "v6e-32": "4,8,1",
    +    "v6e-8": "2,4,1",
    +    "v6e-4": "2,2,1",
    +    32: "4,8,1",
    +    8: "2,4,1",
    +    4: "2,2,1",
    +}
    +
    +
    +def get_tpu_chip_hbm_bytes() -> int:
    +    """Detects the TPU chip generation from Ray node labels or environment variables and returns its HBM capacity."""
    +    tpu_type = ""
    +
    +    # Query Ray cluster node labels for TPU resource type
    +    try:
    +        if ray.is_initialized():
    +            tpu_nodes = [node for node in ray.nodes() if "TPU" in node.get("Resources", {}) and node.get("Alive")]
    +            if tpu_nodes:
    +                labels = tpu_nodes[0].get("Labels", {})
    +                tpu_type = (labels.get("ray.io/accelerator-type") or labels.get("ray.io/tpu-pod-type") or "").lower()
    +    except Exception as e:
    +        logger.warning(f"Unable to query Ray node labels for TPU chip type: {e}")
    +
    +    # Fallback to environment variables
    +    if not tpu_type:
    +        tpu_type = (
    +            os.environ.get("TPU_ACCELERATOR_TYPE")
    +            or os.environ.get("ACCELERATOR_TYPE")
    +            or os.environ.get("TPU_TYPE")
    +            or ""
    +        ).lower()
    +
    +    for chip_gen, hbm_bytes in TPU_HBM_BYTES_MAP.items():
    +        if chip_gen in tpu_type:
    +            return hbm_bytes
    +
    +    logger.warning(f"Unable to determine TPU chip HBM bytes for tpu_type='{tpu_type}'. Returning -1.")
    +    return -1
    +
    +
    +class DummyTpuDeviceModule:
    +    """Fallback device module for CPU-only nodes and driver processes.
    +
    +    Provides no-op implementations for torch.tpu APIs on processes where torch_tpu is not imported
    +    or no TPU devices are attached.
    +    """
    +
    +    def is_available(self) -> bool:
    +        return False
    +
    +    def set_device(self, device_index: Any) -> None:
    +        pass
    +
    +    def current_device(self) -> int:
    +        return 0
    +
    +    def device_count(self) -> int:
    +        return 0
    +
    +    def synchronize(self) -> None:
    +        pass
    +
    +    def manual_seed(self, seed: int) -> None:
    +        torch.manual_seed(seed)
    +
    +    def manual_seed_all(self, seed: int) -> None:
    +        torch.manual_seed(seed)
    +
    +
    +class TPUDeviceModuleProxy:
    +    """Proxy wrapper for torch.tpu to emulate the PyTorch NVIDIA memory management APIs.
    +
    +    Provides default fallback implementations for memory tracking methods
    +    (e.g. memory_reserved, memory_allocated, get_device_properties) that are called throughout verl's codebase
    +    but not natively provided by torch_tpu.
    +    """
    +
    +    def __init__(self, original_module):
    +        self.__dict__["_original_module"] = original_module
    +
    +    def __getattr__(self, name):
    +        if name == "set_device":
    +            return self.set_device
    +
    +        if hasattr(self._original_module, name):
    +            return getattr(self._original_module, name)
    +
    +        if name == "memory_reserved":
    +            return lambda *args, **kwargs: 0
    +        elif name == "memory_allocated":
    +            return lambda *args, **kwargs: 0
    +        elif name == "max_memory_reserved":
    +            return lambda *args, **kwargs: 0
    +        elif name == "max_memory_allocated":
    +            return lambda *args, **kwargs: 0
    +        elif name == "reset_peak_memory_stats":
    +            return lambda *args, **kwargs: None
    +        elif name == "get_device_properties":
    +
    +            class DummyDeviceProperties:
    +                def __init__(self, total_memory=HBM_BYTES_TPU_DEFAULT):
    +                    self.total_memory = total_memory
    +                    self.name = "Google TPU"
    +                    self.major = 1
    +                    self.minor = 0
    +
    +            hbm_bytes = get_tpu_chip_hbm_bytes()
    +            total_mem = hbm_bytes if hbm_bytes > 0 else HBM_BYTES_TPU_DEFAULT
    +            return lambda *args, **kwargs: DummyDeviceProperties(total_memory=total_mem)
    +        elif name == "mem_get_info":
    +            hbm_bytes = get_tpu_chip_hbm_bytes()
    +            total_mem = hbm_bytes if hbm_bytes > 0 else HBM_BYTES_TPU_DEFAULT
    +            return lambda *args, **kwargs: (total_mem, total_mem)
    +
    +        raise AttributeError(f"'TPUDeviceModuleProxy' object has no attribute '{name}'")
    +
    +    def __setattr__(self, name, value):
    +        if name.startswith("_"):
    +            super().__setattr__(name, value)
    +        else:
    +            setattr(self._original_module, name, value)
    +
    +    def is_available(self) -> bool:
    +        if hasattr(self._original_module, "is_available"):
    +            try:
    +                return self._original_module.is_available()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.is_available() check failed: {e}")
    +                return False
    +        return False
    +
    +    def set_device(self, device_index: Any) -> None:
    +        pass
    +
    +    def current_device(self) -> int:
    +        if hasattr(self._original_module, "current_device"):
    +            try:
    +                return self._original_module.current_device()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.current_device() failed: {e}")
    +                return 0
    +        return 0
    +
    +    def device_count(self) -> int:
    +        if hasattr(self._original_module, "device_count"):
    +            try:
    +                return self._original_module.device_count()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.device_count() failed: {e}")
    +                return 0
    +        return 0
    +
    +    def synchronize(self, device_index: int | None = None) -> None:
    +        if hasattr(self._original_module, "synchronize"):
    +            try:
    +                self._original_module.synchronize()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.synchronize() failed: {e}")
    +
    +    def empty_cache(self) -> None:
    +        if hasattr(self._original_module, "_clear_cache"):
    +            try:
    +                self._original_module._clear_cache()
    +            except Exception as e:
    +                logger.warning(f"Failed to clear TPU cache: {e}")
    +
    +
    +@PlatformRegistry.register(platform="tpu")
    +class PlatformTPU(PlatformCUDA):
    +    """Platform backend for Google TPUs (subclasses PlatformCUDA for API compatibility).
    +
    +    Experimental: see the module docstring. Registering this platform does not make verl
    +    runnable on TPU on its own -- the engine backends are still to come.
    +    """
    +
    +    def __init__(self):
    +        super().__init__()
    +        original_tpu = getattr(torch, "tpu", DummyTpuDeviceModule())
    +        self._device_module = TPUDeviceModuleProxy(original_tpu)
    +
    +    @property
    +    def vendor_name(self) -> str:
    +        return "google"
    +
    +    @property
    +    def device_name(self) -> str:
    +        return "tpu"
    +
    +    @property
    +    def device_module(self):
    +        return self._device_module
    +
    +    def current_device(self) -> int:
    +        return self.device_module.current_device()
    +
    +    def device_count(self) -> int:
    +        return self.device_module.device_count()
    +
    +    def set_device(self, device_index: int) -> None:
    +        self.device_module.set_device(device_index)
    +
    +    def synchronize(self, device_index: int | None = None) -> None:
    +        self.device_module.synchronize()
    +
    +    def manual_seed(self, seed: int) -> None:
    +        torch.manual_seed(seed)
    +
    +    def manual_seed_all(self, seed: int) -> None:
    +        self.device_module.manual_seed_all(seed)
    +
    +    def is_available(self) -> bool:
    +        if hasattr(torch, "tpu"):
    +            try:
    +                return torch.tpu.is_available()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.is_available() check failed: {e}")
    +        return False
    +
    +    def is_platform_available(self, use_smi_check=False) -> bool:
    +        if os.environ.get("VERL_PLATFORM") == "tpu":
    +            return True
    +        if "TPU_NAME" in os.environ or "TPU_VISIBLE_DEVICES" in os.environ:
    +            return True
    +        # The env vars come first because a CPU-only Ray driver process has no chip attached
    +        # yet still belongs to a TPU job. Falling back to the runtime lets a plain TPU VM,
    +        # where nothing sets TPU_NAME, detect itself instead of defaulting to CUDA.
    +        return self.is_available()
    +
    +    def ray_resource_name(self) -> str:
    +        return "TPU"
    +
    +    def ray_resource_options(self, num_gpus: float) -> dict[str, Any]:
    +        tpu_chips = int(num_gpus)
    +        return {"resources": {"TPU": tpu_chips}} if tpu_chips >= 1 else {}
    +
    +    def communication_backend_name(self) -> str:
    +        return "tpu_dist"
    +
    +    def ray_noset_envvars(self) -> list[str]:
    +        return super().ray_noset_envvars() + [
    +            "RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS",
    +        ]
    +
    +    def ray_local_rank_override(self) -> Optional[str]:
    +        # Ray does not enumerate TPU chips, so the index comes from TPU_VISIBLE_CHIPS, which
    +        # get_worker_env_vars() sets when the worker is created.
    +        return os.environ.get("TPU_VISIBLE_CHIPS", "0")
    +
    +    def supports_colocated_worker_groups(self) -> bool:
    +        # A TPU chip belongs to one process and cannot be shared between colocated WorkerGroups.
    +        return False
    +
    +    def get_tpu_env_vars(
    +        self,
    +        rank: int,
    +        world_size: int,
    +        local_rank: int,
    +        local_world_size: int,
    +        name_prefix: str,
    +        pgs: list,
    +    ) -> dict[str, str]:
    +        """Generates TPU-specific distributed environment variables for PJRT mesh initialization."""
    +        node_ip_map = {node["NodeID"]: node["NodeManagerAddress"] for node in ray.nodes() if node.get("Alive", False)}
    +        bundle_ips = []
    +        local_ip = ray.util.get_node_ip_address()
    +        clean_prefix = name_prefix.lower().split("_")[0] if name_prefix else ""
    +        matching_pgs = []
    +
    +        # 1. Primary filter: Select placement group containing current worker's node IP
    +        for p in pgs:
    +            specs = ray._private.state.state.placement_group_table(p.id)
    +            if specs.get("state") != "CREATED":
    +                continue
    +            bundles_map = specs.get("bundles_to_node_id", {})
    +            pg_ips = [node_ip_map[node_id] for b_idx, node_id in sorted(bundles_map.items()) if node_id in node_ip_map]
    +            if local_ip in pg_ips:
    +                matching_pgs.append(p)
    +
    +        # 2. Secondary fallback: Filter by clean_prefix if placement group names are explicitly set
    +        if not matching_pgs and clean_prefix:
    +            for p in pgs:
    +                p_name = ray._private.state.state.placement_group_table(p.id).get("name", "").lower()
    +                if clean_prefix in p_name:
    +                    matching_pgs.append(p)
    +
    +        target_pgs = matching_pgs if matching_pgs else pgs
    +
    +        for pg in target_pgs:
    +            specs = ray._private.state.state.placement_group_table(pg.id)
    +            if specs.get("state") != "CREATED":
    +                continue
    +            bundles_map = specs.get("bundles_to_node_id", {})
    +            for b_idx in sorted(bundles_map.keys()):
    +                node_id = bundles_map[b_idx]
    +                if node_id in node_ip_map:
    +                    bundle_ips.append(node_ip_map[node_id])
    +
    +        base_port = TPU_PROCESS_BASE_PORT
    +        sb_addresses = [f"{ip}:{base_port + (b_idx % local_world_size)}" for b_idx, ip in enumerate(bundle_ips)]
    +
    +        # Extract unique worker hostnames preserving rank order
    +        unique_hostnames = list(dict.fromkeys(bundle_ips))
    +
    +        env_vars = {
    +            "TORCH_TPU_SLICEBUILDER_ADDRESSES": ",".join(sb_addresses),
    +            "TPU_PROCESS_ADDRESSES": ",".join(sb_addresses),
    +            "TPU_PROCESS_PORT": str(base_port + local_rank),
    +            "CLOUD_TPU_TASK_ID": str(rank // local_world_size),
    +            "TPU_WORKER_HOSTNAMES": ",".join(unique_hostnames),
    +            "TPU_VISIBLE_CHIPS": str(local_rank),
    +        }
    +
    +        # Apply TPU topology and host bounds based on TPU pod type or world size
    +        tpu_nodes = [node for node in ray.nodes() if "TPU" in node.get("Resources", {}) and node.get("Alive")]
    +        tpu_type = tpu_nodes[0].get("Labels", {}).get("ray.io/tpu-pod-type", "") if tpu_nodes else ""
    +
    +        topo = TPU_TOPOLOGY_MAP.get(tpu_type, TPU_TOPOLOGY_MAP.get(world_size, "1,1,1"))
    jialei777 jialei777 commented on code on Sep 17, 2026 04:07 UTC
    Code Review
    verl/single_controller/base/worker.py:1
    @@ -276,8 +277,10 @@ def _setup_env_cuda_visible_devices(self):
                 # RAY_EXPERIMENTAL_NOSET_*_VISIBLE_DEVICES is set,
                 # so we need to set local rank when the flag is set.
                 device_name = get_resource_name()
    -            local_rank = ray.get_runtime_context().get_accelerator_ids()[device_name][0]
    -            os.environ["LOCAL_RANK"] = local_rank
    +            local_rank = get_platform().ray_local_rank_override()

    This is actually i a bit confusing to read. Can we add a condition of get_platform().device_name == "TPU" and also add a TODO on have ray fix it? cc: @andrewsykim

    jialei777 jialei777 commented on code on Sep 17, 2026 04:10 UTC
    Code Review
    verl/single_controller/ray/base.py:1
    @@ -120,6 +122,10 @@ def __init__(
             detached=False,
             accelerator_type: Optional[str] = None,
         ) -> None:
    +        # Where a device is claimed exclusively, asking to colocate more than one WorkerGroup

    be explicit that this is the case for TPU in the comment?

    askhat-g askhat-g commented on code on Sep 17, 2026 20:44 UTC
    Code Review
    verl/single_controller/base/worker.py:1
    @@ -276,8 +277,10 @@ def _setup_env_cuda_visible_devices(self):
                 # RAY_EXPERIMENTAL_NOSET_*_VISIBLE_DEVICES is set,
                 # so we need to set local rank when the flag is set.
                 device_name = get_resource_name()
    -            local_rank = ray.get_runtime_context().get_accelerator_ids()[device_name][0]
    -            os.environ["LOCAL_RANK"] = local_rank
    +            local_rank = get_platform().ray_local_rank_override()

    Yes, this happens because ranks seem to be treated different in the case of TPU. I wanted to avoid single out the tpu case(if platform == 'TPU') and tried generalize it by overriding the local rank for the tpu case. Let me take it offline with Andrew and discuss if there are better solutions to this

    askhat-g askhat-g commented on code on Sep 17, 2026 20:47 UTC
    Code Review
    verl/plugin/platform/platform_tpu.py:1
    @@ -0,0 +1,432 @@
    +# Copyright (c) 2026 Google LLC. All rights reserved.
    +#
    +# Licensed under the Apache License, Version 2.0 (the "License");
    +# you may not use this file except in compliance with the License.
    +# You may obtain a copy of the License at
    +#
    +#     http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +"""Google TPU platform implementation.
    +
    +**Experimental: TPU support is under development and cannot run training end to end yet.**
    +This module registers the platform and provides the device abstraction plus the Ray resource
    +and worker-environment plumbing. The training engine, the generation engine and the
    +weight-transfer path are still to come.
    +
    +``torch_tpu`` reuses the NVIDIA device API surface, so most of ``PlatformCUDA`` works
    +unchanged. This class subclasses it and overrides device-specific environment configuration,
    +resource options, and memory management proxies.
    +"""
    +
    +import logging
    +import os
    +from typing import Any, Optional
    +
    +import ray
    +import torch
    +
    +from .platform_cuda import PlatformCUDA
    +from .platform_manager import PlatformRegistry
    +
    +logger = logging.getLogger(__file__)
    +logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
    +
    +
    +def _ensure_torch_tpu() -> bool:
    +    """Try to import torch_tpu, which registers the ``tpu_dist`` distributed backend.
    +
    +    Returns True if the TPU runtime is usable after the attempt.
    +    """
    +    if hasattr(torch, "tpu"):
    +        return True
    +    try:
    +        import torch_tpu  # noqa: F401
    +
    +        return hasattr(torch, "tpu")
    +    except Exception as e:
    +        logger.debug("The current machine has no torch.tpu, because: %s", e)
    +    return False
    +
    +
    +_ensure_torch_tpu()  # Attempt at module load time so availability checks are faster later
    +
    +# Base port for the TPU distributed slice builder mesh. Each local rank takes ``base + local_rank``.
    +TPU_PROCESS_BASE_PORT = 8471
    +
    +# TPU chip HBM capacities in bytes
    +HBM_BYTES_TPU_V5P = 95 * 1024 * 1024 * 1024  # 95 GB
    +HBM_BYTES_TPU_V6E = 32 * 1024 * 1024 * 1024  # 32 GB
    +HBM_BYTES_TPU_V7X = 192 * 1024 * 1024 * 1024  # 192 GB
    +
    +TPU_HBM_BYTES_MAP = {
    +    "v5p": HBM_BYTES_TPU_V5P,
    +    "v6e": HBM_BYTES_TPU_V6E,
    +    "v7x": HBM_BYTES_TPU_V7X,

    Yeah but we will support this eventually. I will add the comment

    askhat-g askhat-g commented on code on Sep 17, 2026 20:47 UTC
    Code Review
    verl/plugin/platform/platform_tpu.py:1
    @@ -0,0 +1,433 @@
    +# Copyright (c) 2026 BAAI. All rights reserved.
    +# Copyright (c) 2026 Google LLC. All rights reserved.
    +#
    +# Licensed under the Apache License, Version 2.0 (the "License");
    +# you may not use this file except in compliance with the License.
    +# You may obtain a copy of the License at
    +#
    +#     http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +"""Google TPU platform implementation.
    +
    +**Experimental: TPU support is under development and cannot run training end to end yet.**
    +This module registers the platform and provides the device abstraction plus the Ray resource
    +and worker-environment plumbing. The training engine, the generation engine and the
    +weight-transfer path are still to come.
    +
    +``torch_tpu`` reuses the NVIDIA device API surface, so most of ``PlatformCUDA`` works
    +unchanged. This class subclasses it and overrides device-specific environment configuration,
    +resource options, and memory management proxies.
    +"""
    +
    +import logging
    +import os
    +from typing import Any, Optional
    +
    +import ray
    +import torch
    +
    +from .platform_cuda import PlatformCUDA
    +from .platform_manager import PlatformRegistry
    +
    +logger = logging.getLogger(__file__)
    +logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
    +
    +
    +def _ensure_torch_tpu() -> bool:
    +    """Try to import torch_tpu, which registers the ``tpu_dist`` distributed backend.
    +
    +    Returns True if the TPU runtime is usable after the attempt.
    +    """
    +    if hasattr(torch, "tpu"):
    +        return True
    +    try:
    +        import torch_tpu  # noqa: F401
    +
    +        return hasattr(torch, "tpu")

    The latter is true, it is not about chip availability

    askhat-g askhat-g commented on code on Sep 17, 2026 20:49 UTC
    Code Review
    verl/plugin/platform/platform_tpu.py:1
    @@ -0,0 +1,433 @@
    +# Copyright (c) 2026 BAAI. All rights reserved.
    +# Copyright (c) 2026 Google LLC. All rights reserved.
    +#
    +# Licensed under the Apache License, Version 2.0 (the "License");
    +# you may not use this file except in compliance with the License.
    +# You may obtain a copy of the License at
    +#
    +#     http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +"""Google TPU platform implementation.
    +
    +**Experimental: TPU support is under development and cannot run training end to end yet.**
    +This module registers the platform and provides the device abstraction plus the Ray resource
    +and worker-environment plumbing. The training engine, the generation engine and the
    +weight-transfer path are still to come.
    +
    +``torch_tpu`` reuses the NVIDIA device API surface, so most of ``PlatformCUDA`` works
    +unchanged. This class subclasses it and overrides device-specific environment configuration,
    +resource options, and memory management proxies.
    +"""
    +
    +import logging
    +import os
    +from typing import Any, Optional
    +
    +import ray
    +import torch
    +
    +from .platform_cuda import PlatformCUDA
    +from .platform_manager import PlatformRegistry
    +
    +logger = logging.getLogger(__file__)
    +logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
    +
    +
    +def _ensure_torch_tpu() -> bool:
    +    """Try to import torch_tpu, which registers the ``tpu_dist`` distributed backend.
    +
    +    Returns True if the TPU runtime is usable after the attempt.
    +    """
    +    if hasattr(torch, "tpu"):

    Hm, if it is not imported then we try to import it below, that would be a return prematurely

    askhat-g askhat-g commented on code on Sep 17, 2026 20:49 UTC
    Code Review
    verl/plugin/platform/platform_tpu.py:1
    @@ -0,0 +1,433 @@
    +# Copyright (c) 2026 BAAI. All rights reserved.
    +# Copyright (c) 2026 Google LLC. All rights reserved.
    +#
    +# Licensed under the Apache License, Version 2.0 (the "License");
    +# you may not use this file except in compliance with the License.
    +# You may obtain a copy of the License at
    +#
    +#     http://www.apache.org/licenses/LICENSE-2.0
    +#
    +# Unless required by applicable law or agreed to in writing, software
    +# distributed under the License is distributed on an "AS IS" BASIS,
    +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +# See the License for the specific language governing permissions and
    +# limitations under the License.
    +"""Google TPU platform implementation.
    +
    +**Experimental: TPU support is under development and cannot run training end to end yet.**
    +This module registers the platform and provides the device abstraction plus the Ray resource
    +and worker-environment plumbing. The training engine, the generation engine and the
    +weight-transfer path are still to come.
    +
    +``torch_tpu`` reuses the NVIDIA device API surface, so most of ``PlatformCUDA`` works
    +unchanged. This class subclasses it and overrides device-specific environment configuration,
    +resource options, and memory management proxies.
    +"""
    +
    +import logging
    +import os
    +from typing import Any, Optional
    +
    +import ray
    +import torch
    +
    +from .platform_cuda import PlatformCUDA
    +from .platform_manager import PlatformRegistry
    +
    +logger = logging.getLogger(__file__)
    +logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
    +
    +
    +def _ensure_torch_tpu() -> bool:
    +    """Try to import torch_tpu, which registers the ``tpu_dist`` distributed backend.
    +
    +    Returns True if the TPU runtime is usable after the attempt.
    +    """
    +    if hasattr(torch, "tpu"):
    +        return True
    +    try:
    +        import torch_tpu  # noqa: F401
    +
    +        return hasattr(torch, "tpu")
    +    except Exception as e:
    +        logger.debug("The current machine has no torch.tpu, because: %s", e)
    +    return False
    +
    +
    +_ensure_torch_tpu()  # Attempt at module load time so availability checks are faster later
    +
    +# Base port for the TPU distributed slice builder mesh. Each local rank takes ``base + local_rank``.
    +TPU_PROCESS_BASE_PORT = 8471
    +
    +# TPU chip HBM capacities in bytes
    +HBM_BYTES_TPU_V5P = 95 * 1024 * 1024 * 1024  # 95 GB
    +HBM_BYTES_TPU_V6E = 32 * 1024 * 1024 * 1024  # 32 GB
    +HBM_BYTES_TPU_V7X = 192 * 1024 * 1024 * 1024  # 192 GB
    +
    +TPU_HBM_BYTES_MAP = {
    +    "v5p": HBM_BYTES_TPU_V5P,
    +    "v6e": HBM_BYTES_TPU_V6E,
    +    "v7x": HBM_BYTES_TPU_V7X,
    +}
    +
    +# Fallback HBM capacity when the chip generation cannot be determined.
    +HBM_BYTES_TPU_DEFAULT = HBM_BYTES_TPU_V6E
    +
    +# TPU default 3D mesh topology mappings by pod type or total chips
    +TPU_TOPOLOGY_MAP = {
    +    "v6e-32": "4,8,1",
    +    "v6e-8": "2,4,1",
    +    "v6e-4": "2,2,1",
    +    32: "4,8,1",
    +    8: "2,4,1",
    +    4: "2,2,1",
    +}
    +
    +
    +def get_tpu_chip_hbm_bytes() -> int:
    +    """Detects the TPU chip generation from Ray node labels or environment variables and returns its HBM capacity."""
    +    tpu_type = ""
    +
    +    # Query Ray cluster node labels for TPU resource type
    +    try:
    +        if ray.is_initialized():
    +            tpu_nodes = [node for node in ray.nodes() if "TPU" in node.get("Resources", {}) and node.get("Alive")]
    +            if tpu_nodes:
    +                labels = tpu_nodes[0].get("Labels", {})
    +                tpu_type = (labels.get("ray.io/accelerator-type") or labels.get("ray.io/tpu-pod-type") or "").lower()
    +    except Exception as e:
    +        logger.warning(f"Unable to query Ray node labels for TPU chip type: {e}")
    +
    +    # Fallback to environment variables
    +    if not tpu_type:
    +        tpu_type = (
    +            os.environ.get("TPU_ACCELERATOR_TYPE")
    +            or os.environ.get("ACCELERATOR_TYPE")
    +            or os.environ.get("TPU_TYPE")
    +            or ""
    +        ).lower()
    +
    +    for chip_gen, hbm_bytes in TPU_HBM_BYTES_MAP.items():
    +        if chip_gen in tpu_type:
    +            return hbm_bytes
    +
    +    logger.warning(f"Unable to determine TPU chip HBM bytes for tpu_type='{tpu_type}'. Returning -1.")
    +    return -1
    +
    +
    +class DummyTpuDeviceModule:
    +    """Fallback device module for CPU-only nodes and driver processes.
    +
    +    Provides no-op implementations for torch.tpu APIs on processes where torch_tpu is not imported
    +    or no TPU devices are attached.
    +    """
    +
    +    def is_available(self) -> bool:
    +        return False
    +
    +    def set_device(self, device_index: Any) -> None:
    +        pass
    +
    +    def current_device(self) -> int:
    +        return 0
    +
    +    def device_count(self) -> int:
    +        return 0
    +
    +    def synchronize(self) -> None:
    +        pass
    +
    +    def manual_seed(self, seed: int) -> None:
    +        torch.manual_seed(seed)
    +
    +    def manual_seed_all(self, seed: int) -> None:
    +        torch.manual_seed(seed)
    +
    +
    +class TPUDeviceModuleProxy:
    +    """Proxy wrapper for torch.tpu to emulate the PyTorch NVIDIA memory management APIs.
    +
    +    Provides default fallback implementations for memory tracking methods
    +    (e.g. memory_reserved, memory_allocated, get_device_properties) that are called throughout verl's codebase
    +    but not natively provided by torch_tpu.
    +    """
    +
    +    def __init__(self, original_module):
    +        self.__dict__["_original_module"] = original_module
    +
    +    def __getattr__(self, name):
    +        if name == "set_device":
    +            return self.set_device
    +
    +        if hasattr(self._original_module, name):
    +            return getattr(self._original_module, name)
    +
    +        if name == "memory_reserved":
    +            return lambda *args, **kwargs: 0
    +        elif name == "memory_allocated":
    +            return lambda *args, **kwargs: 0
    +        elif name == "max_memory_reserved":
    +            return lambda *args, **kwargs: 0
    +        elif name == "max_memory_allocated":
    +            return lambda *args, **kwargs: 0
    +        elif name == "reset_peak_memory_stats":
    +            return lambda *args, **kwargs: None
    +        elif name == "get_device_properties":
    +
    +            class DummyDeviceProperties:
    +                def __init__(self, total_memory=HBM_BYTES_TPU_DEFAULT):
    +                    self.total_memory = total_memory
    +                    self.name = "Google TPU"
    +                    self.major = 1
    +                    self.minor = 0
    +
    +            hbm_bytes = get_tpu_chip_hbm_bytes()
    +            total_mem = hbm_bytes if hbm_bytes > 0 else HBM_BYTES_TPU_DEFAULT
    +            return lambda *args, **kwargs: DummyDeviceProperties(total_memory=total_mem)
    +        elif name == "mem_get_info":
    +            hbm_bytes = get_tpu_chip_hbm_bytes()
    +            total_mem = hbm_bytes if hbm_bytes > 0 else HBM_BYTES_TPU_DEFAULT
    +            return lambda *args, **kwargs: (total_mem, total_mem)
    +
    +        raise AttributeError(f"'TPUDeviceModuleProxy' object has no attribute '{name}'")
    +
    +    def __setattr__(self, name, value):
    +        if name.startswith("_"):
    +            super().__setattr__(name, value)
    +        else:
    +            setattr(self._original_module, name, value)
    +
    +    def is_available(self) -> bool:
    +        if hasattr(self._original_module, "is_available"):
    +            try:
    +                return self._original_module.is_available()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.is_available() check failed: {e}")
    +                return False
    +        return False
    +
    +    def set_device(self, device_index: Any) -> None:
    +        pass
    +
    +    def current_device(self) -> int:
    +        if hasattr(self._original_module, "current_device"):
    +            try:
    +                return self._original_module.current_device()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.current_device() failed: {e}")
    +                return 0
    +        return 0
    +
    +    def device_count(self) -> int:
    +        if hasattr(self._original_module, "device_count"):
    +            try:
    +                return self._original_module.device_count()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.device_count() failed: {e}")
    +                return 0
    +        return 0
    +
    +    def synchronize(self, device_index: int | None = None) -> None:
    +        if hasattr(self._original_module, "synchronize"):
    +            try:
    +                self._original_module.synchronize()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.synchronize() failed: {e}")
    +
    +    def empty_cache(self) -> None:
    +        if hasattr(self._original_module, "_clear_cache"):
    +            try:
    +                self._original_module._clear_cache()
    +            except Exception as e:
    +                logger.warning(f"Failed to clear TPU cache: {e}")
    +
    +
    +@PlatformRegistry.register(platform="tpu")
    +class PlatformTPU(PlatformCUDA):
    +    """Platform backend for Google TPUs (subclasses PlatformCUDA for API compatibility).
    +
    +    Experimental: see the module docstring. Registering this platform does not make verl
    +    runnable on TPU on its own -- the engine backends are still to come.
    +    """
    +
    +    def __init__(self):
    +        super().__init__()
    +        original_tpu = getattr(torch, "tpu", DummyTpuDeviceModule())
    +        self._device_module = TPUDeviceModuleProxy(original_tpu)
    +
    +    @property
    +    def vendor_name(self) -> str:
    +        return "google"
    +
    +    @property
    +    def device_name(self) -> str:
    +        return "tpu"
    +
    +    @property
    +    def device_module(self):
    +        return self._device_module
    +
    +    def current_device(self) -> int:
    +        return self.device_module.current_device()
    +
    +    def device_count(self) -> int:
    +        return self.device_module.device_count()
    +
    +    def set_device(self, device_index: int) -> None:
    +        self.device_module.set_device(device_index)
    +
    +    def synchronize(self, device_index: int | None = None) -> None:
    +        self.device_module.synchronize()
    +
    +    def manual_seed(self, seed: int) -> None:
    +        torch.manual_seed(seed)
    +
    +    def manual_seed_all(self, seed: int) -> None:
    +        self.device_module.manual_seed_all(seed)
    +
    +    def is_available(self) -> bool:
    +        if hasattr(torch, "tpu"):
    +            try:
    +                return torch.tpu.is_available()
    +            except Exception as e:
    +                logger.warning(f"torch.tpu.is_available() check failed: {e}")
    +        return False
    +
    +    def is_platform_available(self, use_smi_check=False) -> bool:
    +        if os.environ.get("VERL_PLATFORM") == "tpu":
    +            return True
    +        if "TPU_NAME" in os.environ or "TPU_VISIBLE_DEVICES" in os.environ:
    +            return True
    +        # The env vars come first because a CPU-only Ray driver process has no chip attached
    +        # yet still belongs to a TPU job. Falling back to the runtime lets a plain TPU VM,
    +        # where nothing sets TPU_NAME, detect itself instead of defaulting to CUDA.
    +        return self.is_available()
    +
    +    def ray_resource_name(self) -> str:
    +        return "TPU"
    +
    +    def ray_resource_options(self, num_gpus: float) -> dict[str, Any]:
    +        tpu_chips = int(num_gpus)
    +        return {"resources": {"TPU": tpu_chips}} if tpu_chips >= 1 else {}
    +
    +    def communication_backend_name(self) -> str:
    +        return "tpu_dist"
    +
    +    def ray_noset_envvars(self) -> list[str]:
    +        return super().ray_noset_envvars() + [
    +            "RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS",
    +        ]
    +
    +    def ray_local_rank_override(self) -> Optional[str]:
    +        # Ray does not enumerate TPU chips, so the index comes from TPU_VISIBLE_CHIPS, which
    +        # get_worker_env_vars() sets when the worker is created.
    +        return os.environ.get("TPU_VISIBLE_CHIPS", "0")
    +
    +    def supports_colocated_worker_groups(self) -> bool:
    +        # A TPU chip belongs to one process and cannot be shared between colocated WorkerGroups.
    +        return False
    +
    +    def get_tpu_env_vars(
    +        self,
    +        rank: int,
    +        world_size: int,
    +        local_rank: int,
    +        local_world_size: int,
    +        name_prefix: str,
    +        pgs: list,
    +    ) -> dict[str, str]:
    +        """Generates TPU-specific distributed environment variables for PJRT mesh initialization."""
    +        node_ip_map = {node["NodeID"]: node["NodeManagerAddress"] for node in ray.nodes() if node.get("Alive", False)}
    +        bundle_ips = []
    +        local_ip = ray.util.get_node_ip_address()
    +        clean_prefix = name_prefix.lower().split("_")[0] if name_prefix else ""
    +        matching_pgs = []
    +
    +        # 1. Primary filter: Select placement group containing current worker's node IP
    +        for p in pgs:
    +            specs = ray._private.state.state.placement_group_table(p.id)
    +            if specs.get("state") != "CREATED":
    +                continue
    +            bundles_map = specs.get("bundles_to_node_id", {})
    +            pg_ips = [node_ip_map[node_id] for b_idx, node_id in sorted(bundles_map.items()) if node_id in node_ip_map]
    +            if local_ip in pg_ips:
    +                matching_pgs.append(p)
    +
    +        # 2. Secondary fallback: Filter by clean_prefix if placement group names are explicitly set
    +        if not matching_pgs and clean_prefix:
    +            for p in pgs:
    +                p_name = ray._private.state.state.placement_group_table(p.id).get("name", "").lower()
    +                if clean_prefix in p_name:
    +                    matching_pgs.append(p)
    +
    +        target_pgs = matching_pgs if matching_pgs else pgs
    +
    +        for pg in target_pgs:
    +            specs = ray._private.state.state.placement_group_table(pg.id)
    +            if specs.get("state") != "CREATED":
    +                continue
    +            bundles_map = specs.get("bundles_to_node_id", {})
    +            for b_idx in sorted(bundles_map.keys()):
    +                node_id = bundles_map[b_idx]
    +                if node_id in node_ip_map:
    +                    bundle_ips.append(node_ip_map[node_id])
    +
    +        base_port = TPU_PROCESS_BASE_PORT
    +        sb_addresses = [f"{ip}:{base_port + (b_idx % local_world_size)}" for b_idx, ip in enumerate(bundle_ips)]
    +
    +        # Extract unique worker hostnames preserving rank order
    +        unique_hostnames = list(dict.fromkeys(bundle_ips))
    +
    +        env_vars = {
    +            "TORCH_TPU_SLICEBUILDER_ADDRESSES": ",".join(sb_addresses),
    +            "TPU_PROCESS_ADDRESSES": ",".join(sb_addresses),
    +            "TPU_PROCESS_PORT": str(base_port + local_rank),
    +            "CLOUD_TPU_TASK_ID": str(rank // local_world_size),
    +            "TPU_WORKER_HOSTNAMES": ",".join(unique_hostnames),
    +            "TPU_VISIBLE_CHIPS": str(local_rank),
    +        }
    +
    +        # Apply TPU topology and host bounds based on TPU pod type or world size
    +        tpu_nodes = [node for node in ray.nodes() if "TPU" in node.get("Resources", {}) and node.get("Alive")]
    +        tpu_type = tpu_nodes[0].get("Labels", {}).get("ray.io/tpu-pod-type", "") if tpu_nodes else ""
    +
    +        topo = TPU_TOPOLOGY_MAP.get(tpu_type, TPU_TOPOLOGY_MAP.get(world_size, "1,1,1"))

    Good to know, let me follow up on this, thank you for pointing that out

    andrewsykim andrewsykim commented on code on Sep 17, 2026 23:06 UTC
    Code Review
    verl/single_controller/base/worker.py:1
    @@ -276,8 +277,10 @@ def _setup_env_cuda_visible_devices(self):
                 # RAY_EXPERIMENTAL_NOSET_*_VISIBLE_DEVICES is set,
                 # so we need to set local rank when the flag is set.
                 device_name = get_resource_name()
    -            local_rank = ray.get_runtime_context().get_accelerator_ids()[device_name][0]
    -            os.environ["LOCAL_RANK"] = local_rank
    +            local_rank = get_platform().ray_local_rank_override()

    @ryanaoleary do you know if https://github.com/ray-project/ray/pull/65723 fixes this or is this a separate issue?

    andrewsykim andrewsykim commented on code on Sep 17, 2026 23:16 UTC
    Code Review
    verl/single_controller/base/worker.py:1
    @@ -276,8 +277,10 @@ def _setup_env_cuda_visible_devices(self):
                 # RAY_EXPERIMENTAL_NOSET_*_VISIBLE_DEVICES is set,
                 # so we need to set local rank when the flag is set.
                 device_name = get_resource_name()
    -            local_rank = ray.get_runtime_context().get_accelerator_ids()[device_name][0]
    -            os.environ["LOCAL_RANK"] = local_rank
    +            local_rank = get_platform().ray_local_rank_override()

    @askhat-g did you run this with RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1?

    andrewsykim andrewsykim commented on code on Sep 18, 2026 02:18 UTC
    Code Review
    verl/single_controller/base/worker.py:1
    @@ -276,8 +277,10 @@ def _setup_env_cuda_visible_devices(self):
                 # RAY_EXPERIMENTAL_NOSET_*_VISIBLE_DEVICES is set,
                 # so we need to set local rank when the flag is set.
                 device_name = get_resource_name()
    -            local_rank = ray.get_runtime_context().get_accelerator_ids()[device_name][0]
    -            os.environ["LOCAL_RANK"] = local_rank
    +            local_rank = get_platform().ray_local_rank_override()

    I don't think you need to do this, I suspect it's because we were previously testing with RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS on TPU v6e. Can you try running without RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS?

    askhat-g askhat-g commented on code on Sep 18, 2026 17:03 UTC
    Code Review
    verl/single_controller/base/worker.py:1
    @@ -276,8 +277,10 @@ def _setup_env_cuda_visible_devices(self):
                 # RAY_EXPERIMENTAL_NOSET_*_VISIBLE_DEVICES is set,
                 # so we need to set local rank when the flag is set.
                 device_name = get_resource_name()
    -            local_rank = ray.get_runtime_context().get_accelerator_ids()[device_name][0]
    -            os.environ["LOCAL_RANK"] = local_rank
    +            local_rank = get_platform().ray_local_rank_override()

    It still didn't work but I have removed it from this PR. We can align internally if it is needed

    jialei777 jialei777 approved these changes on Sep 18, 2026 20:12 UTC
    Approved Reviewer

    Approved these changes.

    vlasenkoalexey vlasenkoalexey approved these changes on Sep 18, 2026 20:32 UTC
    Approved Reviewer

    Approved these changes.

    ryanaoleary ryanaoleary commented on code on Sep 18, 2026 22:35 UTC
    Code Review
    verl/single_controller/base/worker.py:1
    @@ -276,8 +277,10 @@ def _setup_env_cuda_visible_devices(self):
                 # RAY_EXPERIMENTAL_NOSET_*_VISIBLE_DEVICES is set,
                 # so we need to set local rank when the flag is set.
                 device_name = get_resource_name()
    -            local_rank = ray.get_runtime_context().get_accelerator_ids()[device_name][0]
    -            os.environ["LOCAL_RANK"] = local_rank
    +            local_rank = get_platform().ray_local_rank_override()

    talked offline with @andrewsykim and believe it's a separate issue. The linked Ray PR fixes an issue with dual-device TPUs (tpu7x) by changing get_current_process_visible_accelerator_ids() to expand physical chip indices (0..3 from GKE's injected TPU_VISIBLE_CHIPS) into logical device IDs (0..7). Previously it would cap the TPU Ray resource on the node with the length of the accelerator Ids, which returned the chip IDs. To handle dual-device TPUs you now set RAY_TPU_RESOURCE_PER_CHIP=2 to ensure the translation occurs correctly without breaking default behavior.

    I think running without RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS=1 fails here because when it's not set Ray rewrites TPU_HOST_BOUNDS based on the logical resources it sees. The verl actors each request resources={"TPU": 1}, so it overwrites TPU_HOST_BOUNDS to 1,1,1 (https://github.com/ray-project/ray/blob/8e779d8152f15ec7d91a1a8fc8b6f10a3d3d839d/python/ray/_private/accelerators/tpu.py#L847), overwriting the host bounds set by PlatformTPU.

    wuxibin89 wuxibin89 approved these changes on Sep 20, 2026 02:20 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    askhat-g askhat-g
    Labels
    risk: low confidence: 81.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 40.2% (MEDIUM) · Higher = larger blast radius
    40.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 81.6% · Lower = rushed or shallow review
    81.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.4% · Safe to merge
    7.4%