Skip to navigation

nemo_automodel.components.models.glm5_next.layers

View as MarkdownOpen in Claude

Native GLM-5.3 text layers.

The released model alternates Kimi Delta Attention (KDA) and GLM-style KPool-compressed Dynamic Sparse Attention (DSA), with manifold-constrained Hyper-Connections (mHC) around both sublayers. FLA owns the production KDA kernel; small pure-Torch fallbacks keep CPU construction and unit tests useful.

Module Contents

Classes

NameDescription
Glm5NextDecoderLayerOne mHC decoder block with KDA/DSA and dense/MoE feed-forward.
Glm5NextHyperConnectionManifold-constrained mixer for hc_mult residual streams.
Glm5NextHyperConnectionFp32ParamsOwn mHC parameters that must remain fp32 under FSDP mixed precision.
Glm5NextKDAFp32ParamsOwn recurrent-decay parameters that must remain fp32 under FSDP.
Glm5NextKPoolIndexerKPool-compressed DSA indexer for training without a KV cache.
Glm5NextLinearAttentionKimi Delta Attention with released GLM-5.3 checkpoint parameter names.
Glm5NextRMSNormRMSNorm with fp32 variance accumulation.
Glm5NextSparseAttentionNoPE MLA whose visibility is selected by the GLM KPool indexer.
Glm5NextUnweightedRMSNormParameter-free fp32 RMS normalization used by mHC.
_TorchRMSNormGatedGated per-head RMSNorm with optional model-owned compilation.
_TorchShortConvolutionDepthwise causal Conv1d matching FLA ShortConvolution state keys.

Functions

NameDescription
_dense_prefix_indicesEnumerate every visible key when all complete causal pools fit the budget.
_rms_norm_gated-
_short_conv-
_torch_recurrent_kdaDifferentiable reference KDA for CPU/small tensors.

Data

_FLA_MSG

API

class nemo_automodel.components.models.glm5_next.layers.Glm5NextDecoderLayer(
layer_idx: int,
)

Bases: Module

One mHC decoder block with KDA/DSA and dense/MoE feed-forward.

_expand_core
= hc_cores(backend.compile_hc).expand
attn_hc
block_type
= config.layer_types[layer_idx]
ffn_hc
input_layernorm
is_linear_attn
= self.block_type == 'linear_attention'
is_moe_layer
= config.mlp_layer_types[layer_idx] == 'sparse'
mlp
post_attention_layernorm
self_attn
nemo_automodel.components.models.glm5_next.layers.Glm5NextDecoderLayer.forward(
hidden_streams: torch.Tensor,
padding_mask: torch.Tensor | None = None,
kwargs: typing.Any = {}
) -> torch.Tensor

Apply attention and feed-forward sublayers through two mHC mixers.

Parameters:

hidden_streams
torch.Tensor

Tensor of shape [batch, local_sequence, streams, hidden], where streams is config.hc_mult.

packed_context
Glm5NextPackedContext

Global document layout passed to attention; doc_ids has shape [batch, padded_global_sequence].

padding_mask
torch.Tensor | NoneDefaults to None

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

**kwargs
AnyDefaults to {}

Forwarded to the attention module.

Returns: torch.Tensor

Tensor with hidden_streams’s shape and dtype.

nemo_automodel.components.models.glm5_next.layers.Glm5NextDecoderLayer.init_weights(
buffer_device: torch.device,
init_std: float
) -> None

Initialize all decoder children.

nemo_automodel.components.models.glm5_next.layers.Glm5NextDecoderLayer.update_moe_gate_bias() -> None

Update the correction bias for this layer’s learned MoE router.

class nemo_automodel.components.models.glm5_next.layers.Glm5NextHyperConnection(
compile_hc: bool = False
)

Bases: Module

Manifold-constrained mixer for hc_mult residual streams.

hidden_streams is [batch, sequence, hc_mult, hidden]. The returned tensors are post [batch, sequence, hc_mult], comb [batch, sequence, hc_mult, hc_mult] and collapsed [batch, sequence, hidden].

