bridge.models.qwen_vl.modelling_qwen3_vl.rope#

Module Contents#

Classes#

Qwen3VLMultimodalRotaryEmbedding

Multimodal Rotary Embedding for Qwen3-VL/Qwen3-Omni language model.

Functions#

_get_flat_packed_ranges

Return (padded_start, valid_end, padded_end) ranges for flat packed input.

get_packed_seq_attention_mask

Build a dense keep mask matching packed sequence metadata.

_build_llm_rope_positions

Build Qwen3-VL MRoPE positions for one logical sample.

get_rope_index

Different from the original implementation, Qwen3VL use timestamps rather than absolute time position ids.

apply_rotary_pos_emb_thd_absolute

A baseline implementation of applying RoPE for thd format.

_fused_rope_unsupported_reason

Return why Transformer Engine’s fused RoPE cannot replace the unfused code here, or None if it can.

_warn_fused_rope_fallback

Report, once per reason and process, that apply_rope_fusion fell back to the unfused implementation.

_apply_fused_rotary_pos_emb_absolute

Apply per-token RoPE with Transformer Engine’s fused SBHD kernel.

apply_rotary_pos_emb_absolute

Apply Qwen’s per-token rotary embedding to a query or key tensor.

Data#

API#

bridge.models.qwen_vl.modelling_qwen3_vl.rope._FUSED_ROPE_FALLBACK_REASONS: set[str]#

‘set(…)’

bridge.models.qwen_vl.modelling_qwen3_vl.rope._get_flat_packed_ranges(
input_ids: torch.Tensor,
packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams | None,
) → list[tuple[int, int, int]] | None#

Return (padded_start, valid_end, padded_end) ranges for flat packed input.

bridge.models.qwen_vl.modelling_qwen3_vl.rope.get_packed_seq_attention_mask(
input_ids: torch.Tensor,
packed_seq_params: megatron.core.packed_seq_params.PackedSeqParams,
) → torch.Tensor#

Build a dense keep mask matching packed sequence metadata.

Collate-time in-batch packing emits a flattened [1, total_padded] token tensor. cu_seqlens_q_padded identifies segment boundaries in that flattened tensor, while cu_seqlens_q may identify the unpadded token counts. Qwen3-VL still needs a dense mask for its local THD conversion, so derive it from the same metadata used by attention.

class bridge.models.qwen_vl.modelling_qwen3_vl.rope.Qwen3VLMultimodalRotaryEmbedding(
kv_channels: int,
rotary_percent: float = 1.0,
rotary_interleaved: bool = False,
seq_len_interpolation_factor: Optional[float] = None,
rotary_base: int = 10000,
cp_group: torch.distributed.ProcessGroup = None,
)#

Bases: torch.nn.Module

Multimodal Rotary Embedding for Qwen3-VL/Qwen3-Omni language model.

Parameters:
  • kv_channels (int) – Projection weights dimension in multi-head attention. Obtained from transformer config

  • rotary_percent (float) – Percent of rotary dimension to use for rotary position embeddings.

  • rotary_interleaved (bool, optional) – If True, interleaved rotary position embeddings. Defaults to False.

  • seq_len_interpolation_factor (float, optional) – scale of linearly interpolating RoPE for longer sequences. The value must be a float larger than 1.0. Defaults to None

  • rotary_base (int, optional) – Base period for rotary position embeddings. Defaults to 10000.

Initialization

apply_interleaved_mrope(freqs, mrope_section)#

Apply interleaved MRoPE to 3D rotary embeddings. Reorganizes frequency layout from chunked [TTT…HHH…WWW] to interleaved [THTHWHTHW…TT], preserving frequency continuity.

