Skip to content

Commit 3824689

Browse files
pengyanaiiqianchengwuxibin89
authored
[fsdp] fix: qwen3vlmoe with Monkey patch to fix a bug in transformers 4.57.x (verl-project#4402)
fix qwen3vlmoe with Monkey patch to fix a bug in transformers 4.57.3 where `Qwen3VLMoeTextSparseMoeBlock.forward` incorrectly uses torch.zeros_like(router_logits) instead of torch.zeros_like(hidden_states) when creating router_weights (line 148 in modeling_qwen3_vl_moe.py). to close issue: verl-project#4401 RuntimeError: scatter(): Expected self.dtype to be equal to src.dtype ### 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. ### Checklist Before Starting - [x] Search for similar PRs. Paste at least one query link here: ... verl-project#3686 huggingface/transformers#41418 - [ ] 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. - [ ] Read the [Contribute Guide](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md). - [ ] 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` - [ ] Add / Update [the documentation](https://github.com/volcengine/verl/tree/main/docs). - [ ] 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: ... - [ ] 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).) --------- Co-authored-by: qian.cheng <mgr.qiancheng@gmail.com> Co-authored-by: wuxibin <wuxibin@bytedance.com>
1 parent 01ab536 commit 3824689

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

verl/models/transformers/monkey_patch.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -356,14 +356,22 @@ def state_dict(self, *args, **kwargs):
356356
Qwen3VLMoeTextModel,
357357
)
358358

359-
from verl.models.transformers.qwen3_vl import forward_with_normal_backend, qwen3_vl_base_forward
359+
from verl.models.transformers.qwen3_vl import (
360+
forward_with_normal_backend,
361+
patch_qwen3_vl_moe_sparse_moe_block_forward,
362+
qwen3_vl_base_forward,
363+
)
360364

361365
Qwen3VLModel.forward = qwen3_vl_base_forward
362366
Qwen3VLMoeModel.forward = qwen3_vl_base_forward
363367
Qwen3VLForConditionalGeneration.forward = forward_with_normal_backend
364368
Qwen3VLMoeForConditionalGeneration.forward = forward_with_normal_backend
365369
print(f"Monkey patch {model.__class__.__name__} model forward")
366370

371+
# Step 1.5: patch Qwen3VLMoeTextSparseMoeBlock to fix transformers 4.57.3 bug
372+
if model.config.model_type == "qwen3_vl_moe" and is_transformers_version_in_range(max_version="4.57.3"):
373+
patch_qwen3_vl_moe_sparse_moe_block_forward()
374+
367375
# Step 2: patch input for multimodal sequence parallelism
368376
if ulysses_sp_size > 1:
369377
patch_vlm_for_ulysses_input_slicing(Qwen3VLTextModel)

verl/models/transformers/qwen3_vl.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
import functools
1516
import logging
1617
import os
1718
from dataclasses import dataclass
@@ -334,3 +335,41 @@ def forward_with_triton_backend(
334335
entropy=entropy,
335336
hidden_states=outputs.hidden_states,
336337
)
338+
339+
340+
def patch_qwen3_vl_moe_sparse_moe_block_forward():
341+
"""
342+
Monkey patch to fix a bug in transformers 4.57.3 where Qwen3VLMoeTextSparseMoeBlock.forward
343+
incorrectly uses torch.zeros_like(hidden_states) instead of torch.zeros_like(router_logits)
344+
when creating router_weights (line 148 in modeling_qwen3_vl_moe.py).
345+
346+
This is a minimal fix that only changes the problematic line while keeping the rest of the
347+
original implementation intact.
348+
"""
349+
try:
350+
from transformers.models.qwen3_vl_moe.modeling_qwen3_vl_moe import Qwen3VLMoeTextSparseMoeBlock
351+
except ImportError:
352+
# Model not available, skip patching
353+
return
354+
355+
# Store the original forward method for reference
356+
original_forward = Qwen3VLMoeTextSparseMoeBlock.forward
357+
358+
@functools.wraps(original_forward)
359+
def patched_forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
360+
batch_size = hidden_states.shape[0]
361+
hidden_states = hidden_states.reshape(-1, self.hidden_size)
362+
router_logits = self.gate(hidden_states)
363+
routing_weights = torch.nn.functional.softmax(router_logits, dim=-1, dtype=torch.float)
364+
routing_weights, router_indices = torch.topk(routing_weights, self.top_k, dim=-1)
365+
routing_weights = routing_weights / routing_weights.sum(dim=-1, keepdim=True)
366+
# BUG FIX: Original code incorrectly uses hidden_states here, should use router_logits
367+
routing_weights = routing_weights.to(router_logits.dtype)
368+
router_weights = torch.zeros_like(router_logits).scatter_(1, router_indices, routing_weights)
369+
hidden_states = hidden_states.reshape(batch_size, -1, self.hidden_size)
370+
routed_out = self.experts(hidden_states, router_weights, router_indices)
371+
return routed_out
372+
373+
# Apply the patch
374+
Qwen3VLMoeTextSparseMoeBlock.forward = patched_forward
375+
logger.info("Monkey patched Qwen3VLMoeTextSparseMoeBlock.forward to fix router_weights bug")

0 commit comments

Comments
 (0)