Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions src/megatron/bridge/models/qwen_vl/modeling_qwen25_vl.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
)

from megatron.bridge.models.gpt_provider import GPTModelProvider
from megatron.bridge.training.utils.packed_seq_utils import (
repack_mcore_thd_position_ids,
unpack_mcore_thd_tensor_for_position_ids,
)
from megatron.bridge.utils.common_utils import hook_hf_module_setattr_for_tp_grad_sync


Expand Down Expand Up @@ -206,22 +210,30 @@ def forward(
) # [b, decoder_seq_len, h_language] -> [decoder_seq_len, b, h_language]

if self.config.sequence_parallel:
inputs_embeds = scatter_to_sequence_parallel_region(inputs_embeds)
tp_group = self.config._pg_collection.tp if self.config._pg_collection is not None else None
inputs_embeds = scatter_to_sequence_parallel_region(inputs_embeds, group=tp_group)

# Compute MRoPE position_ids on ALL pipeline stages
# Each stage has input_ids and visual grid info from the data iterator
# This avoids any broadcasting overhead
rope_input_ids = input_ids
hf_attention_mask = None
packed_row_starts = None
packed_row_lengths = None
if packed_seq_params is not None and packed_seq_params.qkv_format == "thd":
rope_input_ids, hf_attention_mask, packed_row_starts, packed_row_lengths = (
unpack_mcore_thd_tensor_for_position_ids(input_ids, packed_seq_params)
)

# Build mm_token_type_ids: 0=text, 1=image, 2=video
mm_token_type_ids = torch.zeros_like(input_ids, dtype=torch.int)
mm_token_type_ids[input_ids == self.config.image_token_id] = 1
mm_token_type_ids[input_ids == self.config.video_token_id] = 2
mm_token_type_ids = torch.zeros_like(rope_input_ids, dtype=torch.int)
mm_token_type_ids[rope_input_ids == self.config.image_token_id] = 1
mm_token_type_ids[rope_input_ids == self.config.video_token_id] = 2