Parameters:
  • x – (3, bs, seq_len, head_dim // 2)

  • mrope_section – (3,)

Returns:

(bs, seq_len, head_dim // 2)

Return type:

x_t

forward(
position_ids: torch.Tensor,
mrope_section: List[int] | None,
packed_seq_params: Optional[megatron.core.packed_seq_params.PackedSeqParams] = None,
*,
cp_group: torch.distributed.ProcessGroup | None = None,
position_ids_cp_sharded: bool = False,
**kwargs,
) → torch.Tensor#

Forward pass of multimodal RoPE embedding.

Parameters:
  • position_ids (torch.Tensor) – A postion_id tensor with shape [3, batchsize, seqlens]

  • mrope_section (list[int]) – Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.

  • packed_seq_params (PackedSeqParams, optional) – Packed sequence params. Defaults to None.

  • cp_group (ProcessGroup, optional) – Runtime CP group; defaults to the construction group.

  • position_ids_cp_sharded (bool) – Whether position_ids already hold only this CP rank’s part of the sequence. The embedding is then returned without slicing it for the rank again.

Returns:

Embeddings after applying RoPE.

Return type:

Tensor

get_rotary_seq_len(
inference_context: megatron.core.inference.contexts.BaseInferenceContext,
transformer: megatron.core.transformer.transformer_block.TransformerBlock,
transformer_input: torch.Tensor,
transformer_config: megatron.core.transformer.transformer_config.TransformerConfig,
packed_seq_params: Optional[megatron.core.packed_seq_params.PackedSeqParams] = None,
*,
inference_params: Optional[megatron.core.inference.contexts.BaseInferenceContext] = None,
) → int#

Compatibility shim for newer MCore GPT preprocessing.

Qwen3-VL/Qwen3-Omni mRoPE uses explicit multimodal position_ids, but the upstream GPT preprocess path still queries a rotary sequence length helper when preparing inputs.

bridge.models.qwen_vl.modelling_qwen3_vl.rope._build_llm_rope_positions(
sample_input_ids: torch.Tensor,
*,
spatial_merge_size: int,
image_token_id: int,
video_token_id: int,
vision_start_token_id: int,
image_grid_thw: torch.Tensor | None,
video_grid_thw: torch.Tensor | None,
image_index: int,
video_index: int,
) → tuple[torch.Tensor, int, int]#

Build Qwen3-VL MRoPE positions for one logical sample.

bridge.models.qwen_vl.modelling_qwen3_vl.rope.get_rope_index(
spatial_merge_size: int,
image_token_id: int,
video_token_id: int,
vision_start_token_id: int,
input_ids: Optional[torch.LongTensor] = None,
image_grid_thw: Optional[torch.LongTensor] = None,
video_grid_thw: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
packed_seq_params: Optional[megatron.core.packed_seq_params.PackedSeqParams] = None,
) → tuple[torch.Tensor, torch.Tensor]#

Different from the original implementation, Qwen3VL use timestamps rather than absolute time position ids.

bridge.models.qwen_vl.modelling_qwen3_vl.rope.apply_rotary_pos_emb_thd_absolute(
t: torch.Tensor,
cu_seqlens: torch.Tensor,
freqs: torch.Tensor,
rotary_interleaved: bool = False,
) → torch.Tensor#

A baseline implementation of applying RoPE for thd format.

Parameters:
  • t (Tensor) – Input tensor T is of shape [t, h, d]

  • cu_seqlens (Tensor) – Cumulative sum of sequence lengths in a batch for t,

  • consistency. (with shape [b + 1] and dtype torch.int32. Currently unused but kept for API)

  • freqs (Tensor) – Rotary Positional embedding tensor freq is of shape [max_s, 1, 1, d]

Returns:

Shape [t, h, d]. The input tensor after applying RoPE.

Return type:

Tensor

bridge.models.qwen_vl.modelling_qwen3_vl.rope._fused_rope_unsupported_reason(
t: torch.Tensor,
freqs: torch.Tensor,
cu_seqlens: torch.Tensor | None,
) → str | None#

Return why Transformer Engine’s fused RoPE cannot replace the unfused code here, or None if it can.

The unfused code pairs row i of freqs with position i of t (token i for packed input), broadcasting it over the heads, and over the batch when freqs has a single batch column. Transformer Engine’s SBHD kernel does the same for a dense [rows, 1, 1, rotary_dim] table, so any input that can be presented in that form takes the fused path. Only tensor metadata is read: the check does not synchronize with the device and is safe during CUDA graph capture.

Parameters:
  • t – Query or key, [s, b, h, d], or [t, h, d] when cu_seqlens is given.

  • freqs – Rotary angles, one row per position (and sample) or per packed token.

  • cu_seqlens – Packed-sequence boundaries, or None for sbhd input.

Returns:

A short reason when the inputs need the unfused implementation, else None.

bridge.models.qwen_vl.modelling_qwen3_vl.rope._warn_fused_rope_fallback(reason: str) → None#

Report, once per reason and process, that apply_rope_fusion fell back to the unfused implementation.

bridge.models.qwen_vl.modelling_qwen3_vl.rope._apply_fused_rotary_pos_emb_absolute(
t: torch.Tensor,
freqs: torch.Tensor,
*,
rotary_interleaved: bool,
) → torch.Tensor#

Apply per-token RoPE with Transformer Engine’s fused SBHD kernel.

The kernel computes in FP32, rounds once to t’s dtype and returns a new contiguous tensor. Callers check the inputs with :func:_fused_rope_unsupported_reason first.

bridge.models.qwen_vl.modelling_qwen3_vl.rope.apply_rotary_pos_emb_absolute(
t: torch.Tensor,
freqs: torch.Tensor,
config: megatron.bridge.models.qwen_vl.modelling_qwen3_vl.transformer_config.Qwen3VLTransformerConfig,
cu_seqlens: Optional[torch.Tensor] = None,
) → torch.Tensor#

Apply Qwen’s per-token rotary embedding to a query or key tensor.

Unlike Megatron-Core’s apply_rotary_pos_emb, freqs is not a table indexed by the position within a sequence: row i holds the angles of position i of t (token i for packed input), already sliced for this context-parallel rank, so cu_seqlens is not needed to pair them.

With config.apply_rope_fusion, Transformer Engine’s fused kernel runs whenever it computes the same rotation (see :func:_fused_rope_unsupported_reason); other inputs use the unfused implementation, with one warning per reason. The kernel computes in FP32 and rounds once to t’s dtype, which is what config.apply_rotary_pos_emb_in_fp32 asks for, so t is passed to it without casts.

Parameters:
  • t – Query or key, [s, b, h, d], or [t, h, d] for packed (thd) input.

  • freqs – Rotary angles. For [s, b, h, d] input, [s, b, 1, rotary_dim] (one row per position and sample, as MRoPE produces) or [s, 1, 1, rotary_dim]; for packed input, [t, 1, 1, rotary_dim].

  • config – The attention config; reads apply_rope_fusion, apply_rotary_pos_emb_in_fp32 and rotary_interleaved.

  • cu_seqlens – Packed-sequence boundaries for thd input, or None.

Returns:

t with its first rotary_dim channels rotated, in t’s dtype.