Skip to navigation

nemo_automodel.components.models.glm5_next.model

View as MarkdownOpen in Claude

Native AutoModel implementation of GLM-5.3-Flash.

Module Contents

Classes

NameDescription
Glm5NextCausalLMOutputWithPastGLM-5.3 output extended with the MTP head’s per-depth hidden states.
Glm5NextForConditionalGenerationTrainable GLM-5.3 VLM with PP, EP and contiguous packed CP support.
Glm5NextModelCheckpoint-layout container for visual and language_model.
Glm5NextTextModelEmbedding, mHC decoder stack, mean stream collapse and final RMSNorm.

Functions

NameDescription
_packed_context_from_inputsBuild one global document map for a non-CP forward.
build_glm5_next_moe_configTranslate the GLM router/expert contract to AutoModel’s grouped MoE.

Data

ModelClass

API

class nemo_automodel.components.models.glm5_next.model.Glm5NextCausalLMOutputWithPast(
mtp_per_depth_h: list[torch.Tensor] | None = None,
mtp_loss_scaling_factor: float | None = None
)
Dataclass

Bases: CausalLMOutputWithPast

GLM-5.3 output extended with the MTP head’s per-depth hidden states.

mtp_loss_scaling_factor
float | None = None

Weight of the summed per-depth MTP loss.

mtp_per_depth_h
list[Tensor] | None = None

One [batch, local_sequence, hidden] tensor per MTP depth, already normalized for the shared lm_head; None outside training or when MTP is disabled.

class nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration(
logits_dtype: torch.dtype | None = None,
moe_overrides: dict[str, typing.Any] | None = None,
mtp_loss_scaling_factor: float = 0.1
)

Bases: HFCheckpointingMixin, Module, MoEFSDPSyncMixin

Trainable GLM-5.3 VLM with PP, EP and contiguous packed CP support.

_keep_in_fp32_modules_strict
_packed_cp_attn_backends
= ('sdpa', 'cudnn')
_vlm_chunk_idx
int | None = None
_vlm_image_grid_hws_chunks
list[Tensor] | None = None
_vlm_pixel_values_chunks
list[Tensor] | None = None
_vlm_pixel_values_videos_chunks
list[Tensor] | None = None
backend
generation_config
= generation_config_from_model_config(config)
language_model
Glm5NextTextModel

Expose the text module through the multimodal discovery protocol.

lm_head
model
mtp
mtp_config
state_dict_adapter
tie_word_embeddings_support
TieSupport = TieSupport.UNTIED_ONLY
vocab_size
= text_config.vocab_size
nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration._embed_and_splice(
input_ids: torch.Tensor,
pixel_values: torch.Tensor | None,
image_grid_thw: torch.Tensor | None
) -> torch.Tensor

Embed the full sequence and replace image placeholder positions.

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration._mtp_embed_inputs(
inputs_embeds: torch.Tensor,
) -> tuple[torch.Tensor, ...]

Shift the full-sequence embeddings once per MTP depth and keep this rank’s slice.

Parameters:

inputs_embeds
torch.Tensor

Spliced embeddings [batch, padded_sequence, hidden] covering the whole (CP-padded) sequence.

context
Glm5NextPackedContext

Document map whose doc_ids are [batch, padded_sequence].

Returns: torch.Tensor

