verl icon indicating copy to clipboard operation
verl copied to clipboard

[megatron] feat: Integrate Megatron-Bridge and support LoRA/PEFT

Open HollowMan6 opened this issue 1 year ago • 18 comments

What does this PR do?

Add concise overview of what this PR aims to achieve or accomplish. Reference related GitHub issues and PRs that help with the review.

This PR aims to add LoRA/PEFT support by integrating Megatron-Bridge into Verl while maintaining compatibility with mbridge. As a result. LoRA/PEFT support can be added to Verl with megatron backend.

Resolves #3857 Resolves #3402 Resolves #3279

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.

To be added later

API and Usage Example

Demonstrate how the API changes if any, and provide usage example(s) if possible.

To be added later

# 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.

To be added later

Checklist Before Submitting

[!IMPORTANT] Please check all the following items before requesting a review, otherwise the reviewer might deprioritize this PR for review.

✨ Presented to you with Mind Lab - A Lab for Experiential Intelligence.

HollowMan6 avatar Nov 09 '25 23:11 HollowMan6

There are 2 remaining issues that might need some help. I'm not sure if this is caused by some bugs in Megatron-Bridge or in this PR, please let me know if you find anything, and I'll also continue debugging:

  • When PEFT is enabled, we will get the following error when we call get_megatron_optimizer in actor:
User exception:
zer/distrib_optimizer.py", line 584, in __init__
 self._build_optimizer_group_ranges(self.optimizer.param_groups, self.gbuf_ranges)
 File "megatron/core/optimizer/distrib_optimizer.py", line 290, in _build_optimizer_group_ranges
 group_index = world_param_group_map[param]
 ~~~~~~~~~~~~~~~~~~~~~^^^^^^^
