nemo_automodel.components.models.qwen3_5.model
nemo_automodel.components.models.qwen3_5.model
Qwen3.5 dense causal LM with Megatron-style MTP support.
Module Contents
Classes
Functions
Data
API
Bases: Qwen3_5TextRotaryEmbedding
Ensure inv_freq stays in float32 across .to(dtype) calls.
Bases: CausalLMOutputWithPast
Qwen3.5 causal-LM output extended with MTP auxiliary hidden states.
Bases: Block
Qwen3.5 dense decoder block on top of the Qwen3-Next Block.
Identical to Qwen3_5MoeBlock except the MLP degrades to a dense MLP
(no experts). The CP-aware GatedDeltaNet is built natively for
linear-attention layers, and the forward threads NEAT-packing kwargs.
Add the attention output to the residual stream, then apply the MLP sub-block.
The residual add is fused into the post-attention norm.
Parameters:
Residual stream of shape [batch, sequence, hidden], or [tokens, hidden] for the unpadded TE stream.
Attention or GatedDeltaNet output with x’s shape.
Optional padding mask of shape [batch, sequence].
Returns: torch.Tensor
Hidden states with x’s shape.
Run one dense Qwen3.5 decoder block.
Parameters:
Hidden states of shape [batch, sequence, hidden].
Rotary cosine/sine values of shape [batch, sequence, rotary_dim].
Optional validity, indexed document, or backend mask of shape [batch, sequence] or [batch, 1, sequence, sequence].
Optional padding mask of shape [batch, sequence].
Optional positions of shape [batch, sequence] or [axes, batch, sequence].
Optional model-forward-owned packing metadata;
tensor layouts are documented by GatedDeltaPackedMetadata.
Packed or THD metadata: _packed_seq_ids has shape
[batch, sequence] with 1-based document IDs and zero padding.
packed_token_indices has shape [batch, sequence] with row-local
positions and -1 padding, or [tokens] indexing flattened batch
and sequence axes. cu_seqlens has shape [batch, max_documents + 1]
with row-local boundaries and -1 padding, or [documents + 1] for
flattened/THD inputs. max_seqlen is an integer document length.
Returns: torch.Tensor
Hidden states of shape [batch, sequence, hidden].
Bases: Qwen3_5DecoderLayer
One full-attention Qwen3.5 dense MTP sublayer.
Bases: Module
Qwen3.5 dense text decoder rebuilt on the Qwen3-Next Block.
Native counterpart of Qwen3_5MoeTextModelBackend for the dense model:
reuses the same blocks/GatedDeltaNet/norm/rotary so dense and MoE share one
code path, with the fp32 SSMGate built at construction (no runtime patch).
Decode text tokens with model-forward-owned packed GDN metadata.
Parameters:
Optional token IDs of shape [batch, sequence].
Optional token embeddings of shape [batch, sequence, hidden].
Optional validity, indexed document, or backend mask of shape [batch, sequence] or [batch, 1, sequence, sequence].
Optional positions of shape [batch, sequence] or [axes, batch, sequence].
Optional token positions of shape [sequence].
Optional padding mask of shape [batch, sequence].
Unsupported recurrent or KV cache.
Whether to use a cache; only False or None is
supported.
Accepted for Hugging Face compatibility and ignored.
Backend-specific attention arguments, including optional
_packed_seq_ids of shape [batch, sequence], packed_token_indices
of shape [batch, sequence] or [tokens], cu_seqlens of shape
[batch, max_documents + 1] or [documents + 1], and integer
max_seqlen. Batch-major metadata uses -1 padding. Explicit
token metadata is supported without context parallelism.
The multimodal wrapper temporarily prefixes cu_seqlens and
max_seqlen with _text_ while crossing the HF vision path;
their layouts and values are unchanged.
Returns: BaseModelOutputWithPast
Model output whose last_hidden_state has shape [batch, sequence,
Bases: HFCheckpointingMixin, Module
Qwen3.5 dense causal LM with optional Megatron-style MTP head.
Request compact NEAT document IDs when TE consumes packed offsets.
Compute causal-LM logits and optional multi-token prediction states.
Parameters:
Optional token IDs of shape [batch, sequence].
Optional document/validity mask of shape [batch, sequence] or block-causal mask of shape [batch, 1, sequence, sequence].
Optional text positions of shape [batch, sequence] or multi-axis positions of shape [3, batch, sequence] or [4, batch, sequence] including a leading text-position axis.
Optional HF cache; cached generation is unsupported.
Optional embeddings of shape [batch, sequence, hidden].
Optional targets of shape [batch, sequence], ignored here.
Whether to cache states; only False or None is supported.
Trailing token count (zero means all), or position indices of shape [selected_tokens] indexing the sequence axis.
Backbone arguments, including _packed_seq_ids of shape
[batch, sequence], packed_token_indices of shape [batch, sequence]
or [tokens], cu_seqlens of shape [batch, max_documents + 1] or
[documents + 1], and integer max_seqlen. Batch-major metadata
uses -1 padding and is removed before the separate MTP sublayers.
Returns: Qwen3_5CausalLMOutputWithPast
Logits of shape [batch, selected_sequence, vocab], final hidden states
Bases: HFCheckpointingMixin, HFQwen3_5ForConditionalGeneration
Qwen3.5/Qwen3.6 dense VLM with optional Megatron-style MTP head.
The base VLM retains upstream image/video and M-RoPE semantics, with model-owned host metadata and media insertion paths to avoid CUDA syncs. MTP is added as an auxiliary train-time module over the final language hidden states, matching the dense text-only MTP architecture.
Request compact NEAT document IDs when TE consumes packed offsets.
Embed token ids and splice image/video features into the embeddings.
The VLM->LM multimodal scatter runs on the full (unsharded) sequence
inside the forward before the CP sequence shard, so it is identical to
the pre-CP-refactor pre-embed. Vision features may be frame-sharded
across the CP group before the fixed-size splice inserts them into the
full input_ids sequence.
Parameters:
Token ids [batch, sequence] (full, unsharded).
Optional packed image patches for HF vision encoding.
Optional packed video patches.
Per-image [num_images, 3] T/H/W grid.
Per-video [num_videos, 3] T/H/W grid.
Returns: torch.Tensor
inputs_embeds of shape [batch, sequence, hidden] with image /
Encode one modality’s patches into flat, entry-ordered visual tokens under CP.
Under context parallelism the vision tower otherwise runs redundantly on the full,
un-sharded patch set on every CP rank. When the CP vision-frame sharding group is published
(see set_cp_vision_group),
route the single self.model.visual call through
maybe_distribute_visual,
which shards the frames across the CP group and all-gathers the per-frame embeds in
original entry order. Its pooler_output is the flat, already-concatenated tensor,
identical to torch.cat(get_image_features(...).pooler_output, dim=0) (HF
get_image_features splits that same flat tensor per entry). When sharding is
disabled / inactive this is the exact replicated get_image_features /
get_video_features path.
Parameters:
Patch rows of shape [total_patch_rows, patch_dim] for ALL entries
of one modality, frame-contiguous in entry order.
[num_entries, 3] tensor of per-entry (t, h, w) grid sizes.
Select the video (True) vs image (False) replicated fallback.
Returns: torch.Tensor
[total_patch_rows / spatial_merge_size**2, hidden] flat merged-token embeddings
Resolve explicit media or consume the next staged pipeline chunk.
Staged media advances once per microbatch, including text-only inputs. Only explicitly passed media is filtered using token-presence metadata.
Parameters:
Token IDs of shape [batch, sequence], or None.
Forward arguments with optional image and video patch tensors of shape [patches, patch_features] and grids of shape [entries, 3].
Returns: torch.Tensor | None
Image patches [image_patches, patch_features], video patches
Per-stage input/output meta tensors for the PP schedule’s shape inference.
Matches the framework default (first stage consumes full token ids
[mb, seq]; later stages consume hidden states; the last stage owning
lm_head emits logits, earlier stages emit hidden states) except that
under context parallelism the first stage embeds the full sequence and
shards it in forward, so every stage output and later-stage input carries
the LOCAL (padded-to-2*cp then //cp) sequence length while the
first-stage input stays full-length. At cp_size == 1 this reduces to
the default symmetric shapes.
Retain host metadata outside distributed tensor input transfers.
Return a sharder-only CP backend plus the full-sequence mRoPE positions.
Embedding and the VLM->LM multimodal scatter now run inside forward
per microbatch (see _embed_and_splice_for_cp), so this hook only
(a) computes the mRoPE position_ids on the full (unsharded) sequence
via get_rope_index when the batch has none, and (b) returns the
ContextParallelSharder. Packed batches (_packed_seq_ids or a
4D mask) get block-diagonal CP over contiguous chunks so attention and the
GatedDeltaNet keep per-document boundaries; other batches get round-robin
CP. input_ids and the media inputs are left in the batch for the
forward; mm_token_type_ids is consumed here (only get_rope_index
needs it) so the sharded forward never sees a full-length copy.
Parameters:
The batch dict (with input_ids and optional multimodal
keys). input_ids is [batch, sequence]; _packed_seq_ids,
when present, is [batch, sequence] with 1-based document IDs and
zero padding.
Accepted for hook-signature parity; unused.
Raises:
ValueError: Packed batches with a full-attention backend other than SDPA.NotImplementedError: Packed batches with an MTP head.
Prepare dense Qwen VLM future-token streams before CP sharding.
Call this after prepare_model_inputs_for_cp has materialized
full-sequence mRoPE positions.
Parameters:
Full-sequence batch whose input_ids and labels tensors
have shape [batch, sequence] and whose position_ids tensor
has shape [axes, batch, sequence].
Fill value for invalid targets at trailing and packed document-boundary positions.
Returns: MTPContextParallelInputs
Global per-depth token IDs, mRoPE position IDs, targets, and validity
Tie lm_head to the active VLM text embedding when requested.
Bases: HFQwen3_5Model
Thin VLM wrapper exposing language_model internals as properties and
routing the forward: vision encoding and a fixed-size splice when media and
token IDs are present, mask-based splicing for embedded media, and the NeMo dense
backbone for text only.
Replace selected token embeddings without dynamic-size backward ops.
Parameters:
Token embeddings of shape [batch, sequence, hidden].
Media embeddings of shape [media_tokens, hidden], in
the order of true entries in media_mask.
Boolean mask of shape [batch, sequence, 1].
Returns: torch.Tensor
Combined token embeddings of shape [batch, sequence, hidden].
Route multimodal inputs without exposing text boundaries to vision.
Parameters:
Token IDs of shape [batch, sequence], or floating-point pipeline hidden states of shape [batch, sequence, hidden].
Padding/document IDs of shape [batch, sequence] or a dense mask of shape [batch, 1, sequence, sequence].
Text positions of shape [batch, sequence] or mRoPE coordinates of shape [3 or 4, batch, sequence].
Unsupported recurrent or KV cache.
Optional embeddings of shape [batch, sequence, hidden].
Optional image patches of shape [patches, patch_features].
Optional video patches of shape [patches, patch_features].
Image grids of shape [images, 3] in temporal/height/width order.
Video grids of shape [videos, 3] in temporal/height/width order.
Optional token positions of shape [sequence].
Text attention metadata, including cu_seqlens of shape
[batch, max_documents + 1] or [documents + 1], integer
max_seqlen, and packed_token_indices of shape [batch,
sequence] or [tokens]. Image/video-prefixed metadata retains
the inherited HF precomputed-vision contract.
Returns:
Model output with last_hidden_state of shape [batch, sequence,
Encode image patches, keeping SDPA segment lengths on the host.
Parameters:
Tensor of shape [patches, patch_features], in image order.
Integer tensor of shape [images, 3], with temporal, height, and width grid sizes in that order.
Matching CPU grid retained before the distributed wrapper moves tensor inputs to CUDA.
Additional Hugging Face vision-forward arguments.
Returns: tuple | BaseModelOutputWithPooling
Vision output whose last_hidden_state has shape [patches, hidden]
Return image and video masks while checking token counts on device.
Parameters:
Token IDs of shape [batch, sequence], or None when
only embeddings are available.
Token embeddings of shape [batch, sequence, hidden].
Optional image features of shape [image_tokens, hidden].
Optional video features of shape [video_tokens, hidden].
Returns: tuple[torch.Tensor, torch.Tensor]
Image and video boolean masks, each of shape [batch, sequence, 1].
Bases: Qwen3NextAttention
Qwen3.5 full attention with packed block-diagonal CP dispatch.
Route preprocessed QKV through packed CP or the configured backend.
Parameters:
Query states of shape [batch, heads, local_sequence, head_dim].
Key states of shape [batch, kv_heads, local_sequence, head_dim].
Value states with the same layout as key.
Keyword arguments produced by the parent attention’s backend preprocessing.
Returns: torch.Tensor
Attention output of shape [batch, heads, local_sequence, head_dim].
Trivial MoEConfig for the dense Qwen3.5 backbone.
The dense model has no experts (num_experts is 0/absent), so Block
builds a dense MLP and never consults this config; it is only required to
satisfy Block.__init__’s signature.
Zero invalid future-token embeddings in the local CP layout.
Parameters:
Per-depth embeddings of shape [batch, sequence, hidden].
Per-depth masks of shape [batch, sequence] in the same
local CP token layout as embed_inputs.
Returns: torch.Tensor
Per-depth embeddings with invalid trailing or packed-boundary positions
Build a 4D block-causal attention mask from an indexed packing mask.
packing_mask is [B, S] with the 1-based document index per token
(0 = padding). The returned bool mask [B, 1, S, S] (True = attend)
keeps attention causal and within each packed document, matching the
backbone’s packed-sequence semantics. Used for the MTP sublayers, which run
SDPA self-attention over the same packed batch (NVBugs 6330129).
Return a Qwen3.5 backend with TE fused RoPE disabled.
Qwen3.5 VLM training can feed full-attention layers in packed/THD shape via the shared Qwen3-Next attention block. TE fused RoPE expects 4D inputs there, so keep the non-fused RoPE path while preserving the rest of the backend selection (TE Linear, attention backend, etc.).
Replace multimodal placeholder rows without dynamic-size indexing.
masked_scatter implements its source gradient through masked_select.
On CUDA that dynamic-size selection synchronizes the stream before allocating
its result. The feature row count is already known, so use fixed-size
nonzero_static indices and index_copy instead. Its backward is the
asynchronous index_fill/index_select pair.
Parameters:
Tensor of shape […, hidden], with arbitrary leading token dimensions.
Tensor of shape […], matching the leading dimensions of inputs_embeds
and on the same device.
Tensor of shape [num_placeholder_tokens, hidden], with the same device and
dtype as inputs_embeds. Rows follow the flattened placeholder order.
Token ID marking the positions to replace.
Modality name used in the count-mismatch error.
Returns: torch.Tensor
Tensor of shape […, hidden] with placeholder rows replaced by features.
Raises:
ValueError: The placeholder count differs fromnum_placeholder_tokens.
Build Qwen3.5 MTP runtime config from HF-style config fields.
Construct dense Qwen3.5 MTP blocks.
Qwen3.5 MTP follows Megatron Bridge: each depth is one full-attention Qwen3.5 decoder block, regardless of the backbone’s GatedDeltaNet layers.