Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions roll/distributed/executor/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ def is_pipeline_last_stage(self):
class Worker:

def __init__(self, worker_config: WorkerConfig):
current_platform.select_assigned_devices()
if worker_config.offload_nccl:
# Validate the server-provided runtime in every worker before loading
# models or allocating distributed training state.
Expand Down
4 changes: 4 additions & 0 deletions roll/platforms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from .cuda import CudaPlatform
from .npu import NpuPlatform
from .rocm import RocmPlatform
from .xpu import XpuPlatform
from .unknown import UnknownPlatform
from .cpu import CpuPlatform

Expand Down Expand Up @@ -36,6 +37,9 @@ def _init_platform() -> Platform:
return RocmPlatform()
logger.warning("Unrecognized CUDA device. Falling back to UnknownPlatform.")
return UnknownPlatform()
elif torch.xpu.is_available():
logger.debug("Detected Intel XPU. Initializing XPU platform.")
return XpuPlatform()
else:
try:
import torch_npu # noqa: F401
Expand Down
17 changes: 17 additions & 0 deletions roll/platforms/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ class Platform:
# Examples: "nccl", "hccl"
communication_backend: str

# Whether colocated weight updates can share device tensors through IPC; otherwise broadcast is used.
supports_tensor_ipc: bool = True

