Skip to content

Commit f70037b

Browse files
noemotiovonFightingZhenlowdy1
authored andcommitted
feat: add device abstraction and Ascend NPU support
This commit introduces native support for Ascend NPUs in the ROLL project while maintaining compatibility with existing CUDA-based infrastructure. Key changes include: - Added a unified device abstraction interface for initialization, memory management, and synchronization, enabling extensibility for both CUDA and Ascend. - Replaced direct usage of Ray CUDA resource APIs with the new abstraction layer to support heterogeneous multi-device environments. - Integrated Ascend inference backend via vLLM + vLLM-Ascend. - Added experimental training support with DeepSpeed on Ascend hardware. - Added documentation for Ascend usage. This enhancement lays the foundation for seamless switching between CUDA and Ascend devices. Future work: - Add inference support for SGLang on Ascend NPUs. - Add training support for Megatron on Ascend NPUs. - Add training support for FSDP on Ascend NPUs. - Add support for vLLM versions >= 0.10. - Provide documentation with accuracy and performance benchmarks. Co-authored-by: noemotiovon <757486878@qq.com> Co-authored-by: FightingZhen <295632982@qq.com> Co-authored-by: lowdy1 <xiahouweidong@gmail.com>
1 parent 061732d commit f70037b

78 files changed

Lines changed: 1870 additions & 531 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

docs/ascend/ascend_roll.md

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
# ROLL x Ascend
2+
3+
Last updated: 09/04/2025.
4+
5+
我们在 ROLL 上增加对华为昇腾设备的支持。
6+
7+
## 硬件支持
8+
9+
Atlas 900 A2 PODc
10+
11+
12+
## 安装
13+
14+
15+
### 基础环境准备
16+
17+
| software | version |
18+
|-----------|-------------|
19+
| Python | 3.10 |
20+
| CANN | 8.1.RC1 |
21+
22+
### 创建 conda 环境
23+
24+
25+
使用以下命令在 Miniconda 中创建新的 conda 环境:
26+
27+
```
28+
conda create --name roll python=3.10
29+
conda activate roll
30+
```
31+
32+
### 安装 torch & torch_npu:
33+
34+
35+
为了能在 ROLL 中正常使用 torch 和 torch_npu,需使用以下命令安装 torch 和 torch_npu。
36+
37+
```
38+
# 安装 torch 的 CPU 版本
39+
pip install torch==2.5.1 torchvision==0.20.1 torchaudio==2.5.1 --index-url https://download.pytorch.org/whl/cpu
40+
41+
# 安装 torch_npu
42+
pip install torch_npu==2.5.1
43+
```
44+
45+
46+
### 安装vllm & vllm-ascend:
47+
48+
为了能够在 ROLL 中正常使用 vllm,需使用以下命令编译安装 vllm 和 vllm-ascend。
49+
50+
```
51+
# vllm
52+
git clone -b v0.8.4 --depth 1 https://github.com/vllm-project/vllm.git
53+
cd vllm
54+
55+
VLLM_TARGET_DEVICE=empty pip install -v -e .
56+
cd ..
57+
```
58+
59+
```
60+
# vllm-ascend
61+
git clone -b v0.8.4rc2 --depth 1 https://github.com/vllm-project/vllm-ascend.git
62+
cd vllm-ascend
63+
64+
export COMPILE_CUSTOM_KERNELS=1
65+
pip install -e .
66+
cd ..
67+
```
68+
69+
如果在安装 vllm-ascend 时遇到类似以下问题:
70+
71+
```
72+
RuntimeError: CMake configuration failed: Command '['/pathto/miniconda3/envs/roll/bin/python3.10', '-m', 'pybind11', '--cmake']' returned non-zero exit status 2.
73+
```
74+
75+
可尝试在 vllm-ascend 目录下 setup.py 文件 151-158 行进行如下修改并重新进行编译:
76+
77+
```
78+
try:
79+
# if pybind11 is installed via pip
80+
pybind11_cmake_path = (subprocess.check_output(
81+
[python_executable, "-m", "pybind11",
82+
"--cmakedir"]).decode().strip())
83+
except subprocess.CalledProcessError as e:
84+
# else specify pybind11 path installed from source code on CI container
85+
raise RuntimeError(f"CMake configuration failed: {e}")
86+
```
87+
88+
### 安装 ROLL
89+
90+
```
91+
git clone https://github.com/alibaba/ROLL.git
92+
cd ROLL
93+
pip install -r requirements_common.txt
94+
pip install deepspeed==0.16.0
95+
cd ..
96+
```
97+
98+
### 其他三方库说明
99+
100+
| software | description |
101+
|-------------------------------|---------------|
102+
| transformers | v4.52.4 |
103+
| flash_attn | not supported |
104+
| transformer-engine[pytorch] | not supported |
105+
106+
1. 支持通过 transformers 使能 --flash_attention_2, transformers 需等于 4.52.4版本。
107+
2. 不支持通过 flash_attn 使能 flash attention 加速。
108+
3. 暂不支持 transformer-engine[pytorch]
109+
110+
```
111+
pip install transformers==4.52.4
112+
```
113+
114+
## 快速开始,单节点部署指引
115+
116+
正式使用前,建议您通过对单节点流水线的训练尝试以检验环境准备和安装的正确性。
117+
由于目前暂不支持 Megatron-LM 训练,请首先将对应文件中
118+
strategy_args 参数修改为 deepspeed 选项。
119+
120+
1. 使用 shell 执行单节点流水线
121+
122+
```
123+
bash examples/agentic_demo/run_agentic_pipeline_frozen_lake_single_node_demo.sh
124+
```
125+
126+
2. 使用配置文件执行 agentic pipeline
127+
128+
```
129+
# 确保当前位于ROLL项目目录的根目录下
130+
# export PYTHONPATH=$(pwd):$PYTHONPATH
131+
132+
python examples/start_agentic_pipeline.py \
133+
--config_path qwen2.5-0.5B-agentic \
134+
--config_name agentic_val_sokoban
135+
136+
- ``--config_path`` – 包含您的YAML配置文件的目录。
137+
- ``--config_name`` – 文件名(不含.yaml后缀)。
138+
```
139+
140+
## 支持现状
141+
142+
| Feature | Example | Training Backend | Inference Backend | Hardware |
143+
| --------------- | ------------------------------------------------------------ | ---------------- | ----------------- | ----------------- |
144+
| Agentic | examples/qwen2.5-0.5B-agentic/run_agentic_pipeline_sokoban.sh | DeepSpeed | vLLM | Atlas 900 A2 PODc |
145+
| Agentic-Rollout | examples/qwen2.5-0.5B-agentic/run_agentic_rollout_sokoban.sh | DeepSpeed | vLLM | Atlas 900 A2 PODc |
146+
| DPO | examples/qwen2.5-3B-dpo_megatron/run_dpo_pipeline.sh | DeepSpeed | vLLM | Atlas 900 A2 PODc |
147+
| RLVR | examples/qwen2.5-7B-rlvr_megatron/run_rlvr_pipeline.sh | DeepSpeed | vLLM | Atlas 900 A2 PODc |
148+
149+
150+
## 声明
151+
ROLL 中提供的 Ascend 支持代码皆为参考样例,生产环境使用请通过官方正式途径沟通,谢谢。

