Skip to content

Commit e2b7735

Browse files
authored
[megatron] feat: Add MindSpeed support on the NPU device (verl-project#2707)
### What does this PR do? Add MindSpeed(Megatron) support on the NPU device. First, import the Megatron adapter to avoid import errors, and reapply the patch according to the configuration. ### Checklist Before Starting - [x] Search for similar PRs. Paste at least one query link here: ... - [x] Format the PR title as `[{modules}] {type}: {description}` (This will be checked by the CI) - `{modules}` include `fsdp`, `megatron`, `sglang`, `vllm`, `rollout`, `trainer`, `ci`, `training_utils`, `recipe`, `hardware`, `deployment`, `ray`, `worker`, `single_controller`, `misc`, `perf`, `model`, `algo`, `env`, `tool`, `ckpt`, `doc`, `data` - If this PR involves multiple modules, separate them with `,` like `[megatron, fsdp, doc]` - `{type}` is in `feat`, `fix`, `refactor`, `chore`, `test` - If this PR breaks any API (CLI arguments, config, function signature, etc.), add `[BREAKING]` to the beginning of the title. - Example: `[BREAKING][fsdp, megatron] feat: dynamic batching` ### Test > For changes that can not be tested by CI (e.g., algorithm implementation, new model support), validate by experiment(s) and show results like training curve plots, evaluation results, etc. ### API and Usage Example > Demonstrate how the API changes if any, and provide usage example(s) if possible. ```python # Add code snippet or script demonstrating how to use this ``` ### Design & Code Changes > Demonstrate the high-level design if this PR is complex, and list the specific changes. ### Checklist Before Submitting > [!IMPORTANT] > Please check all the following items before requesting a review, otherwise the reviewer might deprioritize this PR for review. - [x] Read the [Contribute Guide](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md). - [x] Apply [pre-commit checks](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md#code-linting-and-formatting): `pre-commit install && pre-commit run --all-files --show-diff-on-failure --color=always` - [x] Add / Update [the documentation](https://github.com/volcengine/verl/tree/main/docs). - [x] Add unit or end-to-end test(s) to [the CI workflow](https://github.com/volcengine/verl/tree/main/.github/workflows) to cover all the code. If not feasible, explain why: ... - [x] Once your PR is ready for CI, send a message in [the `ci-request` channel](https://verl-project.slack.com/archives/C091TCESWB1) in [the `verl` Slack workspace](https://join.slack.com/t/verl-project/shared_invite/zt-3855yhg8g-CTkqXu~hKojPCmo7k_yXTQ). (If not accessible, please try [the Feishu group (飞书群)](https://applink.larkoffice.com/client/chat/chatter/add_by_link?link_token=772jd4f1-cd91-441e-a820-498c6614126a).)
1 parent 2633140 commit e2b7735

6 files changed

Lines changed: 128 additions & 3 deletions

File tree

.github/workflows/e2e_ascend.yml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,3 +143,10 @@ jobs:
143143
ray stop --force
144144
bash tests/special_npu/run_qwen2_5_05b_dapo.sh
145145
rm -rf $HOME/ckpts
146+
- name: Running gsm8k e2e training tests with GRPO MindSpeed on ASCEND NPU
147+
run: |
148+
ray stop --force
149+
USE_DIST_CKPT=True bash tests/special_npu/run_qwen2_5_05b_grpo_mindspeed.sh
150+
rm -rf $HOME/dist_ckpt/qwen2_5_05b_grpo_mindspeed
151+
rm -rf $HOME/ckpts
152+

docs/ascend_tutorial/ascend_quick_start.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,15 @@ vllm & vllm-ascend
153153
trainer.total_epochs=1 \
154154
trainer.device=npu $@
155155
156+
MindSpeed 训练后端
157+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
158+
1. 参考 `MindSpeed Readme <https://gitee.com/ascend/MindSpeed>`_ 说明安装 MindSpeed 加速库。
159+
160+
2. 使能 Verl worker 模型 ``strategy`` 配置为 ``megatron`` ,例如 ``actor_rollout_ref.actor.strategy=megatron``。
161+
162+
3. MindSpeed 自定义入参可通过 ``override_transformer_config`` 参数传入,例如对 actor 模型开启 FA 特性可使用 ``+actor_rollout_ref.actor.megatron.override_transformer_config.use_flash_attn=True``。
163+
164+
4. 更多特性信息可参考 `MindSpeed Verl 文档 <https://gitee.com/ascend/MindSpeed/blob/master/docs/user-guide/verl.md>`_ 。
156165

157166
支持现状
158167
-----------------------------------

scripts/converter_hf_to_mcore.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,13 @@
2323
import numpy as np
2424
import torch
2525
import torch.distributed as dist
26+
27+
try:
28+
# NPU patch
29+
import mindspeed.megatron_adaptor # noqa: F401
30+
except ImportError:
31+
pass
32+
2633
from accelerate import init_empty_weights
2734
from megatron.core import dist_checkpointing
2835
from megatron.core import parallel_state as mpu
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
set -x
2+
3+
MODEL_ID=${MODEL_ID:-Qwen/Qwen2.5-0.5B-Instruct}
4+
MODEL_PATH=${MODEL_PATH:-${HOME}/models/${MODEL_ID}}
5+
huggingface-cli download "${MODEL_ID}" --local-dir "${MODEL_PATH}"
6+
7+
USE_DIST_CKPT=${USE_DIST_CKPT:-False}
8+
DIST_CKPT_PATH=${DIST_CKPT_PATH:-${HOME}/dist_ckpt/qwen2_5_05b_grpo_mindspeed}
9+
if [ "$USE_DIST_CKPT" = "True" ]; then
10+
if [ "$USE_DUMMY_MODEL" = "True" ]; then
11+
DIST_CKPT_PATH=${HOME}/dist_ckpt_dummy/${MODEL_ID}
12+
fi
13+
python scripts/converter_hf_to_mcore.py \
14+
--hf_model_path "${MODEL_PATH}" \
15+
--output_path "${DIST_CKPT_PATH}"
16+
fi
17+
18+
19+
python3 -m verl.trainer.main_ppo --config-path=config \
20+
--config-name='ppo_megatron_trainer.yaml' \
21+
algorithm.adv_estimator=grpo \
22+
data.train_files=$HOME/data/gsm8k/train.parquet \
23+
data.val_files=$HOME/data/gsm8k/test.parquet \
24+
data.train_batch_size=128 \
25+
data.max_prompt_length=512 \
26+
data.max_response_length=128 \
27+
data.filter_overlong_prompts=True \
28+
data.truncation='error' \
29+
actor_rollout_ref.model.path=${MODEL_ID} \
30+
actor_rollout_ref.actor.optim.lr=5e-7 \
31+
actor_rollout_ref.actor.ppo_mini_batch_size=64 \
32+
actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=20 \
33+
actor_rollout_ref.actor.strategy=megatron \
34+
actor_rollout_ref.actor.megatron.pipeline_model_parallel_size=2 \
35+
actor_rollout_ref.actor.megatron.tensor_model_parallel_size=2 \
36+
actor_rollout_ref.actor.megatron.expert_model_parallel_size=1 \
37+
actor_rollout_ref.actor.megatron.use_dist_checkpointing=True \
38+
actor_rollout_ref.actor.megatron.dist_checkpointing_path=${DIST_CKPT_PATH} \
39+
actor_rollout_ref.actor.use_kl_loss=True \
40+
actor_rollout_ref.actor.kl_loss_coef=0.001 \
41+
actor_rollout_ref.actor.kl_loss_type=low_var_kl \
42+
actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=40 \
43+
actor_rollout_ref.rollout.enable_chunked_prefill=False \
44+
actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
45+
actor_rollout_ref.rollout.name=vllm \
46+
actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
47+
actor_rollout_ref.rollout.n=5 \
48+
actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=40 \
49+
actor_rollout_ref.ref.strategy=megatron \
50+
actor_rollout_ref.ref.megatron.pipeline_model_parallel_size=2 \
51+
actor_rollout_ref.ref.megatron.tensor_model_parallel_size=2 \
52+
actor_rollout_ref.ref.megatron.expert_model_parallel_size=1 \
53+
actor_rollout_ref.ref.megatron.use_dist_checkpointing=True \
54+
actor_rollout_ref.ref.megatron.dist_checkpointing_path=${DIST_CKPT_PATH} \
55+
algorithm.kl_ctrl.kl_coef=0.001 \
56+
trainer.critic_warmup=0 \
57+
trainer.logger=console \
58+
trainer.project_name='verl_grpo_example_gsm8k' \
59+
trainer.experiment_name='qwen2_7b_function_rm' \
60+
trainer.n_gpus_per_node=8 \
61+
trainer.nnodes=1 \
62+
trainer.save_freq=-1 \
63+
trainer.test_freq=5 \
64+
trainer.total_epochs=1 \
65+
trainer.total_training_steps=2 \
66+
trainer.device=npu \
67+
+actor_rollout_ref.actor.megatron.override_transformer_config.use_flash_attn=True $@

verl/utils/kernel/kernels.py

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,37 @@
3737

3838
import torch
3939
import torch.distributed as dist
40-
import triton
41-
import triton.language as tl
40+
41+
try:
42+
import triton
43+
import triton.language as tl
44+
45+
HAVE_TRITON = True
46+
except ImportError:
47+
HAVE_TRITON = False
4248

4349
from verl.utils.device import get_torch_device
4450

51+
if not HAVE_TRITON:
52+
from contextlib import contextmanager
53+
from unittest.mock import MagicMock
54+
55+
@contextmanager
56+
def null_decorator(*args, **kwargs):
57+
if len(kwargs) == 0 and len(args) == 1 and callable(args[0]):
58+
return args[0]
59+
else:
60+
61+
def inner(func):
62+
return func
63+
64+
return inner
65+
66+
triton = MagicMock()
67+
triton.jit = null_decorator
68+
triton.autotune = null_decorator
69+
tl = MagicMock()
70+
4571

4672
@dataclass
4773
class EntropyReductionEnum:

verl/workers/megatron_workers.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,15 @@
2525
import torch
2626
import torch.distributed
2727
from codetiming import Timer
28-
from megatron.core import parallel_state as mpu
2928
from omegaconf import DictConfig, OmegaConf
3029

30+
try:
31+
from mindspeed.megatron_adaptor import repatch
32+
except ImportError:
33+
repatch = None
34+
35+
from megatron.core import parallel_state as mpu
36+
3137
from verl import DataProto
3238
from verl.single_controller.base.decorator import Dispatch, register
3339
from verl.single_controller.base.megatron.worker import MegatronWorker
@@ -90,6 +96,9 @@ class ActorRolloutRefWorker(MegatronWorker, DistProfilerExtension):
9096
def __init__(self, config: DictConfig, role: str, **kwargs):
9197
MegatronWorker.__init__(self)
9298
self.config = config
99+
if repatch is not None:
100+
# NPU MindSpeed patch, will be refactored with MindSpeedEngine.
101+
repatch(self.config.actor.megatron.get("override_transformer_config", {}))
93102

94103
# NOTE(sgm): We utilize colocate WorkerGroup by default.
95104
# As a result, Workers for different model share the same process.

0 commit comments

Comments
 (0)