def __getattr__(self, key: str):
"""Fallback attribute accessor for device-specific Torch modules.

Expand Down Expand Up @@ -101,6 +104,10 @@ def is_npu(cls) -> bool:
def is_rocm(cls) -> bool:
return False

@classmethod
def is_xpu(cls) -> bool:
return False

@classmethod
def clear_cublas_workspaces(cls) -> None:
raise NotImplementedError
Expand Down Expand Up @@ -159,6 +166,16 @@ def get_visible_gpus(cls) -> list:
return os.environ.get(cls.device_control_env_var, "").split(",")
return []

@classmethod
def select_assigned_devices(cls) -> None:
"""Select the physical device assigned to the current worker."""
return

@classmethod
def get_vllm_device_kwargs(cls, engine_kwargs: dict) -> dict:
"""Return platform-specific device assignments for vLLM."""
return {}

@classmethod
def get_vllm_worker_class(cls):
"""Return the custom vLLM WorkerWrapper class used in Ray."""
Expand Down
127 changes: 127 additions & 0 deletions roll/platforms/xpu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import os

import torch

from ..utils.logging import get_logger
from .platform import Platform

logger = get_logger()


class XpuPlatform(Platform):
device_name: str = "INTEL"
device_type: str = "xpu"
dispatch_key: str = "XPU"
ray_device_key: str = "GPU"
device_control_env_var: str = "ZE_AFFINITY_MASK"
ray_experimental_noset: str = "RAY_EXPERIMENTAL_NOSET_ONEAPI_DEVICE_SELECTOR"
assigned_devices_env_var: str = "ROLL_ASSIGNED_XPU_IDS"
communication_backend: str = "xccl"
supports_tensor_ipc: bool = False

@classmethod
def is_xpu(cls) -> bool:
return True

@classmethod
def clear_cublas_workspaces(cls) -> None:
return

@classmethod
def set_allocator_settings(cls, env: str) -> None:
return

@classmethod
def reset_max_memory_allocated(cls, device=None) -> None:
torch.xpu.reset_peak_memory_stats(device)

@classmethod
def reset_max_memory_cached(cls, device=None) -> None:
torch.xpu.reset_peak_memory_stats(device)

@classmethod
def get_custom_env_vars(cls) -> dict:
env_vars = {
**Platform.get_common_envs(),
"RAY_get_check_signal_interval_milliseconds": "1",
"VLLM_ALLOW_INSECURE_SERIALIZATION": "1",
"RAY_CGRAPH_get_timeout": "600",
}
return env_vars

@classmethod
def update_env_vars_for_visible_devices(cls, env_vars: dict, gpu_ranks: list) -> None:
# Keep node-local XPUs visible so XCCL ranks share a consistent device view; each worker selects its XPU.
visible_devices_env_vars = {
cls.assigned_devices_env_var: ",".join(map(str, gpu_ranks)),
# Compatibility for components that derive their device from LOCAL_RANK.
"LOCAL_RANK": str(gpu_ranks[0]),
cls.ray_experimental_noset: "1",
}
env_vars.update(visible_devices_env_vars)

@classmethod
def get_visible_gpus(cls) -> list:
return os.environ.get(cls.assigned_devices_env_var, "").split(",")

@classmethod
def select_assigned_devices(cls) -> None:
assigned = os.environ.get(cls.assigned_devices_env_var)
if not assigned:
return
if os.environ.get(cls.device_control_env_var):
raise RuntimeError(
f"{cls.device_control_env_var}={os.environ[cls.device_control_env_var]} is not supported with "
"explicit XPU placement because ROLL cannot verify consistent XPU visibility across ranks; "
f"unset it to use the assigned XPUs ({cls.assigned_devices_env_var}={assigned})"
)
device = int(assigned.split(",")[0])
torch.xpu.set_device(device)
logger.info(
f"XPU placement: rank={os.environ.get('RANK')} assigned={assigned} "
f"current_device={device} uuid={torch.xpu.get_device_properties(device).uuid}"
)

@classmethod
def get_vllm_device_kwargs(cls, engine_kwargs: dict) -> dict:
assigned = os.environ.get(cls.assigned_devices_env_var)
if not assigned:
return {}
import vllm
from packaging.version import Version

if Version(vllm.__version__) < Version("0.31.0"):
raise RuntimeError(f"vLLM {vllm.__version__} ignores device_ids on XPU; vLLM >= 0.31 is required")
device_ids = [int(i) for i in assigned.split(",")]
if int(engine_kwargs.get("data_parallel_size") or 1) > 1:
# vLLM's XPU worker picks its slot in device_ids from the DP rank; place the assigned XPUs in that slot.
device_count = torch.xpu.device_count()
slots = device_count // len(device_ids)
start = int(engine_kwargs.get("data_parallel_rank") or 0) % slots * len(device_ids)
others = [i for i in range(device_count) if i not in device_ids]
device_ids = others[:start] + device_ids + others[start:]
return {"device_ids": device_ids}

@classmethod
def get_vllm_worker_class(cls):
try:
from vllm.v1.worker.xpu_worker import XPUWorker

logger.info("Successfully imported vLLM XPU Worker.")
return XPUWorker
except ImportError as e:
logger.error("Failed to import vLLM Worker. Make sure vLLM is installed correctly: %s", e)
raise RuntimeError("vLLM is not installed or not properly configured.") from e

@classmethod
def get_vllm_run_time_env_vars(cls, gpu_rank: str) -> dict:
env_vars = {
"VLLM_ALLOW_INSECURE_SERIALIZATION": "1",
"ZE_AFFINITY_MASK": f"{gpu_rank}",
"RAY_EXPERIMENTAL_NOSET_ONEAPI_DEVICE_SELECTOR": "1",
}
return env_vars

@classmethod
def apply_ulysses_patch(cls) -> None:
return
2 changes: 1 addition & 1 deletion roll/third_party/fsdp2/model_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def __init__(
self.infer_cluster = infer_cluster
self.is_colocated = is_actor_infer_overlapping_with_any_cluster(
infer_cluster.worker_config, actor_train=worker_config
)
) and current_platform.supports_tensor_ipc

# Colocated mode attributes
self._infer_parallel_cpu_group = None
Expand Down
4 changes: 3 additions & 1 deletion roll/third_party/vllm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ async def create_async_llm(resource_placement_groups: List[Dict], headless: bool
f"got {data_parallel_backend!r}."
)
kwargs["distributed_executor_backend"] = executor_backend or "mp"
kwargs.update(current_platform.get_vllm_device_kwargs(kwargs))
if "data_parallel_backend" in engine_arg_names:
kwargs["data_parallel_backend"] = "mp"
else:
Expand Down Expand Up @@ -113,7 +114,8 @@ async def create_async_llm(resource_placement_groups: List[Dict], headless: bool
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = ""
# torch.cuda may already init, explicitly disable expandable_segments
# here (only matters when VLLM_USE_RAY_SPMD_WORKER=0)
current_platform.memory._set_allocator_settings("expandable_segments:False")
if hasattr(current_platform.memory, "_set_allocator_settings"):
current_platform.memory._set_allocator_settings("expandable_segments:False")

os.environ["VLLM_CACHE_ROOT"] = os.path.join(get_default_cache_root(), "vllm", os.environ.get("WORKER_NAME", ""))

Expand Down
2 changes: 1 addition & 1 deletion roll/utils/offload_states.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def clear_memory(clear_host_memory: bool = False):
if clear_host_memory:
if current_platform.is_npu():
torch.npu.host_empty_cache()
else:
elif hasattr(torch._C, "_host_emptyCache"):
torch._C._host_emptyCache()


Expand Down
3 changes: 3 additions & 0 deletions roll/utils/ray_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

@ray.remote
def get_visible_gpus(device_control_env_var: str):
# Ray may export a different visibility variable (e.g. ONEAPI_DEVICE_SELECTOR for XPU); use Ray's IDs.
if device_control_env_var not in os.environ:
return [str(gpu_id) for gpu_id in ray.get_gpu_ids()]
return os.environ.get(device_control_env_var, "").split(",")


Expand Down