Skip to content

Commit 46d485f

Browse files
committed
add other platform and refactory
Signed-off-by: noemotiovon <757486878@qq.com>
1 parent 2d5b2b6 commit 46d485f

17 files changed

Lines changed: 256 additions & 220 deletions

File tree

roll/distributed/executor/cluster.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
from roll.distributed.scheduler.resource_manager import ResourceManager
2323
from roll.utils.import_utils import safe_import_class
2424
from roll.utils.logging import get_logger
25-
from roll.utils.ray_utils import RayUtils
2625

2726
logger = get_logger()
2827

@@ -114,9 +113,7 @@ def _create_workers(self):
114113
env_vars["MASTER_ADDR"] = self.master_addr
115114
env_vars["MASTER_PORT"] = str(self.master_port)
116115
if deploy_pg["gpu_rank"] is not None:
117-
RayUtils.update_env_vars_for_visible_devices(
118-
env_vars=env_vars,
119-
gpu_ranks=pg_zero_gpu_ranks)
116+
current_platform.update_env_vars_for_visible_devices(env_vars=env_vars, gpu_ranks=pg_zero_gpu_ranks)
120117
if "ROLL_LOG_DIR" in os.environ:
121118
env_vars["ROLL_LOG_DIR"] = os.environ["ROLL_LOG_DIR"]
122119
env_vars.update(self.worker_config.system_envs)
@@ -135,10 +132,14 @@ def _create_workers(self):
135132
if current_platform.ray_device_key == "GPU":
136133
worker_options.update({"num_gpus": 0.01 if self.worker_config.device_mapping else 0})
137134
elif current_platform.ray_device_key == "NPU":
138-
worker_options.update({
139-
"num_cpus": 0,
140-
"resources": {current_platform.ray_device_key: 0.01 if self.worker_config.device_mapping else 0},
141-
})
135+
worker_options.update(
136+
{
137+
"num_gpus": 0,
138+
"resources": {
139+
current_platform.ray_device_key: 0.01 if self.worker_config.device_mapping else 0
140+
},
141+
}
142+
)
142143

143144
worker = self.worker_cls.options(**worker_options).remote(worker_config=self.worker_config)
144145
self.workers.append(worker)

roll/distributed/executor/worker.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@
1717
from roll.utils.logging import get_logger
1818
from roll.utils.offload_states import OffloadStateType
1919
from roll.platforms import current_platform
20-
from roll.utils.ray_utils import RayUtils
21-
from roll.platforms import current_platform
2220

2321

2422
@dataclass
@@ -121,7 +119,7 @@ def get_master_addr_and_port(self):
121119

122120
@staticmethod
123121
def get_visible_gpus():
124-
return RayUtils.get_visible_gpus()
122+
return current_platform.get_visible_gpus()
125123

126124
def get_devices_info(self):
127125
devices_info = [

roll/distributed/scheduler/driver_utils.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,27 +15,27 @@ def is_driver():
1515

1616

1717
def get_driver_rank():
18-
assert is_driver(), "this function should only be ran on a driver"
18+
assert is_driver(), "this function should only be run on a driver"
1919
return int(os.getenv("RANK", "0"))
2020

2121

2222
def get_driver_world_size():
23-
assert is_driver(), "this function should only be ran on a driver"
23+
assert is_driver(), "this function should only be run on a driver"
2424
return int(os.getenv("WORLD_SIZE", "1"))
2525

2626

2727
def get_driver_master_addr():
28-
assert is_driver(), "this function should only be ran on a driver"
28+
assert is_driver(), "this function should only be run on a driver"
2929
return os.getenv("MASTER_ADDR", "127.0.0.1")
3030

3131

3232
def get_driver_master_port():
33-
assert is_driver(), "this function should only be ran on a driver"
33+
assert is_driver(), "this function should only be run on a driver"
3434
return os.getenv("MASTER_PORT", "6379")
3535

3636

3737
def get_driver_node_name():
38-
assert is_driver(), "this function should only be ran on a driver"
38+
assert is_driver(), "this function should only be run on a driver"
3939
return os.getenv("WORKER_ID", f"{get_driver_master_addr()}:{get_driver_rank()}")
4040

4141
def is_multi_tenant():

roll/distributed/scheduler/initialize.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from roll.distributed.scheduler.log_monitor import LogMonitorListener
1919
from roll.utils.constants import RAY_NAMESPACE
2020
from roll.utils.logging import get_logger
21-
from roll.utils.ray_utils import RayUtils
21+
from roll.platforms import current_platform
2222

2323
logger = get_logger()
2424

@@ -60,7 +60,7 @@ def init():
6060
manual_start = start_ray_cluster()
6161

6262
runtime_env = {
63-
"env_vars": RayUtils.get_custom_env_env_vars(),
63+
"env_vars": current_platform.get_custom_env_vars(),
6464
}
6565

6666
if not ray.is_initialized():

roll/distributed/scheduler/resource_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def __init__(self, num_gpus_per_node, num_nodes):
5555
if current_platform.ray_device_key == "GPU"
5656
else {"resources": {current_platform.ray_device_key: self.gpu_per_node}}
5757
)
58-
).remote(current_platform.ray_device_key)
58+
).remote(current_platform.device_control_env_var)
5959
for pg in self.placement_groups
6060
])
6161
print(f"gpu ranks: {gpu_ranks}")