_collapse_core
= cores.collapse
_fp32_params
_project_core
= cores.project
base
Parameter

Expose the checkpoint’s flat mHC base parameter.

fn
hc_eps
= config.hc_eps
hc_mult
= config.hc_mult
hc_sinkhorn_iters
= config.hc_sinkhorn_iters
input_norm
= Glm5NextUnweightedRMSNorm(config.rms_norm_eps)
scale
Parameter

Expose the checkpoint’s flat mHC scale parameter.

nemo_automodel.components.models.glm5_next.layers.Glm5NextHyperConnection.forward(
hidden_streams: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]

Build Sinkhorn mixing weights and collapse streams for one sublayer.

Parameters:

hidden_streams
torch.Tensor

Tensor of shape [batch, sequence, hc_mult, hidden], where hc_mult is the number of residual streams.

Returns: torch.Tensor

FP32 post weights [batch, sequence, hc_mult], FP32 combination

nemo_automodel.components.models.glm5_next.layers.Glm5NextHyperConnection.init_weights(
buffer_device: torch.device,
init_std: float
) -> None

Initialize mHC parameters on buffer_device.

class nemo_automodel.components.models.glm5_next.layers.Glm5NextHyperConnectionFp32Params(
mix_size: int,
)

Bases: Module

Own mHC parameters that must remain fp32 under FSDP mixed precision.

base
scale
nemo_automodel.components.models.glm5_next.layers.Glm5NextHyperConnectionFp32Params.forward(
pre_w: torch.Tensor,
post_w: torch.Tensor,
comb_w: torch.Tensor,
hc: int,
eps: float,
sinkhorn_iters: int
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]

Build FP32 mHC weights while this holder’s FSDP unit is unsharded.

streams below is hc, the number of residual streams (config.hc_mult).

Parameters:

pre_w
torch.Tensor

FP32 tensor of shape [batch, sequence, streams], the raw collapse coefficients.

post_w
torch.Tensor

FP32 tensor of shape [batch, sequence, streams], the raw expansion coefficients.

comb_w
torch.Tensor

FP32 tensor of shape [batch, sequence, streams * streams], row-major raw mixing logits indexed [source_stream, destination_stream]. It may be a last-axis slice of a larger projection.

hc
int

Number of residual streams.

eps
float

Additive stabilizer for pre and Sinkhorn denominators.

sinkhorn_iters
int

Number of Sinkhorn normalization rounds.

Returns: torch.Tensor

pre of shape [batch, sequence, streams] (sigmoid plus eps),

class nemo_automodel.components.models.glm5_next.layers.Glm5NextKDAFp32Params(
num_heads: int,
projection_size: int
)

Bases: Module

Own recurrent-decay parameters that must remain fp32 under FSDP.

A_log
dt_bias
nemo_automodel.components.models.glm5_next.layers.Glm5NextKDAFp32Params.forward(
gate: torch.Tensor,
head_dim: int,
lower_bound: float | None
) -> torch.Tensor

Return log-decay gates [batch, sequence, heads, head_dim].

class nemo_automodel.components.models.glm5_next.layers.Glm5NextKPoolIndexer(
layer_idx: int,
dtype: torch.dtype,
)

Bases: Module

KPool-compressed DSA indexer for training without a KV cache.

always_select_tail
= config.index_kpool_always_select_tail
head_dim
= config.index_head_dim
index_kpool
= config.index_kpool
index_kpool_compress_ape
index_kpool_compress_gate
index_topk
= config.index_topk
k_norm
n_heads
= config.index_n_heads
softmax_scale
= self.head_dim ** -0.5
weights_proj
weights_projection_tile
= 512
wk
wq_b
nemo_automodel.components.models.glm5_next.layers.Glm5NextKPoolIndexer.forward(
full_hidden: torch.Tensor,
query_hidden: torch.Tensor,
query_resid: torch.Tensor,
query_positions: torch.Tensor
) -> torch.Tensor

Prepare one document and select indices for a query chunk.

