Skip to navigation

nemo_automodel.components.models.glm5_next

View as MarkdownOpen in Claude

Native AutoModel support for zai-org/GLM-5.3-Flash.

Submodules

Package Contents

Classes

NameDescription
Glm5NextConfigTop-level GLM-5.3 vision-language configuration.
Glm5NextForConditionalGenerationTrainable GLM-5.3 VLM with PP, EP and contiguous packed CP support.
Glm5NextTextConfigConfiguration for the GLM-5.3 hybrid KDA/KPool-DSA text backbone.
Glm5NextVisionConfigConfiguration for the GLM-5.3 image/video encoder.

Data

ModelClass

API

class nemo_automodel.components.models.glm5_next.config.Glm5NextConfig(
text_config: dict[str, typing.Any] | nemo_automodel.components.models.glm5_next.config.Glm5NextTextConfig | None = None,
vision_config: dict[str, typing.Any] | nemo_automodel.components.models.glm5_next.config.Glm5NextVisionConfig | None = None,
image_token_id: int = 154854,
video_token_id: int = 154855,
image_start_token_id: int = 154830,
image_end_token_id: int = 154831,
video_start_token_id: int = 154832,
video_end_token_id: int = 154833,
tie_word_embeddings: bool = False,
kwargs: typing.Any = {}
)

Bases: PretrainedConfig

Top-level GLM-5.3 vision-language configuration.

hidden_size
= text_config.hidden_size
keys_to_ignore_at_inference
= ['past_key_values']
max_position_embeddings
= text_config.max_position_embeddings
model_type
= 'glm5_next'
sub_configs
vocab_size
= text_config.vocab_size
nemo_automodel.components.models.glm5_next.config.Glm5NextConfig.get_text_config(
decoder: bool = False

Return the decoder config using the Transformers multimodal protocol.

nemo_automodel.components.models.glm5_next.config.Glm5NextConfig.to_dict() -> dict[str, typing.Any]
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.config.Glm5NextTextConfig(
vocab_size: int = 154880,
hidden_size: int = 4096,
intermediate_size: int = 12288,
moe_intermediate_size: int = 2048,
num_hidden_layers: int = 45,
num_attention_heads: int = 64,
num_key_value_heads: int = 64,
n_shared_experts: int = 1,
n_routed_experts: int = 288,
routed_scaling_factor: float = 2.5,
kv_lora_rank: int = 512,
q_lora_rank: int = 1536,
qk_rope_head_dim: int = 0,
qk_nope_head_dim: int = 256,
v_head_dim: int = 256,
n_group: int = 1,
topk_group: int = 1,
num_experts_per_tok: int = 8,
norm_topk_prob: bool = True,
mlp_layer_types: list[str] | None = None,
layer_types: list[str] | None = None,
indexer_types: list[str] | None = None,
index_topk_pattern: str | list[str] | None = None,
index_topk_freq: int = 1,
index_skip_topk_offset: int = 2,
index_topk: int = 2048,
index_head_dim: int = 128,
index_n_heads: int = 32,
index_kpool: int = 16,
index_kpool_always_select_tail: bool = True,
hidden_act: str = 'silu',
swiglu_limit: float = 10.0,
linear_head_dim: int = 128,
linear_num_heads: int = 64,
linear_conv_kernel_dim: int = 4,
linear_lower_bound: float | None = -5.0,
linear_attn_config: dict[str, typing.Any] | None = None,
hc_mult: int = 4,
hc_eps: float = 1e-06,
hc_sinkhorn_iters: int = 20,
max_position_embeddings: int = 1048576,
initializer_range: float = 0.02,
rms_norm_eps: float = 1e-05,
use_cache: bool = False,
attention_bias: bool = False,
attention_dropout: float = 0.0,
output_router_logits: bool = False,
router_aux_loss_coef: float = 0.001,
num_nextn_predict_layers: int = 1,
pad_token_id: int | None = 154820,
bos_token_id: int | None = None,
eos_token_id: int | list[int] | None = None,
tie_word_embeddings: bool = False,
kwargs: typing.Any = {}
)

Bases: PretrainedConfig

Configuration for the GLM-5.3 hybrid KDA/KPool-DSA text backbone.

attribute_map
= {'num_local_experts': 'n_routed_experts'}
flops_formula
= staticmethod(glm5_next_flops)
indexer_types
= list(indexer_types)
keys_to_ignore_at_inference
= ['past_key_values']
layer_types
= list(layer_types)
linear_attn_config
mlp_layer_types
= list(mlp_layer_types)
model_type
= 'glm5_next_text'
num_local_experts
int

Alias used by Hugging Face expert implementations.

qk_head_dim
= qk_nope_head_dim + qk_rope_head_dim
nemo_automodel.components.models.glm5_next.config.Glm5NextTextConfig.to_dict() -> dict[str, typing.Any]
class nemo_automodel.components.models.glm5_next.config.Glm5NextVisionConfig(
depth: int = 24,
hidden_size: int = 1024,
hidden_act: str = 'silu',
attention_bias: bool = True,
attention_dropout: float = 0.0,
num_heads: int = 16,
in_channels: int = 3,
image_size: int = 448,
patch_size: int = 14,
rms_norm_eps: float = 1e-05,
spatial_merge_size: int = 2,
temporal_patch_size: int = 2,
out_hidden_size: int = 4096,
intermediate_size: int = 4096,
projection_intermediate_size: int = 10240,
initializer_range: float = 0.02,
swiglu_limit: float = 10.0,
kwargs: typing.Any = {}
)

Bases: PretrainedConfig

Configuration for the GLM-5.3 image/video encoder.

model_type
= 'glm5_next_vision'
nemo_automodel.components.models.glm5_next.config.Glm5NextVisionConfig.to_dict() -> dict[str, typing.Any]
nemo_automodel.components.models.glm5_next.ModelClass = Glm5NextForConditionalGeneration