docs/qa.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ profiler_output_dir: /data/oss_bucket_0/yali/llm/profile/${exp_name}
6363
6464
0. **如何debug代码**
6565
66-
在RayUtils的env中设置 "RAY_DEBUG": "legacy" , 就可以采用pdb进行单步调试
66+
在对应后端的Platform的env中设置 "RAY_DEBUG": "legacy" , 就可以采用pdb进行单步调试
6767
6868
6969
0. **如果出现这种错误: self.node2pg[node_rank] KeyError: 1**

docs_roll/docs/English/QuickStart/qa_issues.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ Then use the [Perfetto UI](https://ui.perfetto.dev/) tool for analysis.
9292

9393
### How to debug code?
9494

95-
Set `"RAY_DEBUG": "legacy"` in RayUtils' env, and then you can use pdb for step-by-step debugging.
95+
Set `"RAY_DEBUG": "legacy"` in Platform' env, and then you can use pdb for step-by-step debugging.
9696

9797
## Common Errors and Solutions
9898

docs_roll/docs/简体中文/快速开始/qa_issues.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ profiler_output_dir: /data/oss_bucket_0/yali/llm/profile/${exp_name}
9292

9393
### 如何 debug 代码?
9494

95-
RayUtils 的 env 中设置 `"RAY_DEBUG": "legacy"`,就可以采用 pdb 进行单步调试。
95+
Platform 的 env 中设置 `"RAY_DEBUG": "legacy"`,就可以采用 pdb 进行单步调试。
9696

9797
## 常见错误及解决方案
9898

mcore_adapter/src/mcore_adapter/initialize.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
from .training_args import TrainingArguments
99
from .utils import get_logger
1010

11+
from .platforms import current_platform
12+
1113

1214
logger = get_logger(__name__)
1315

@@ -28,7 +30,7 @@ def _set_random_seed(seed_):
2830
random.seed(seed)
2931
np.random.seed(seed)
3032
torch.manual_seed(seed)
31-
if torch.cuda.device_count() > 0:
33+
if current_platform.device_count() > 0:
3234
tensor_parallel.model_parallel_cuda_manual_seed(seed)
3335
else:
3436
raise ValueError("Seed ({}) should be a positive integer.".format(seed))
@@ -45,10 +47,10 @@ def _initialize_distributed(args: "TrainingArguments"):
4547
logger.info(f"Initializing mpu on device {args.device}")
4648
if not torch.distributed.is_initialized():
4749
# Manually set the device ids.
48-
torch.cuda.set_device(args.device)
50+
current_platform.set_device(args.device)
4951
# Call the init process
5052
torch.distributed.init_process_group(
51-
backend=args.ddp_backend or "nccl",
53+
backend=args.ddp_backend or current_platform.communication_backend,
5254
rank=int(os.getenv("RANK", "0")),
5355
world_size=int(os.getenv("WORLD_SIZE", "1")),
5456
timeout=args.ddp_timeout_delta,

mcore_adapter/src/mcore_adapter/models/converter/convert_utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import torch.distributed as dist
88
from megatron.core import mpu
99
from packaging.version import Version as PkgVersion
10+
from ...platforms import current_platform
1011

1112

1213
if TYPE_CHECKING:
@@ -286,7 +287,7 @@ def is_full(self):
286287
class SendBucketManager:
287288
def __init__(self, bucket_size):
288289
self.bucket_size = bucket_size
289-
self.bucket = TensorBucket(bucket_size)
290+
self.bucket = TensorBucket(bucket_size, current_platform.device_type)
290291

291292
def push_tensor(self, tensor: "torch.Tensor", name: str):
292293
tensor_start = 0

mcore_adapter/src/mcore_adapter/models/model_factory.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from .converter.model_converter import ModelConverter
2121
from .model_config import McaModelConfig
2222
from .model_utils import ModuleUtilsMixin, RMSNorm, exists_hf_config, exists_mca_config, get_thd_data_on_this_cp_rank
23+
from ..platforms import current_platform
2324

2425

2526
if TYPE_CHECKING:
@@ -233,7 +234,8 @@ def get_batch_on_this_cp_rank(self, batch: Dict[str, "torch.Tensor"], dim3_keys:
233234
val.shape[seq_dim] // (2 * cp_size),
234235
*val.shape[(seq_dim + 1) :],
235236
)
236-
index = torch.tensor([cp_rank, (2 * cp_size - cp_rank - 1)], device="cpu", pin_memory=True).cuda(
237+
index = torch.tensor([cp_rank, (2 * cp_size - cp_rank - 1)], device="cpu", pin_memory=True).to(
238+
current_platform.device_type,
237239
non_blocking=True
238240
)
239241
val = val.index_select(seq_dim, index)
@@ -271,7 +273,7 @@ def __init__(self, config: "McaModelConfig", **kwargs):
271273
for param in self.parameters():
272274
tensor_parallel.set_defaults_if_not_set_tensor_model_parallel_attributes(param)
273275
if not config.use_cpu_initialization:
274-
self.cuda(torch.cuda.current_device())
276+
self.to(current_platform.current_device())
275277

276278
def _get_transformer_layer_spec(self, config: Optional["McaModelConfig"] = None):
277279
config = config or self.config

mcore_adapter/src/mcore_adapter/models/model_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from ..constants import MCA_CONFIG_NAME
1111
from ..utils import get_logger
12-
12+
from ..platforms import current_platform
1313

1414
if TYPE_CHECKING:
1515
from megatron.core.transformer import TransformerConfig
@@ -93,7 +93,7 @@ def floating_point_ops(
9393
class RMSNorm(nn.Module):
9494
def __init__(self, config: "TransformerConfig", hidden_size, eps=1e-6, **kwargs):
9595
super().__init__()
96-
device = torch.cuda.current_device() if not config.use_cpu_initialization else None
96+
device = current_platform.current_device() if not config.use_cpu_initialization else None
9797
self.weight = torch.nn.Parameter(torch.ones(hidden_size, dtype=config.params_dtype, device=device))
9898
self.variance_epsilon = eps
9999

mcore_adapter/src/mcore_adapter/models/qwen2_5_vl/modeling_qwen2_5_vl.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import torch
44
from megatron.core import mpu
55

6+
from ...platforms import current_platform
67
from ..auto.modeling_auto import register_model
78
from ..model_factory import McaGPTModel
89
from ..model_utils import ModuleUtilsMixin
@@ -24,7 +25,7 @@ def __init__(self, config: "Qwen2_5_VLConfig", **kwargs):
2425
Qwen2_5_VLVisionConfig(**config.vision_config),
2526
attn_implementation="flash_attention_2",
2627
torch_dtype=self.config.params_dtype,
27-
).to(torch.cuda.current_device())
28+
).to(current_platform.current_device())
2829
for param in self.vision_model.parameters():
2930
setattr(param, "sequence_parallel", config.sequence_parallel)
3031

mcore_adapter/src/mcore_adapter/models/qwen2_vl/modeling_qwen2_vl.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import torch
44
from megatron.core import mpu
55

6+
from ...platforms import current_platform
67
from ..auto.modeling_auto import register_model
78
from ..model_factory import McaGPTModel
89
from ..model_utils import ModuleUtilsMixin
@@ -24,7 +25,7 @@ def __init__(self, config: "Qwen2VLConfig", **kwargs):
2425
Qwen2VLVisionConfig(**config.vision_config),
2526
attn_implementation="sdpa",
2627
torch_dtype=self.config.params_dtype,
27-
).to(torch.cuda.current_device())
28+
).to(current_platform.current_device())
2829
for param in self.vision_model.parameters():
2930
setattr(param, "sequence_parallel", config.sequence_parallel)
3031

0 commit comments

Comments
 (0)