roll/platforms/__init__.py

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,56 @@
1-
import logging
1+
import torch
2+
23
from .platform import Platform
34
from .cuda import CudaPlatform
4-
from .npu import NPUPlatform
5+
from .npu import NpuPlatform
6+
from .rocm import RocmPlatform
7+
from .unknown import UnknownPlatform
8+
from .cpu import CpuPlatform
9+
10+
from roll.utils.logging import get_logger
11+
12+
13+
logger = get_logger()
514

6-
logger = logging.getLogger(__name__)
715

816
def _init_platform() -> Platform:
9-
"""Initialize and return the current platform instance.
17+
"""
18+
Detect and initialize the appropriate platform based on available devices.
19+
20+
Priority:
21+
1. CUDA (NVIDIA / AMD ROCm)
22+
2. NPU (if torch_npu is installed)
23+
3. CPU (fallback)
1024
11-
Automatically selects the platform based on environment and availability:
12-
- If torch_npu is installed, use NPUPlatform.
13-
- Otherwise, fall back to CudaPlatform.
25+
Returns:
26+
An instance of a subclass of Platform corresponding to the detected hardware.
1427
"""
15-
try:
16-
import torch_npu # noqa: F401
17-
logger.info("Detected torch_npu. Initializing NPU platform.")
18-
return NPUPlatform()
19-
except ImportError:
20-
logger.info("Initializing ROLL default device backend: Cuda platform.")
21-
return CudaPlatform()
28+
if torch.cuda.is_available():
29+
device_name = torch.cuda.get_device_name().upper()
30+
logger.info(f"Detected CUDA device: {device_name}")
31+
if "NVIDIA" in device_name:
32+
logger.info("Initializing CUDA platform (NVIDIA).")
33+
return CudaPlatform()
34+
elif "AMD" in device_name:
35+
logger.info("Initializing ROCm platform (AMD).")
36+
return RocmPlatform()
37+
logger.warning("Unrecognized CUDA device. Falling back to UnknownPlatform.")
38+
return UnknownPlatform()
39+
else:
40+
try:
41+
import torch_npu # noqa: F401
42+
43+
logger.info("Detected torch_npu. Initializing NPU platform.")
44+
return NpuPlatform()
45+
except ImportError:
46+
logger.info("No supported accelerator detected. Initializing CPU platform.")
47+
return CpuPlatform()
48+
2249

2350
# Global singleton representing the current platform in use.
2451
current_platform: Platform = _init_platform()
2552

2653
__all__ = [
2754
"Platform",
2855
"current_platform",
29-
]
56+
]

roll/platforms/cpu.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from .platform import Platform
2+
from roll.utils.logging import get_logger
3+
4+
5+
logger = get_logger()
6+
7+
8+
class CpuPlatform(Platform):
9+
device_name: str = "CPU"
10+
device_type: str = "cpu"
11+
dispatch_key: str = "CPU"
12+
ray_device_key: str = "CPU"
13+
communication_backend: str = "gloo"
14+
15+
@classmethod
16+
def clear_cublas_workspaces(cls):
17+
pass
18+
19+
@classmethod
20+
def get_custom_env_vars(cls) -> dict:
21+
return {}

roll/platforms/cuda.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
from .platform import Platform
2-
from roll.utils.logging import logger
2+
from roll.utils.logging import get_logger
33

44
import torch
55

6+
logger = get_logger()
7+
8+
69
class CudaPlatform(Platform):
10+
device_name: str = "NVIDIA"
711
device_type: str = "cuda"
812
dispatch_key: str = "CUDA"
913
ray_device_key: str = "GPU"
@@ -14,24 +18,37 @@ class CudaPlatform(Platform):
1418
@classmethod
1519
def clear_cublas_workspaces(cls):
1620
torch._C._cuda_clearCublasWorkspaces()
17-
21+
1822
@classmethod
1923
def get_vllm_worker_class(clas):
2024
try:
2125
from vllm import envs
26+
2227
if envs.VLLM_USE_V1:
2328
from vllm.v1.worker.gpu_worker import Worker
29+
2430
logger.info("Successfully imported vLLM V1 Worker.")
2531
return Worker
2632
else:
2733
from vllm.worker.worker import Worker
34+
2835
logger.info("Successfully imported vLLM V0 Worker.")
2936
return Worker
3037
except ImportError as e:
31-
logger.error("Failed to import vLLM Worker. "
32-
"Make sure vLLM is installed correctly: %s", e)
38+
logger.error("Failed to import vLLM Worker. " "Make sure vLLM is installed correctly: %s", e)
3339
raise RuntimeError("vLLM is not installed or not properly configured.") from e
34-
40+
3541
@classmethod
3642
def set_allocator_settings(cls):
3743
torch.cuda.memory._set_allocator_settings("expandable_segments:False")
44+
45+
@classmethod
46+
def get_custom_env_vars(cls) -> dict:
47+
env_vars = {
48+
# "RAY_DEBUG": "legacy"
49+
"TORCHINDUCTOR_COMPILE_THREADS": "2",
50+
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
51+
"NCCL_CUMEM_ENABLE": "0", # https://github.com/NVIDIA/nccl/issues/1234
52+
"NCCL_NVLS_ENABLE": "0",
53+
}
54+
return env_vars

roll/platforms/npu.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
from .platform import Platform
2-
from roll.utils.logging import logger
2+
from roll.utils.logging import get_logger
33

4-
import torch
4+
logger = get_logger()
55

6-
class NPUPlatform(Platform):
6+
7+
class NpuPlatform(Platform):
8+
device_name: str = "ASCEND"
79
device_type: str = "npu"
810
dispatch_key: str = "PrivateUse1"
911
ray_device_key: str = "NPU"
@@ -14,24 +16,33 @@ class NPUPlatform(Platform):
1416
@classmethod
1517
def clear_cublas_workspaces(cls):
1618
pass
17-
19+
1820
@classmethod
1921
def get_vllm_worker_class(clas):
2022
try:
2123
from vllm import envs
24+
2225
if envs.VLLM_USE_V1:
2326
from vllm_ascend.worker.worker_v1 import NPUWorker as Worker
27+
2428
logger.info("Successfully imported vLLM V1 Worker.")
2529
return Worker
2630
else:
2731
from vllm_ascend.worker.worker import NPUWorker as Worker
32+
2833
logger.info("Successfully imported vLLM V0 Worker.")
2934
return Worker
3035
except ImportError as e:
31-
logger.error("Failed to import vLLM Worker. "
32-
"Make sure vLLM is installed correctly: %s", e)
36+
logger.error("Failed to import vLLM Worker. " "Make sure vLLM is installed correctly: %s", e)
3337
raise RuntimeError("vLLM is not installed or not properly configured.") from e
34-
38+
3539
@classmethod
3640
def set_allocator_settings(cls):
3741
pass
42+
43+
@classmethod
44+
def get_custom_env_vars(cls) -> dict:
45+
env_vars = {
46+
"TORCHINDUCTOR_COMPILE_THREADS": "2",
47+
}
48+
return env_vars

roll/platforms/platform.py

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import torch
2-
from roll.utils.logging import logger
2+
import os
3+
4+
from roll.utils.logging import get_logger
5+
6+
logger = get_logger()
37

48

59
class Platform:
@@ -23,7 +27,12 @@ class Platform:
2327
- `get_vllm_worker_class`: to specify the vLLM Ray worker class.
2428
- `set_allocator_settings`: to configure platform-specific memory allocators.
2529
"""
26-
# Corresponding torch module name, e.g., "cuda", "npu"
30+
# High-level platform name, used for readability and logging.
31+
# Examples: "NVIDIA", "AMD", "ASCEND"
32+
device_name: str
33+
34+
# Corresponding torch module name
35+
# Examples: "cuda", "npu"
2736
device_type: str
2837

2938
# available dispatch keys:
@@ -92,3 +101,21 @@ def get_vllm_worker_class(cls):
92101
def set_allocator_settings(cls):
93102
"""Configure memory allocator settings based on the device type."""
94103
raise NotImplementedError
104+
105+
@classmethod
106+
def get_custom_env_vars(cls) -> dict:
107+
raise NotImplementedError
108+
109+
@classmethod
110+
def update_env_vars_for_visible_devices(cls, env_vars: dict, gpu_ranks: list):
111+
visible_devices_env_vars = {
112+
cls.device_control_env_var: ",".join(map(str, gpu_ranks)),
113+
cls.ray_experimental_noset: "1",
114+
}
115+
env_vars.update(visible_devices_env_vars)
116+
117+
@classmethod
118+
def get_visible_gpus(cls) -> list:
119+
if cls.device_control_env_var is not None:
120+
return os.environ.get(cls.device_control_env_var, "").split(",")
121+
return []

0 commit comments

Comments
 (0)