KeyError: Parameter containing:
tensor([1., 1., 1., ..., 1., 1., 1.], device='cuda:0', dtype=torch.bfloat16)
  • (I think I might made some mistakes in this PR for this one, as several CI failed with OOM, and it shouldn't be related to Megatron-Bridge) Without PEFT but with Megatron-Bridge, we will have "Tensor exists on more than one PP rank" error when vLLM updates weight, and this happens for all the params, not only embed_tokens (so this is not caused by tie_word_embedding)
File "verl/workers/megatron_workers.py", line 686, in rollout_mode
  for name, weight in self.bridge.export_hf_weights(self.actor.actor_module, cpu=True, show_progress=False):
File "megatron/bridge/models/conversion/model_bridge.py", line 623, in stream_weights_megatron_to_hf
  converted_weights_dict = task.mapping.megatron_to_hf(task.param_weight, task.megatron_module)
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "megatron/bridge/models/conversion/param_mapping.py", line 1237, in megatron_to_hf
  result = self._mapping.megatron_to_hf(megatron_weights, megatron_module)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "megatron/bridge/models/conversion/param_mapping.py", line 995, in megatron_to_hf
  megatron_weights = self.broadcast_from_pp_rank(megatron_weights, cache_key=str(self.hf_param))
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "megatron/bridge/models/conversion/param_mapping.py", line 336, in broadcast_from_pp_rank
  raise ValueError(f"Tensor exists on more than one PP rank. Found on ranks {src_rank} and {rank}.")
ValueError: Tensor exists on more than one PP rank. Found on ranks 0 and 1.

cc @ISEEKYAN

HollowMan6 avatar Nov 10 '25 00:11 HollowMan6

@HollowMan6 good job! @conver334 has also been developing this feature lately, I will check this PR with her tomorrow and leave feedbacks.

ISEEKYAN avatar Nov 10 '25 12:11 ISEEKYAN

/gemini review

HollowMan6 avatar Nov 10 '25 22:11 HollowMan6

can we have lora related CI/CD test?

Yes, sure, but I think the piority is that we get weight updating/loading working first: https://github.com/volcengine/verl/pull/4063#discussion_r2512256334 after that, we can add some test cases here.

HollowMan6 avatar Nov 11 '25 11:11 HollowMan6

Thank you @ISEEKYAN ! I have solved 2 issues mentioned in #4063 (comment) by myself. The first one is that we should set PEFT first before we wrap with DDP, the second one is that I forgot to pass those pp, tp, ep configs to the Megatron-Bridge provider.

I think now this PR is ready to get some systematic review. Aside from #4063 (comment) (which I'm not sure if there's any equivalent option in Megatron-Bridge/how to modify), and the below issue related to export HF weights with PEFT adapters, I have tested with the following scripts with saving/loading checkpoints (with lora.rank=16 or 0 (full params)), and they all look good:

except that I face the following error when I set pp=2, though it looks like to be model specific.

cc: @conver334

Good job! @conver334 will help with testing your great work and make sure the integration's correctness.

For more formal and advanced usage of megatron-bridge, I think nemo-rl is a very good reference.

ISEEKYAN avatar Nov 12 '25 11:11 ISEEKYAN

Thank you @conver334 and @ISEEKYAN again for reviewing! I've successfully integrated LoRA Merge and related mapping in Megatron-Bridge: https://github.com/NVIDIA-NeMo/Megatron-Bridge/pull/1310, I've also tested this with TP, PP, and EP, so that now load_hf_weights and export_hf_weights works correctly for LoRA enabled models as well by merging weights. I recommend to test this PR with the main branch mcore due to https://github.com/NVIDIA-NeMo/Megatron-Bridge/pull/1289#discussion_r2515852230 After https://github.com/NVIDIA-NeMo/Megatron-Bridge/pull/1310 is merged and released, we can consider adding some CI test cases for megatron lora.

I've also tested this PR, both w/ and w/o lora using Megatron-Bridge, aside from the pp issue mentioned in https://github.com/volcengine/verl/pull/4063#pullrequestreview-3445527855, which I think is probably related to Megatron-Bridge as it works fine when I use vanilla mbridge, I find that when I combine tp with ep for Qwen3-30B-A3B (please check the script I use in this PR examples/grpo_trainer/run_qwen3moe-30b_megatron_lora.sh), it will stuck in the forward pass (see the stack trace when stuck happens below), which I'm not sure what's going on here. Since I'm not familiar with Megatron-Bridge, I'll probably need your help to resolve these issues. Please let me know if you have any insights about these 2 issues, thanks in advance!

    forward (core/tensor_parallel/layers.py:480)
    decorate_fwd (torch/amp/autocast_mode.py:517)
    apply (torch/autograd/function.py:576)
    linear_with_grad_accumulation_and_async_allreduce (core/tensor_parallel/layers.py:737)
    _forward_impl (core/tensor_parallel/layers.py:944)
    forward (core/tensor_parallel/layers.py:1014)
    _call_impl (torch/nn/modules/module.py:1784)
    _wrapped_call_impl (torch/nn/modules/module.py:1773)
    forward (bridge/peft/utils.py:581)
    _call_impl (torch/nn/modules/module.py:1784)
    _wrapped_call_impl (torch/nn/modules/module.py:1773)
    forward (bridge/peft/lora_layers.py:56)
    _call_impl (torch/nn/modules/module.py:1784)
    _wrapped_call_impl (torch/nn/modules/module.py:1773)
    forward (core/transformer/moe/experts.py:882)
    _call_impl (torch/nn/modules/module.py:1784)
    _wrapped_call_impl (torch/nn/modules/module.py:1773)
    routed_experts_compute (core/transformer/moe/moe_layer.py:231)
    custom_forward (core/transformer/moe/moe_layer.py:276)
    forward (core/transformer/moe/moe_layer.py:292)
    _call_impl (torch/nn/modules/module.py:1784)
    _wrapped_call_impl (torch/nn/modules/module.py:1773)
    _forward_mlp (core/transformer/transformer_layer.py:618)
    forward (core/transformer/transformer_layer.py:435)
    _call_impl (torch/nn/modules/module.py:1784)
    _wrapped_call_impl (torch/nn/modules/module.py:1773)
    __call__ (core/transformer/module.py:305)
    __call__ (core/transformer/transformer_layer.py:852)
    custom_forward (core/transformer/transformer_block.py:426)
    forward (core/tensor_parallel/random.py:426)
    apply (torch/autograd/function.py:576)
    checkpoint (core/tensor_parallel/random.py:480)
    checkpoint_handler (core/transformer/transformer_block.py:456)
    _checkpointed_forward (core/transformer/transformer_block.py:472)
    forward (core/transformer/transformer_block.py:669)
    _call_impl (torch/nn/modules/module.py:1784)
    _wrapped_call_impl (torch/nn/modules/module.py:1773)
    __call__ (core/transformer/module.py:305)
    __call__ (core/transformer/transformer_block.py:553)
    _fused_GPTModel_forward (verl/models/mcore/model_forward_fused.py:175)
    _call_impl (torch/nn/modules/module.py:1784)
    _wrapped_call_impl (torch/nn/modules/module.py:1773)
    forward (core/transformer/module.py:429)
    _call_impl (torch/nn/modules/module.py:1784)
    _wrapped_call_impl (torch/nn/modules/module.py:1773)
    forward (core/distributed/data_parallel_base.py:22)
    _call_impl (torch/nn/modules/module.py:1784)
    _wrapped_call_impl (torch/nn/modules/module.py:1773)
    fused_forward_model (verl/models/mcore/model_forward_fused.py:117)
    forward_step (verl/workers/actor/megatron_actor.py:561)
    forward_step (core/pipeline_parallel/schedules.py:402)
    forward_backward_no_pipelining (core/pipeline_parallel/schedules.py:615)
    forward_backward_batch (verl/workers/actor/megatron_actor.py:633)
    compute_log_prob (verl/workers/actor/megatron_actor.py:217)
    log (verl/utils/profiler/performance.py:118)
    f (verl/utils/profiler/performance.py:105)
    compute_log_prob (verl/workers/megatron_workers.py:801)
    wrapper (verl/utils/profiler/profile.py:256)
    log (verl/utils/profiler/performance.py:118)
    f (verl/utils/profiler/performance.py:105)
    dummy_inner (verl/utils/transferqueue_utils.py:199)
    inner (verl/single_controller/base/decorator.py:442)
    func (verl/single_controller/ray/base.py:700)
    _resume_span (ray/util/tracing/tracing_helper.py:461)
    actor_method_executor (ray/_private/function_manager.py:693)
    main_loop (ray/_private/worker.py:1042)
    <module> (ray/_private/workers/default_worker.py:322)

HollowMan6 avatar Nov 12 '25 22:11 HollowMan6

Wondering if you have encountered this issue in your testing:

When loading a model with Megatron-Bridge using TP > 1 and PP > 1 across multiple nodes, it looks like each TP rank within a PP group ends up loading the full PP shard (all layers for that PP stage), instead of being further sharded by TP.

Encountering an issue like this example:

  • Model: ~10B parameters, 8 layers
  • TP8, PP2
  • 2 nodes with 8 h100 gpus

This should end up with 2 PP groups, each responsible for 5 layers:

  • PP stage 0: layers 1–4
  • PP stage 1: layers 5-8

Each PP stage should own ~10B / 2 = 5B parameters. This ends up behaving as expected when I inspect the loaded actor module.

For TP, I encounter the following - Expected Behavior:

  • Within each PP group, the 5B parameters should be sharded across TP=8 ranks, so that each TP rank only holds roughly 5B / 8 parameters for that PP stage.

Observed Behavior:

  • every TP rank within a PP group appears to load the full 5B parameters for that PP stage. In other words, the PP sharding works (each PP group gets the correct subset of layers), but TP sharding does not appear to be applied on top of that for the loaded weights, and each TP rank in the PP group ends up with the full PP shard.

This results in OOM very quickly as the DDP wrapper initializes the param buffers for the entire PP stage on every TP rank

ryxli avatar Nov 13 '25 20:11 ryxli

Wondering if you have encountered this issue in your testing:

@ryxli Are you using the latest commit of this PR? I used to have an issue on my side for my initial draft (see issue 2: https://github.com/volcengine/verl/pull/4063#issuecomment-3508974383) when I export to hf weight using Megatron Bridge, but it turned out to be that I forgot to pass the pp size value to the provider during initialization.

However, actually I haven't fully tested TP+PP as I encountered another shape mismatch issue as mentioned in: https://github.com/volcengine/verl/pull/4063#pullrequestreview-3445527855 so I'm not sure about your situation if it's not caused by using an older commit of this PR, and your issue might be related to the shape mismatch issue as well. Please let me know if you have any further insights, thanks!

HollowMan6 avatar Nov 13 '25 20:11 HollowMan6

@HollowMan6 yes, I patched with the contents of the latest commits, minus the portions related to PEFT.

When loading the ref module without the ddp wrapper it seems to behave as expected. Continuing to debug this

ryxli avatar Nov 13 '25 21:11 ryxli

@HollowMan6 think i figured it my specific issue, in native megatron-lm, if TransformerConfig is instantiated with tensor_model_parallel_size and expert_tensor_parallel_size is unspecified, it defaults to tp size

But in verl, we have a default value for 1, this is why my expert layers seemed to be taking more memory than expected and caused OOM.

ryxli avatar Nov 13 '25 22:11 ryxli

But in verl, we have a default value for 1, this is why my expert layers seemed to be taking more memory than expected and caused OOM.

@ryxli That's interesting to know! Though the issue I was facing (shape mismatch) was related to dense model, thanks for reporting this! I agree that the current default value is not very straightforward for this, so I opened a PR at https://github.com/volcengine/verl/pull/4119 to set it to null by default.

HollowMan6 avatar Nov 13 '25 23:11 HollowMan6

Updates: Now the issues mentioned in https://github.com/volcengine/verl/pull/4063#issuecomment-3524102640 has been resolved by https://github.com/volcengine/verl/pull/4063#discussion_r2529826758. The MoE LoRA will also be fine if we only target modules without experts (target_modules=["linear_qkv", "linear_proj"]), or unset ETP (make sure ETP == TP) (reference: https://github.com/NVIDIA-NeMo/Megatron-Bridge/issues/1363), or wait for https://github.com/NVIDIA-NeMo/Megatron-Bridge/pull/1380 to be merged.

I've also added test cases for Dense w/ or w/o LoRA for Megatron Bridge in the CI, though currently the value models are still using mbridge as it ~~face the stuck situation during reward model score compute in the CI for dense (https://github.com/volcengine/verl/actions/runs/19394353250/job/55492282113)~~, it's OK when I test this locally w/ or w/o LoRA with Megatron Bridge for dense value models using the same test script and model.

~~For MoE test cases, I will need help to download Qwen/Qwen3-30B-A3B-Instruct-2507 in the runner (moonshotai/Moonlight-16B-A3B-Instruct is not a good candidate as it contains some remote code which the current random model creator can't handle, also it's not good to execute remote code in CI). However, when I test this locally with the value models using Megatron Bridge, it stuck as well (during reward compute), and it hangs in a memory leak way.~~ Will be okay with https://github.com/NVIDIA-NeMo/Megatron-Bridge/pull/1397

So now everything should work!

HollowMan6 avatar Nov 16 '25 11:11 HollowMan6

/gemini review

HollowMan6 avatar Nov 18 '25 00:11 HollowMan6

@HollowMan6 Hi we want to add models verl mcore initializer to support our training with Megatron instead of fsdp backend.

We could use slurm , k8s to start nodes.

But for the moment it is ok to start nodes by hand manually.

We will add gpt-oss to models/mcore manually if there is anything prevent us to use codes to train on megatron backend, please let me know.

Target missing model gpt-oss.

Hi @yiakwy-xpu-ml-framework-team, I think now verl doesn't accept new models hardcode in the codebase, and support will gradually move to mbridge and eventually Megatron-Bridge. I can see that Megatron-Bridge already has gpt_oss marked as supported: https://github.com/NVIDIA-NeMo/Megatron-Bridge/tree/main/src/megatron/bridge/models/gpt_oss, so I think you can try this PR together with Megatron-Bridge and see how things will go (to get started, you can mark gpt_oss as supported in verl, similar to https://github.com/volcengine/verl/pull/3838). Feel free to let me know if you face any errors that are related to this PR.

cc:@ISEEKYAN

HollowMan6 avatar Nov 18 '25 13:11 HollowMan6

@yiakwy-xpu-ml-framework-team Were you able to get it working with gpt-oss?

ajsinger1 avatar Nov 18 '25 22:11 ajsinger1

I added the value model support using Megatron-Bridge back in the CI, and it has passed (one cancelled because of random network issue), so this PR is ready to be merged.

  • https://github.com/volcengine/verl/actions/runs/19501139164/job/55815349425?pr=4063
  • https://github.com/volcengine/verl/actions/runs/19501139174/job/55815333698?pr=4063

HollowMan6 avatar Nov 19 '25 12:11 HollowMan6

merge for now. Some todos: 0. add detailed documents

  1. refactor Lora configs, compatible with fsdp
  2. support gpt-oss
  3. support local parallel

ISEEKYAN avatar Nov 24 '25 10:11 ISEEKYAN

@ISEEKYAN Yes we can add gptoss via megatron-bridge , cheers!

Hi @HollowMan6, I found a severe issue regarding the lora rank:

In verl/trainer/config/ppo_megatron_trainer.yaml, which imports the model config from hf_config, and defines lora related parameters like actor_rollout_ref.model.lora.rank:

# specify the default per-component configs
defaults:
  ...
  # Model config.
  - model@actor_rollout_ref.model: hf_model
  ...

actor_rollout_ref:
...
  model:
  ...
  # LoRA (Low-Rank Adaptation) configuration for parameter-efficient fine-tuning
    lora:
      # LoRA type: "lora", "vlm_lora", "canonical_lora", or "dora"
      type: lora

      # LoRA rank (Dimension of the low-rank projection space.). Set to 0 to disable LoRA
      rank: 0  # typical values: 8, 16, 32, 64
      
      #  Weighting factor for the low-rank projection. Defaults to 32
      alpha: 32
...

But in verl/trainer/config/model/hf_model.yaml, which also defines lora related parameters:

...
# Set to positive value to enable LoRA (e.g., 32)
lora_rank: 0

# LoRA scaling factor
lora_alpha: 16

# Target modules for LoRA adaptation
target_modules: all-linear
...

These parameters, after importing to ppo_megatron_trainer.yaml, become something like actor_rollout_ref.model.lora_rank. So in ppo_megatron_trainer.yaml, both actor_rollout_ref.model.lora.rank and actor_rollout_ref.model.lora_rank exist.

What makes it worse is that megatron uses actor_rollout_ref.lora.rank to determine whether to use lora

# verl/workers/config/megatron_peft.py
def get_peft_cls(model_config, bridge, provider, dtype=None):
    peft_cls = None
    if not hasattr(model_config, "lora"):
        return peft_cls

    lora_cfg = model_config.lora
    # Only enable if rank > 0
    if lora_cfg.get("rank", 0) <= 0:
        return peft_cls

but the vllm rollout uses actor_rollout_ref.lora_rank instead

# verl/workers/rollout/vllm_rollout/vllm_rollout_spmd.py
class vLLMAsyncRollout(BaseRollout):
    """vLLMAsyncRollout is a thin wrapper of WorkerWrapperBase, which is engine in single worker process."""
    def __init__(
        self,
        config: RolloutConfig,
        model_config: HFModelConfig,
        device_mesh: DeviceMesh,
    ):
        ...
        self.lora_config = (
            {"max_loras": 1, "max_lora_rank": get_vllm_max_lora_rank(self.model_config.lora_rank)}
            if self.model_config.lora_rank > 0
            else {}
        )

So in examples/grpo_trainer/run_qwen3moe-30b_megatron_lora.sh, if only set actor_rollout_ref.model.lora.rank, vllm won't use lora and will only run the base model.

Junxiao-Zhao avatar Dec 03 '25 08:12 Junxiao-Zhao