# In transformers 5.3.0+, get_rope_index requires mm_token_type_ids as the second argument
if is_transformers_min_version("5.3.0"):
position_ids, rope_deltas = self.get_rope_index(
input_ids,
rope_input_ids,
mm_token_type_ids,
image_grid_thw,
video_grid_thw,
Expand All @@ -230,12 +242,19 @@ def forward(
)
else:
position_ids, rope_deltas = self.get_rope_index(
input_ids,
rope_input_ids,
image_grid_thw,
video_grid_thw,
second_per_grid_ts=second_per_grid_ts,
attention_mask=hf_attention_mask,
)
if packed_row_starts is not None and packed_row_lengths is not None:
position_ids = repack_mcore_thd_position_ids(
position_ids,
padded_starts=packed_row_starts,
lengths=packed_row_lengths,
total_length=input_ids.size(1),
)

outputs = self.language_model.forward(
input_ids=None,
Expand Down
294 changes: 219 additions & 75 deletions src/megatron/bridge/models/qwen_vl/modelling_qwen3_vl/model.py

Large diffs are not rendered by default.

297 changes: 223 additions & 74 deletions src/megatron/bridge/models/qwen_vl/modelling_qwen3_vl/rope.py

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@
3e5a40f2ee42a2c74/mbridge/models/qwen3_vl/gpt_model.py
"""

from dataclasses import replace
from typing import Literal, Optional

import torch
from megatron.core import tensor_parallel
from megatron.core.dist_checkpointing.mapping import ShardedStateDict
from megatron.core.inference.contexts import BaseInferenceContext
from megatron.core.models.gpt.gpt_model import GPTModel
from megatron.core.packed_seq_params import PackedSeqParams
Expand All @@ -33,6 +35,23 @@
from megatron.bridge.models.qwen_vl.modelling_qwen3_vl.rope import Qwen3VLMultimodalRotaryEmbedding
from megatron.bridge.models.qwen_vl.modelling_qwen3_vl.transformer_block import Qwen3VLTransformerBlock
from megatron.bridge.models.transformer_config import TransformerConfig
from megatron.bridge.training.utils.packed_seq_utils import get_packed_seq_q_cu_seqlens


def _get_mtp_packed_seq_params(packed_seq_params: PackedSeqParams | None) -> PackedSeqParams | None:
"""Use physical padded offsets for MTP token rolling without changing attention metadata."""
if packed_seq_params is None or packed_seq_params.cu_seqlens_q_padded is None:
return packed_seq_params

_, cu_seqlens_q = get_packed_seq_q_cu_seqlens(packed_seq_params)
cu_seqlens_kv = packed_seq_params.cu_seqlens_kv_padded
if cu_seqlens_kv is None:
cu_seqlens_kv = cu_seqlens_q
return replace(
packed_seq_params,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_kv=cu_seqlens_kv,
)


class Qwen3VLGPTModel(GPTModel):
Expand Down Expand Up @@ -106,6 +125,25 @@ def __init__(
pg_collection=pg_collection,
)

def tie_embeddings_and_output_weights_state_dict(
self,
sharded_state_dict: ShardedStateDict,
output_layer_weight_key: str,
first_stage_word_emb_key: str,
metadata: dict | None = None,
) -> None:
"""Tie embedding/output checkpoint entries for Qwen3-VL MTP pipeline stages."""
if getattr(self, "mtp_process", False) and not self.pre_process:
sharded_state_dict.pop(output_layer_weight_key, None)
return

super().tie_embeddings_and_output_weights_state_dict(
sharded_state_dict,
output_layer_weight_key,
first_stage_word_emb_key,
metadata if metadata is not None else {},
)

def forward(
self,
input_ids: Tensor,
Expand Down Expand Up @@ -186,12 +224,15 @@ def forward(

def _sp_scatter_embedding(input_ids, position_ids):
out = _original_embedding(input_ids=input_ids, position_ids=position_ids)
return tensor_parallel.scatter_to_sequence_parallel_region(out)
return tensor_parallel.scatter_to_sequence_parallel_region(out, group=self.pg_collection.tp)

_sp_scatter_embedding.word_embeddings = _original_embedding.word_embeddings
self.__dict__["embedding"] = _sp_scatter_embedding
_shadow_embedding = True

postprocess_packed_seq_params = (
_get_mtp_packed_seq_params(packed_seq_params) if self.mtp_process else packed_seq_params
)
result = self._postprocess(
hidden_states=hidden_states,
input_ids=input_ids,
Expand All @@ -205,7 +246,7 @@ def _sp_scatter_embedding(input_ids, position_ids):
decoder_input=decoder_input,
attention_mask=attention_mask,
inference_params=inference_params,
packed_seq_params=packed_seq_params,
packed_seq_params=postprocess_packed_seq_params,
sequence_len_offset=sequence_len_offset,
runtime_gather_output=runtime_gather_output,
extra_block_kwargs=extra_block_kwargs,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ def __init__(
config,
patch_merger_spec,
use_postshuffle_norm=True,
tp_group=self.tp_group,
)
for _ in range(len(config.deepstack_visual_indexes))
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,13 @@ def get_vision_model_config(hf_config, megatron_config=None):
config.spatial_merge_size = hf_config.spatial_merge_size
config.num_position_embeddings = hf_config.num_position_embeddings
config.out_hidden_size = hf_config.out_hidden_size
config.deepstack_visual_indexes = deepcopy(hf_config.deepstack_visual_indexes)
# ``deepstack_visual_indexes`` is a Qwen3-VL-only field. Qwen3.5-VL's HF
# config does not declare it in the schema, so the field is sometimes
# absent — e.g. after a YAML round-trip through
# ``PretrainedConfig.to_dict()`` / ``from_dict()`` which only persists
# declared fields. ``Qwen3VLModel.__init__`` already reads it
# defensively with the same default (``modelling_qwen3_vl/model.py:193``).
config.deepstack_visual_indexes = deepcopy(getattr(hf_config, "deepstack_visual_indexes", []))

config.apply_rope_fusion = False
config.gated_linear_unit = False # no gated
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def __init__(
skip_bias_add=False,
is_expert=False,
tp_comm_buffer_name="patch_fc1",
tp_group=tp_group,
tp_group=self.tp_group,
)

self.activation_func = self.config.activation_func
Expand All @@ -164,7 +164,7 @@ def __init__(
skip_bias_add=False,
is_expert=False,
tp_comm_buffer_name="patch_fc2",
tp_group=tp_group,
tp_group=self.tp_group,
)

def forward(self, hidden_states):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ def __init__(
transformer_config,
patch_merger_spec,
use_postshuffle_norm=False,
tp_group=self.tp_group,
)

self.input_tensor = None
Expand Down
Loading
Loading