full_hidden is [1, keys, hidden]; query tensors are [1, queries, ...] and positions are document-local [queries]. Returns [1, queries, index_topk + kpool - 1] int32 indices.

nemo_automodel.components.models.glm5_next.layers.Glm5NextKPoolIndexer.init_weights(
buffer_device: torch.device,
init_std: float
) -> None

Initialize indexer projections and KPool parameters.

nemo_automodel.components.models.glm5_next.layers.Glm5NextKPoolIndexer.prepare_pools(
full_hidden: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]

Compress one document’s keys into KPool candidates.

Parameters:

full_hidden
torch.Tensor

Hidden states with shape [1, keys, hidden] for one unpadded document.

Returns: torch.Tensor

Pool keys with shape [complete_pools, index_head_dim] and raw

nemo_automodel.components.models.glm5_next.layers.Glm5NextKPoolIndexer.select(
query_hidden: torch.Tensor,
query_resid: torch.Tensor,
query_positions: torch.Tensor,
pool_keys: torch.Tensor,
pool_indices: torch.Tensor,
key_length: int,
query_projection_chunk_size: int | None = None
) -> torch.Tensor

Select raw key indices for one query chunk.

Parameters:

query_hidden
torch.Tensor

Tensor of shape [1, queries, hidden].

query_resid
torch.Tensor

Tensor of shape [1, queries, q_lora_rank], the normalized low-rank query states.

query_positions
torch.Tensor

Integer tensor of shape [queries] holding document-local positions. The cuDNN backend requires them to be contiguous and ascending.

pool_keys
torch.Tensor

Tensor of shape [complete_pools, index_head_dim] from prepare_pools.

pool_indices
torch.Tensor

Integer tensor of shape [complete_pools, index_kpool] holding document-local token indices.

key_length
int

Number of tokens in the unpadded document.

query_projection_chunk_size
int | NoneDefaults to None

Original projection tile size, preserved when the cuDNN score kernel processes several tiles together.

Returns: torch.Tensor