One [batch, local_sequence, hidden] tensor per depth; position t

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.forward(
input_ids: torch.Tensor | None = None,
attention_mask: torch.Tensor | None = None,
position_ids: torch.Tensor | None = None,
inputs_embeds: torch.Tensor | None = None,
padding_mask: torch.Tensor | None = None,
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.Tensor | None = None,
pixel_values_videos: torch.Tensor | None = None,
logits_to_keep: int | torch.Tensor = 0,
output_hidden_states: bool | None = None,
kwargs: typing.Any = {}

Decode ids [B,S] or a PP activation [B,Slocal,hc_mult,H].

Vision splice and CP slicing run only on the embedding stage. Packed metadata arrives as a chunkable tuple under multi-microbatch PP, then gets a fresh per-microbatch boundary cache. streams below is config.text_config.hc_mult; padded_global_sequence is the global length padded to a multiple of the CP size, and local_sequence is that length divided by the CP size.

Parameters:

input_ids
torch.Tensor | NoneDefaults to None

Integer tensor of shape [microbatch, global_sequence] (or [global_sequence]) on the embedding stage; it is not CP sharded. Later PP stages receive residual streams of shape [microbatch, local_sequence, streams, hidden] in this position, already local to this CP rank.

attention_mask
torch.Tensor | NoneDefaults to None

Optional integer tensor of shape [microbatch, global_sequence], binary or holding one-based document ids. Read only when glm5_next_packed_context is None.

position_ids
torch.Tensor | NoneDefaults to None

Ignored; positions follow the document map.

inputs_embeds
torch.Tensor | NoneDefaults to None

Optional tensor of shape [microbatch, global_sequence, hidden] on the embedding stage, padded and sliced here to this rank’s interval; or already-local [microbatch, local_sequence, streams, hidden] on later stages.

padding_mask
torch.Tensor | NoneDefaults to None

Optional Boolean tensor of shape [microbatch, local_sequence], with True marking padding. Defaults to nonpositive local document ids.

pixel_values
torch.Tensor | NoneDefaults to None

Optional flattened image patches of shape [vision_patches, channels * temporal_patch * patch * patch]. Under PP microbatching the embedding stage reads its chunk from _vlm_pixel_values_chunks instead.

image_grid_thw
torch.Tensor | NoneDefaults to None

Integer tensor of shape [images, 3] holding each image’s (t, h, w) patch grid; required with pixel_values.

pixel_values_videos
torch.Tensor | NoneDefaults to None

Unsupported; must be None. Empty PP chunks are treated as None.

logits_to_keep
int | torch.TensorDefaults to 0

0 to project every local position, or the positions to keep as in slice_logits_to_keep.

output_hidden_states
bool | NoneDefaults to None

Whether to attach final hidden states.

glm5_next_packed_context
Glm5NextPackedContext | Glm5NextPackedMetadata | NoneDefaults to None

Per-microbatch context or Glm5NextPackedMetadata (doc_ids, seq_start, cp_size, original_seq_len). doc_ids is an integer tensor of shape [microbatch, padded_global_sequence], replicated across CP ranks; nonpositive values mark padding. seq_start is the global offset of this rank’s contiguous interval, and original_seq_len is the length before CP padding. The global map is used even on later PP stages, whose activations are already local. When None, a non-CP context is built from input_ids, attention_mask, padding_mask and cu_seqlens/_packed_seq_ids.

**kwargs
AnyDefaults to {}

cu_seqlens and _packed_seq_ids feed the fallback context. All kwargs reach the decoder layers.

Returns: Glm5NextCausalLMOutputWithPast | torch.Tensor

With _pp_return_hidden_states, the text-model tensor: [microbatch,

Raises:

  • ValueError: If the MTP head is enabled while the model is split into pipeline stages.
nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.from_config(
kwargs: typing.Any = {}
) -> 'Glm5NextForConditionalGeneration'
classmethod

Construct from an already resolved native config.

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.from_pretrained(
pretrained_model_name_or_path: str,
model_args: typing.Any = (),
kwargs: typing.Any = {}
) -> 'Glm5NextForConditionalGeneration'
classmethod

Resolve the local config and generation settings; checkpoint loading is owned by AutoModel.

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.get_image_features(
pixel_values: torch.Tensor,
image_grid_thw: torch.Tensor

Return raw and merged features for flattened image patches.

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.get_input_embeddings() -> torch.nn.Module

Return the token embedding table.

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.get_output_embeddings() -> torch.nn.Module

Return the untied language-model head.

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.get_pipeline_stage_metas(
is_first: bool,
microbatch_size: int,
seq_len: int,
dtype: torch.dtype
) -> tuple[tuple[torch.Tensor, ...], tuple[torch.Tensor, ...]]

Describe token ids [B,S] and local mHC activations [B,S/CP,M,H].

CP pads the global length to a multiple of its size. Only the last stage emits collapsed hidden states [B,S/CP,H] or logits [B,S/CP,V]; the first stage still receives unsharded token ids.

Parameters:

is_first
bool

Whether the stage owns the token embedding.

microbatch_size
int

PP microbatch size.

seq_len
int

Global sequence length before CP padding.

dtype
torch.dtype

Activation dtype.

Returns: tuple[torch.Tensor, ...]

One-element input and output tuples of meta tensors. The input is

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.initialize_weights(
buffer_device: torch.device | None = None,
dtype: torch.dtype = torch.bfloat16
) -> None

Initialize all tensors for checkpoint-free construction.

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.prepare_model_inputs_for_cp(
batch: dict[str, typing.Any],
num_chunks: int = 1
) -> dict[str, typing.Any]

Install GLM’s contiguous packed sharder while leaving media and ids global.

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.prepare_mtp_inputs_for_cp(
batch: dict[str, typing.Any],
ignore_index: int = -100

Shift MTP targets globally with the same document map the GLM CP sharder uses.

Parameters:

batch
dict[str, Any]

Unsharded batch with input_ids and labels of shape [batch, sequence] (or [sequence] from THD collaters) and the packing metadata read by the GLM CP sharder.

ignore_index
intDefaults to -100

Target fill value past each document end.

Returns: MTPContextParallelInputs

Global per-depth token ids, position ids, targets and validity masks of

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.set_input_embeddings(
value: torch.nn.Module
) -> None

Replace the token embedding table.

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.set_output_embeddings(
value: torch.nn.Module
) -> None

Replace the language-model head.

nemo_automodel.components.models.glm5_next.model.Glm5NextForConditionalGeneration.update_moe_gate_bias() -> None

Update no-aux-loss router correction biases after an optimizer step.

class nemo_automodel.components.models.glm5_next.model.Glm5NextModel(
moe_overrides: dict[str, typing.Any] | None = None
)

Bases: Module

Checkpoint-layout container for visual and language_model.

language_model
visual
= Glm5NextVisionModel(config.vision_config)
nemo_automodel.components.models.glm5_next.model.Glm5NextModel.get_image_features(
pixel_values: torch.Tensor,
image_grid_thw: torch.Tensor

Encode image patches and split-free concatenated features.

class nemo_automodel.components.models.glm5_next.model.Glm5NextTextModel(
moe_overrides: dict[str, typing.Any] | None = None
)

Bases: Module

Embedding, mHC decoder stack, mean stream collapse and final RMSNorm.

embed_tokens
layers
moe_config
norm
padding_idx
= config.pad_token_id
nemo_automodel.components.models.glm5_next.model.Glm5NextTextModel.forward(
input_ids: torch.Tensor | None = None,
inputs_embeds: torch.Tensor | None = None,
padding_mask: torch.Tensor | None = None,
kwargs: typing.Any = {}
) -> torch.Tensor

Decode local tokens, preserving residual streams between PP stages.

Only the embedding stage (embed_tokens present) expands the streams; the final-norm stage (norm present) averages them and applies RMSNorm. streams below is config.hc_mult.

Parameters:

input_ids
torch.Tensor | NoneDefaults to None

Optional integer tensor of shape [batch, local_sequence], embedded on the embedding stage. Exactly one of input_ids and inputs_embeds must be given.

inputs_embeds
torch.Tensor | NoneDefaults to None

Optional tensor of shape [batch, local_sequence, hidden] on the embedding stage, or residual streams of shape [batch, local_sequence, streams, hidden] on later PP stages.

glm5_next_packed_context
Glm5NextPackedContext

Global document layout. Its doc_ids tensor has shape [batch, padded_global_sequence] and is replicated across CP ranks; seq_start locates this rank’s local interval. Each row’s document-range cache is filled in place before the decoder layers run.

padding_mask
torch.Tensor | NoneDefaults to None

Optional Boolean tensor of shape [batch, local_sequence], with True marking padding.

**kwargs
AnyDefaults to {}

Forwarded unchanged to every decoder layer.

Returns: torch.Tensor

On the final-norm stage, a tensor of shape [batch, local_sequence,

nemo_automodel.components.models.glm5_next.model.Glm5NextTextModel.init_weights(
buffer_device: torch.device
) -> None

Initialize a checkpoint-free text model on buffer_device.

nemo_automodel.components.models.glm5_next.model.Glm5NextTextModel.update_moe_gate_bias() -> None

Update every sparse layer’s no-aux-loss routing correction bias.

nemo_automodel.components.models.glm5_next.model._packed_context_from_inputs(
input_ids: torch.Tensor,
attention_mask: torch.Tensor | None,
padding_mask: torch.Tensor | None,
cu_seqlens: torch.Tensor | None,
packed_seq_ids: torch.Tensor | None

Build one global document map for a non-CP forward.

Sources are tried in order: packed_seq_ids, cu_seqlens, a 2-D attention_mask, then padding_mask; otherwise every token belongs to document 1.

Parameters:

input_ids
torch.Tensor

Tensor of shape [batch, sequence]. Only its shape and device are read.

attention_mask
torch.Tensor | None

Optional integer tensor of shape [batch, sequence], either binary (one document) or one-based packed document ids with 0 at padding.

padding_mask
torch.Tensor | None

Optional Boolean tensor of shape [batch, sequence], with True marking padding.

cu_seqlens
torch.Tensor | None

Optional integer tensor of cumulative document boundaries, flattened to [documents + 1]; negative entries are ignored. Describes a single packed row.

packed_seq_ids
torch.Tensor | None

Optional integer tensor of shape [batch, sequence] or [sequence] holding one-based document ids, with 0 at padding.

Returns: Glm5NextPackedContext

Context whose doc_ids is an int32 tensor of shape [batch,

nemo_automodel.components.models.glm5_next.model.build_glm5_next_moe_config(
dtype: torch.dtype,
overrides: dict[str, typing.Any] | None = None

Translate the GLM router/expert contract to AutoModel’s grouped MoE.

nemo_automodel.components.models.glm5_next.model.ModelClass = Glm5NextForConditionalGeneration