Int32 document-local indices of shape [1, queries, index_topk +

class nemo_automodel.components.models.glm5_next.layers.Glm5NextLinearAttention(
layer_idx: int,
compile_norm: bool = False
)

Bases: Module

Kimi Delta Attention with released GLM-5.3 checkpoint parameter names.

A_log
Parameter

Expose the checkpoint’s flat A_log parameter name.

_fp32_params
b_proj
conv_size
= config.linear_conv_kernel_dim
dt_bias
Parameter

Expose the checkpoint’s flat dt_bias parameter name.

f_a_proj
f_b_proj
g_a_proj
g_b_proj
head_dim
= config.linear_head_dim
hidden_size
= config.hidden_size
k_conv1d
k_proj
num_heads
= config.linear_num_heads
o_norm
o_proj
projection_size
= self.head_dim * self.num_heads
q_conv1d
q_proj
v_conv1d
v_proj
nemo_automodel.components.models.glm5_next.layers.Glm5NextLinearAttention._core(
hidden_states: torch.Tensor,
cu_seqlens: torch.Tensor | None = None,
cu_seqlens_cpu: torch.Tensor | None = None,
cp_context: typing.Any = None
) -> torch.Tensor

Project and execute KDA for one packed row or a regular batch.

Parameters:

hidden_states
torch.Tensor

Tensor of shape [rows, sequence, hidden]. Packed and CP calls pass one row, [1, local_sequence, hidden].

cu_seqlens
torch.Tensor | NoneDefaults to None

Optional integer tensor of shape [segments + 1] on the input device with ascending row-local boundaries from 0 to sequence. It is cloned before use and never mutated.

cu_seqlens_cpu
torch.Tensor | NoneDefaults to None

Optional CPU tensor of shape [segments + 1] with the same values as cu_seqlens, passed to FLA to avoid a device synchronization.

cp_context
AnyDefaults to None

Optional FLA CP context for this row, carrying its own boundaries; callers pass it instead of cu_seqlens.

Returns: torch.Tensor

Tensor of shape [rows, sequence, hidden] in the projection dtype.

nemo_automodel.components.models.glm5_next.layers.Glm5NextLinearAttention.forward(
hidden_states: torch.Tensor,
padding_mask: torch.Tensor | None = None,
_: typing.Any = {}
) -> torch.Tensor

Run KDA over local tokens without crossing documents.

Parameters:

hidden_states
torch.Tensor

Tensor of shape [batch, local_sequence, hidden], this rank’s contiguous CP interval.

packed_context
Glm5NextPackedContext | NoneDefaults to None

Optional global document layout whose doc_ids has shape [batch, padded_global_sequence]. With CP each row runs through FLA’s CP context; without CP its per-row boundaries reset the recurrence. None runs each row as one sequence.

padding_mask
torch.Tensor | NoneDefaults to None

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

Returns: torch.Tensor

Tensor of shape [batch, local_sequence, hidden], zero at padding.

nemo_automodel.components.models.glm5_next.layers.Glm5NextLinearAttention.init_weights(
buffer_device: torch.device,
init_std: float
) -> None

Initialize KDA while preserving fp32 recurrent parameters.

nemo_automodel.components.models.glm5_next.layers.Glm5NextLinearAttention.setup_cp_attention(
cp_mesh
) -> None

Attach the one-dimensional contiguous CP mesh.

class nemo_automodel.components.models.glm5_next.layers.Glm5NextRMSNorm(
hidden_size: int,
eps: float,
dtype: torch.dtype,
compile_norm: bool = False
)

Bases: Module

RMSNorm with fp32 variance accumulation.

Input and output have shape [batch, sequence, hidden]; the leading axes may be replaced by any token layout as long as hidden is last.

_norm_core
= rms_norm_core(compile_norm)
weight
= nn.Parameter(torch.ones(hidden_size, dtype=dtype))
nemo_automodel.components.models.glm5_next.layers.Glm5NextRMSNorm.forward(
hidden_states: torch.Tensor
) -> torch.Tensor

Normalize the last axis and preserve the input dtype.

Parameters:

hidden_states
torch.Tensor

Tensor of shape […, hidden], with arbitrary leading dimensions.

Returns: torch.Tensor

Tensor with hidden_states’s shape. Normalization runs in FP32

nemo_automodel.components.models.glm5_next.layers.Glm5NextRMSNorm.reset_parameters() -> None
class nemo_automodel.components.models.glm5_next.layers.Glm5NextSparseAttention(
layer_idx: int,
)

Bases: Module

NoPE MLA whose visibility is selected by the GLM KPool indexer.

indexer
indexer_chunk_pow2_threshold
= 512
indexer_query_chunk_size
= 2048
indexer_score_workspace_bytes
= 256 * 1024 ** 2
kv_a_layernorm
kv_a_proj_with_mqa
kv_b_proj
kv_lora_rank
= config.kv_lora_rank
num_heads
= config.num_attention_heads
o_proj
q_a_layernorm
q_a_proj
q_b_proj
q_lora_rank
= config.q_lora_rank
qk_head_dim
= config.qk_nope_head_dim
query_chunk_size
= 32
scaling
= self.qk_head_dim ** -0.5
v_head_dim
= config.v_head_dim
nemo_automodel.components.models.glm5_next.layers.Glm5NextSparseAttention._forward_document(
full_hidden: torch.Tensor,
query_start: int,
query_end: int
) -> torch.Tensor

Execute sparse attention for a local query interval of one full document.

Parameters:

full_hidden
torch.Tensor

Unpadded document states with shape [1, key_tokens, hidden].

query_start
int

Inclusive document-local index of the first local query.

query_end
int

Exclusive document-local index of the final local query.

Returns: torch.Tensor

Projected attention output with shape

nemo_automodel.components.models.glm5_next.layers.Glm5NextSparseAttention._forward_packed_cudnn(
full_hidden: torch.Tensor,
local_sequence_length: int
) -> torch.Tensor

Batch document-isolated attention after gathering global hidden states.

Preserve the original per-document K/V projection, indexer and query projection order and shapes. Concatenate only the attention inputs.

Parameters:

full_hidden
torch.Tensor

CUDA tensor of shape [batch, padded_global_sequence, hidden], all-gathered across CP ranks (the local tensor when CP is disabled).

packed_context
Glm5NextPackedContext

Global document layout. doc_ids has shape [batch, padded_global_sequence]; seq_start is this rank’s global query offset.

local_sequence_length
int

Number of tokens owned by this CP rank.

Returns: torch.Tensor

Tensor of shape [batch, local_sequence, hidden], zero at tokens

nemo_automodel.components.models.glm5_next.layers.Glm5NextSparseAttention._select_document_indices_cudnn(
query_hidden: torch.Tensor,
q_resid: torch.Tensor,
pool_keys: torch.Tensor,
pool_indices: torch.Tensor,
query_start: int,
query_end: int,
length: int
) -> torch.Tensor

Select document-local keys using the original indexer projection tiles.

Parameters:

query_hidden
torch.Tensor

Tensor of shape [1, queries, hidden], where queries is query_end - query_start.

q_resid
torch.Tensor

Tensor of shape [1, queries, q_lora_rank], the normalized low-rank queries.

pool_keys
torch.Tensor

Tensor of shape [complete_pools, index_head_dim].

pool_indices
torch.Tensor

Integer tensor of shape [complete_pools, index_kpool] holding document-local token indices.

query_start
int

First local query’s position within the document.

query_end
int

Exclusive document-local query end.

length
int

Full document length.

Returns: torch.Tensor

Contiguous int32 tensor of shape [queries, 1, selection_width]

nemo_automodel.components.models.glm5_next.layers.Glm5NextSparseAttention.forward(
hidden_states: torch.Tensor,
padding_mask: torch.Tensor | None = None,
_: typing.Any = {}
) -> torch.Tensor

Run document-isolated sparse attention for this rank’s queries.

Keys come from the full document, so under CP the local states are all-gathered along the sequence with a gradient-summing backward.

Parameters:

hidden_states
torch.Tensor

Tensor of shape [batch, local_sequence, hidden], this rank’s contiguous interval of the CP-padded sequence.

packed_context
Glm5NextPackedContext

Global document layout. doc_ids is an integer tensor of shape [batch, padded_global_sequence], replicated across CP ranks, with nonpositive values at padding; seq_start is this rank’s global query offset.

padding_mask
torch.Tensor | NoneDefaults to None

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

Returns: torch.Tensor

Tensor of shape [batch, local_sequence, hidden], zero at padding

nemo_automodel.components.models.glm5_next.layers.Glm5NextSparseAttention.init_weights(
buffer_device: torch.device,
init_std: float
) -> None

Initialize MLA and indexer parameters.

nemo_automodel.components.models.glm5_next.layers.Glm5NextSparseAttention.setup_cp_attention(
cp_mesh
) -> None

Attach the CP mesh used for differentiable full-sequence gathering.

class nemo_automodel.components.models.glm5_next.layers.Glm5NextUnweightedRMSNorm(
eps: float
)

Bases: Module

Parameter-free fp32 RMS normalization used by mHC.

nemo_automodel.components.models.glm5_next.layers.Glm5NextUnweightedRMSNorm.forward(
hidden_states: torch.Tensor
) -> torch.Tensor

Normalize [..., hc_streams * hidden] without a learned weight.

class nemo_automodel.components.models.glm5_next.layers._TorchRMSNormGated(
hidden_size: int,
eps: float,
dtype: torch.dtype,
compile_norm: bool = False
)

Bases: Glm5NextRMSNorm

Gated per-head RMSNorm with optional model-owned compilation.

_gated_norm_core
= rms_norm_gated_core(compile_norm)
nemo_automodel.components.models.glm5_next.layers._TorchRMSNormGated.forward(
hidden_states: torch.Tensor,
gate: torch.Tensor
) -> torch.Tensor

Normalize each head then sigmoid-gate it.

Parameters:

hidden_states
torch.Tensor

Tensor of shape [batch, sequence, heads, head_dim].

gate
torch.Tensor

Tensor with hidden_states’s shape.

Returns: torch.Tensor

Tensor with hidden_states’s shape and dtype; see

class nemo_automodel.components.models.glm5_next.layers._TorchShortConvolution(
hidden_size: int,
kernel_size: int,
dtype: torch.dtype
)

Bases: Module

Depthwise causal Conv1d matching FLA ShortConvolution state keys.

weight
nemo_automodel.components.models.glm5_next.layers._TorchShortConvolution.forward(
x: torch.Tensor,
cu_seqlens: torch.Tensor | None = None,
cu_seqlens_cpu: torch.Tensor | None = None,
kwargs: typing.Any = {}
) -> tuple[torch.Tensor, None]

Apply causal depthwise convolution and SiLU, resetting at packed boundaries.

Parameters:

x
torch.Tensor

Tensor of shape [batch, sequence, channels]. Packed callers pass one row, [1, sequence, channels].

cu_seqlens
torch.Tensor | NoneDefaults to None

Optional integer tensor of shape [segments + 1] on x’s device, holding ascending row-local boundaries from 0 to sequence; segments are consecutive equal-document-id runs, padding included. The CPU fallback applies the same boundaries to every batch row.

cu_seqlens_cpu
torch.Tensor | NoneDefaults to None

Optional CPU tensor of shape [segments + 1] with the same values as cu_seqlens. Only the FLA CUDA kernel reads it, to avoid a device synchronization.

**kwargs
AnyDefaults to {}

FLA-only cache (initial state), output_final_state and cp_context; the CPU fallback ignores them.

Returns: torch.Tensor

Output of shape [batch, sequence, channels] in x’s dtype, and

nemo_automodel.components.models.glm5_next.layers._TorchShortConvolution.reset_parameters() -> None
nemo_automodel.components.models.glm5_next.layers._dense_prefix_indices(
positions: torch.Tensor,
index_topk: int,
pool_size: int,
always_select_tail: bool
) -> torch.Tensor

Enumerate every visible key when all complete causal pools fit the budget.

Parameters:

positions
torch.Tensor

Integer tensor of shape [queries] holding document-local query positions.

index_topk
int

Maximum number of tokens selected from complete pools.

pool_size
int

Number of tokens per complete pool.

always_select_tail
bool

Whether to include the incomplete causal pool.

Returns: torch.Tensor

Int32 tensor of shape [1, queries, index_topk + tail_width], where

nemo_automodel.components.models.glm5_next.layers._rms_norm_gated(
hidden_size: int,
eps: float,
dtype: torch.dtype,
compile_norm: bool = False
) -> torch.nn.Module
nemo_automodel.components.models.glm5_next.layers._short_conv(
hidden_size: int,
kernel_size: int,
dtype: torch.dtype
) -> torch.nn.Module
nemo_automodel.components.models.glm5_next.layers._torch_recurrent_kda(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
g: torch.Tensor,
beta: torch.Tensor,
cu_seqlens: torch.Tensor | None
) -> torch.Tensor

Differentiable reference KDA for CPU/small tensors.

Parameters:

q
torch.Tensor

Query tensor of shape [batch, sequence, heads, head_dim].

k
torch.Tensor

Key tensor with q’s layout.

v
torch.Tensor

Value tensor with q’s layout.

g
torch.Tensor

Log-decay tensor with q’s layout.

beta
torch.Tensor

Update weights of shape [batch, sequence, heads].

cu_seqlens
torch.Tensor | None

Optional integer tensor [documents + 1] containing packed boundaries. Each boundary resets the FP32 recurrent state.

Returns: torch.Tensor

Tensor of shape [batch, sequence, heads, head_dim] in v’s dtype.

nemo_automodel.components.models.glm5_next.layers._FLA_MSG = 'GLM-5.3 KDA requires the flash-linear-attention/fla extra for GPU training.'