Skip to navigation

nemo_automodel.components.models.glm_moe_dsa.layers

View as MarkdownOpen in Claude

GLM-5.2 DSA layers.

Contains the GlmMoeDsaIndexer for top-k sparse attention selection and GlmMoeDsaMLA which integrates the indexer with Multi-head Latent Attention.

Module Contents

Classes

NameDescription
GlmMoeDsaIndexerIndexer for top-k sparse attention selection.
GlmMoeDsaMLAMulti-head Latent Attention with Indexer for sparse attention.
_AbsorbedSparseQueryBuild the absorbed sparse-attention query [tokens, heads, latent + rope] without a concat.

Functions

NameDescription
_apply_index_rope_half_splitApply NON-interleaved (half-split) RoPE to the indexer’s rope slice.
_dsa_kernel_backendResolve the DSA kernel path from the configured attention backend.
_rotate_activationApply Hadamard rotation activation.
_to_additive_key_maskConvert a {0,1} keep-mask (1=attend, 0=mask) to an ADDITIVE key mask (0 / finfo.min).
absorbed_sparse_queryReturn cat([q_nope @ w_kc (per head), q_pe], -1) as one contiguous tensor without the concat copy.
hadamard_transformFallback hadamard_transform when fast_hadamard_transform is not available.
hadamard_transform_torchMultiply H_n @ u where H_n is the Hadamard matrix of dimension n x n.

Data

_FAST_HADAMARD_AVAILABLE

glm_dsa_indexer_replay

API

class nemo_automodel.components.models.glm_moe_dsa.layers.GlmMoeDsaIndexer(
config: transformers.models.glm_moe_dsa.configuration_glm_moe_dsa.GlmMoeDsaConfig,
)

Bases: Module

Indexer for top-k sparse attention selection.

Based on the official GLM-5.2 training implementation. Computes attention scores between queries and keys with per-head weights, applies ReLU activation, then selects the top-k positions to attend to.

Key features:

  • Uses LayerNorm (not RMSNorm) for key normalization
  • Has a weights_proj that learns per-head importance weights
  • Optional Hadamard transform (rotate_activation) on Q and K
  • ReLU activation on attention scores before weighting
head_dim
= config.index_head_dim
hidden_size
= config.hidden_size
index_topk
= config.index_topk
k_norm
num_heads
= config.index_n_heads
q_lora_rank
= config.q_lora_rank
qk_nope_head_dim
= self.head_dim - self.qk_rope_head_dim
qk_rope_head_dim
= config.qk_rope_head_dim
rope_interleave
= getattr(config, 'indexer_rope_interleave', False)
softmax_scale
= self.head_dim ** -0.5
weights_proj
wk
wq_b
nemo_automodel.components.models.glm_moe_dsa.layers.GlmMoeDsaIndexer._head_weights(
x: torch.Tensor
) -> torch.Tensor

Per-head indexer weights in fp32.

The projection follows the GLM-5.3 RL trainer / SGLang: one fp32 GEMM on the resident (bf16) weight, in every configuration. HF Transformers lists indexer.weights_proj in _keep_in_fp32_modules but enforces it only for fp16 loads, so a bf16 HF model rounds the projection to bf16; that rounding is deliberately not reproduced (it only moves near-tied keys). The GEMM runs with autocast disabled: F.linear is autocast-eligible, so casting the operands alone would still produce bf16 under a bf16 autocast wrapper, and the dense scorer’s autocast-disabled head reduction needs fp32 operands. An installed adapter (LoRA/DoRA, possibly with dropout) overrides forward; it is always called so its update, dropout and magnitude semantics are kept, and its output is lifted to fp32.

Parameters:

x
torch.Tensor

Hidden states of shape [tokens, hidden] (THD) or [batch, sequence, hidden].

Returns: torch.Tensor

fp32 tensor of shape x.shape[:-1] + [index_n_heads].

nemo_automodel.components.models.glm_moe_dsa.layers.GlmMoeDsaIndexer.forward(
x: torch.Tensor,
q_resid: torch.Tensor,
freqs_cis: torch.Tensor,
attention_mask: torch.Tensor | None = None,
attn_kwargs: typing.Any = {}
) -> torch.Tensor

Compute top-k indices for sparse attention.

Parameters:

x
torch.Tensor

Hidden-state tensor of shape [batch, sequence, hidden] for BSHD or [tokens, hidden] for packed THD.

q_resid
torch.Tensor

Query-LoRA residual tensor of shape [batch, sequence, q_lora_rank] for BSHD or [tokens, q_lora_rank] for packed THD.

freqs_cis
torch.Tensor

Complex RoPE tensor of shape [batch, sequence, rope_head_dim / 2] for BSHD or [tokens, rope_head_dim / 2] for packed THD.

attention_mask
torch.Tensor | NoneDefaults to None

Optional key mask tensor of shape [batch, sequence] or additive attention tensor of shape [batch, 1, sequence, sequence].

**attn_kwargs
AnyDefaults to {}

Attention metadata. Optimized packed backends require an int32 cu_seqlens tensor of shape [sequences + 1]. Packed CP may also supply glm_dsa_cp_query_indices of shape [tokens] and cu_seqlens_padded of shape [sequences + 1]. The cuDNN backend requires CUDA bfloat16 query/key tensors.

Returns: torch.Tensor

Top-k index tensor. The optimized packed backends return contiguous int32

nemo_automodel.components.models.glm_moe_dsa.layers.GlmMoeDsaIndexer.init_weights(
init_std: float = 0.02
)
class nemo_automodel.components.models.glm_moe_dsa.layers.GlmMoeDsaMLA(
config: transformers.models.glm_moe_dsa.configuration_glm_moe_dsa.GlmMoeDsaConfig,
skip_topk: bool = False
)

Bases: Module

Multi-head Latent Attention with Indexer for sparse attention.

This extends the V3 MLA with an Indexer module that performs top-k selection for sparse attention. The indexer uses the q_lora residual and hidden states to compute which positions to attend to.

index_topk
= config.index_topk
indexer
kv_a_layernorm
kv_a_proj_with_mqa
kv_b_proj
kv_lora_rank
= config.kv_lora_rank
n_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
qk_nope_head_dim
= config.qk_nope_head_dim
qk_rope_head_dim
= config.qk_rope_head_dim
rope_fusion
= backend.rope_fusion
softmax_scale
= mla_softmax_scale(config, self.qk_head_dim)
v_head_dim
= config.v_head_dim
nemo_automodel.components.models.glm_moe_dsa.layers.GlmMoeDsaMLA._build_sparse_mask(
topk_indices: torch.Tensor,
seq_len: int,
qkv_format: str,
bsz: int = 1,
n_heads: int = 1,
dtype: torch.dtype = torch.bfloat16,
attention_mask: torch.Tensor | None = None,
union_across_batches: bool = False
) -> torch.Tensor

Build a sparse attention mask/bias from top-k indices.

Creates a mask tensor where non-top-k positions are set to finfo.min. Works for both TE (core_attention_bias) and SDPA (attn_mask).

Uses the same efficient pattern as the official DeepSeek inference code, but with finfo.min instead of -inf (F.sdpa mishandles -inf float masks): torch.full(..., finfo.min).scatter_(-1, topk_indices, 0)

Parameters:

topk_indices
torch.Tensor

Integer tensor of shape [batch, sequence, top_k] or [tokens, top_k] for packed THD inputs.

seq_len
int

Sequence length

qkv_format
str

‘bshd’ or ‘thd’

bsz
intDefaults to 1

Batch size (only used for bshd format)

n_heads
intDefaults to 1

Number of attention heads to expand to

dtype
torch.dtypeDefaults to torch.bfloat16

Data type for the output tensor

attention_mask
torch.Tensor | NoneDefaults to None

Optional key keep mask of shape [batch, sequence], or additive mask broadcastable to [batch, heads, sequence, sequence].

union_across_batches
boolDefaults to False

If True, union top-k across batches (for TE); if False, keep per-batch masks (for SDPA)

Returns: torch.Tensor

Mask tensor with shape:

  • [1, n_heads, S, S] if union_across_batches=True
  • [B, n_heads, S, S] if union_across_batches=False (bshd)
  • [1, n_heads, T, T] for thd format
nemo_automodel.components.models.glm_moe_dsa.layers.GlmMoeDsaMLA._indexer_draws_random_numbers() -> bool

Return whether the indexer forward draws random numbers: LoRA dropout on one of its projections.

nemo_automodel.components.models.glm_moe_dsa.layers.GlmMoeDsaMLA._select_topk(
x: torch.Tensor,
q_resid: torch.Tensor,
freqs_cis: torch.Tensor,
attention_mask: torch.Tensor | None,
attn_kwargs: typing.Any = {}
) -> torch.Tensor

Run the indexer, or replay its recorded selection during an activation-checkpoint recompute.

The selection is a deterministic function of the layer input and the indexer weights, and no gradient reaches the indexer (its top-k indices are discrete and its scores feed nothing else), so a checkpointed block records the indices in its forward and hands them back in the recompute instead of re-running the score GEMM, the top-k and the index canonicalization. Outside a replay scope (no activation checkpointing, or a block wrapped without Block.nemo_checkpoint_context_fn) the indexer runs as before. It also runs in both passes while LoRA dropout is active on an indexer projection: that forward draws random numbers, and the recompute must draw the same ones so that the dropout masks after the indexer match the forward.

Parameters:

x
torch.Tensor

Hidden states of shape [batch, sequence, hidden] or packed [tokens, hidden].

q_resid
torch.Tensor

Normalized query-LoRA residual with the token axes of x.

freqs_cis
torch.Tensor

Rotary tensor for the indexer’s rope slice.

attention_mask
torch.Tensor | None

Optional key mask forwarded to the indexer.

**attn_kwargs
AnyDefaults to {}

Attention metadata forwarded to the indexer.

Returns: torch.Tensor

Top-k index tensor in the layout documented by GlmMoeDsaIndexer.forward.

nemo_automodel.components.models.glm_moe_dsa.layers.GlmMoeDsaMLA.forward(
x: torch.Tensor,
freqs_cis: torch.Tensor,
attention_mask: torch.Tensor | None = None,
prev_topk_indices: torch.Tensor | None = None,
return_topk_indices: bool = False,
attn_kwargs: typing.Any = {}
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]

Run MLA with (optionally shared) DSA sparse attention.

Parameters:

x
torch.Tensor

Hidden-state tensor of shape [batch, sequence, hidden] for BSHD or [tokens, hidden] for packed THD.

freqs_cis
torch.Tensor

Complex RoPE tensor of shape [batch, sequence, rope_head_dim / 2] for BSHD or [tokens, rope_head_dim / 2] for packed THD.

attention_mask
torch.Tensor | NoneDefaults to None

Optional additive attention tensor of shape [batch, 1, sequence, sequence] or key mask of shape [batch, sequence].

prev_topk_indices
torch.Tensor | NoneDefaults to None

Top-k index tensor from the most recent full indexer layer. Optimized THD backends use int32 [tokens, 1, index_topk]; the dense BSHD path uses int64 [batch, sequence, min(index_topk, sequence)]. Required only for a shared layer (skip_topk=True).

return_topk_indices
boolDefaults to False

When True, return (attn_out, topk_indices) so the caller can thread the selection to subsequent shared layers (GLM IndexShare). When False (default), return just attn_out.

**attn_kwargs
AnyDefaults to {}

Attention metadata. Optimized packed backends require an int32 cu_seqlens tensor of shape [sequences + 1]. Packed CP may also provide _glm_dsa_cp_group and packed query-position tensors. The cuDNN backend requires CUDA bfloat16 inputs.

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

Attention output tensor of shape [batch, sequence, hidden] for BSHD or

nemo_automodel.components.models.glm_moe_dsa.layers.GlmMoeDsaMLA.init_weights(
_buffer_device: torch.device,
init_std: float = 0.02
)
class nemo_automodel.components.models.glm_moe_dsa.layers._AbsorbedSparseQuery()

Bases: Function

Build the absorbed sparse-attention query [tokens, heads, latent + rope] without a concat.

cat([einsum(q_nope, w_kc), q_pe]) materializes the 1.2 GB (16k tokens) kernel input twice; here the head-batched GEMM writes straight into the first latent columns of the kernel input (cuBLAS accepts the strided output view) and the rotated rope slice is copied into the rest.

nemo_automodel.components.models.glm_moe_dsa.layers._AbsorbedSparseQuery.backward(
ctx: typing.Any,
grad_out: torch.Tensor
) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]
staticmethod

Route the latent columns’ gradient through the GEMM and the rope columns’ gradient straight to q_pe.

Parameters:

ctx
Any

Context holding q_nope and w_kc.

grad_out
torch.Tensor

Gradient of shape [tokens, heads, latent + qk_rope_head_dim].

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

Gradients for q_nope, q_pe and w_kc (None where not required).

nemo_automodel.components.models.glm_moe_dsa.layers._AbsorbedSparseQuery.forward(
ctx: typing.Any,
q_nope: torch.Tensor,
q_pe: torch.Tensor,
w_kc: torch.Tensor
) -> torch.Tensor
staticmethod

Absorb the key up-projection into the query.

Parameters:

ctx
Any

Autograd context.

q_nope
torch.Tensor

Non-rope query of shape [tokens, heads, qk_nope_head_dim].

q_pe
torch.Tensor

Rotated rope query of shape [tokens, heads, qk_rope_head_dim], same dtype as q_nope.

w_kc
torch.Tensor

Key up-projection of shape [heads, qk_nope_head_dim, latent], same dtype as q_nope.

Returns: torch.Tensor

Contiguous tensor of shape [tokens, heads, latent + qk_rope_head_dim].

nemo_automodel.components.models.glm_moe_dsa.layers._apply_index_rope_half_split(
x: torch.Tensor,
freqs_cis: torch.Tensor,
qkv_format: str
) -> torch.Tensor

Apply NON-interleaved (half-split) RoPE to the indexer’s rope slice.

Legacy DSA indexers use half-split RoPE (rotate_half: pair dim j with j + d/2), unlike checkpoints that request interleaved indexer RoPE. freqs_cis is the same complex tensor used by the MLA (exp(i * theta_j * pos) for j in [0, d/2)); we read its real/imag parts as cos/sin so the angles match exactly.

Parameters:

x
torch.Tensor

rope slice, [B, S, H, d] / [B, S, d] (bshd) or [T, H, d] / [T, d] (thd).

freqs_cis
torch.Tensor

complex RoPE table with trailing dim d/2.

qkv_format
str

"bshd" or "thd".

nemo_automodel.components.models.glm_moe_dsa.layers._dsa_kernel_backend(
) -> str

Resolve the DSA kernel path from the configured attention backend.

nemo_automodel.components.models.glm_moe_dsa.layers._rotate_activation(
x: torch.Tensor
) -> torch.Tensor

Apply Hadamard rotation activation.

Reference

https://github.com/deepseek-ai/DeepSeek-V3.2-Exp/blob/main/inference/model.py#L424-L428

Parameters:

x
torch.Tensor

Input tensor (must be bfloat16).

Returns: torch.Tensor

Rotated tensor.

nemo_automodel.components.models.glm_moe_dsa.layers._to_additive_key_mask(
mask: torch.Tensor,
dtype: torch.dtype
) -> torch.Tensor

Convert a {0,1} keep-mask (1=attend, 0=mask) to an ADDITIVE key mask (0 / finfo.min).

Masked positions use finfo.min rather than -inf: F.scaled_dot_product_attention mishandles -inf float masks (its fused kernels corrupt the softmax). HF builds the attention bias with create_causal_mask, which likewise masks padding to finfo.min. The recipe, however, hands the model a 2D &#123;0,1&#125; padding mask; adding it to the scores raw (the previous behaviour) both fails to mask padding (0 -> +0 instead of finfo.min) AND adds +1.0 to every kept key, which is only softmax-invariant in fp32 — in bf16 the +1.0 swamps the (scaled) score differences and collapses attention toward uniform. A mask that is already additive (values <= 0) is returned unchanged.

nemo_automodel.components.models.glm_moe_dsa.layers.absorbed_sparse_query(
q_nope: torch.Tensor,
q_pe: torch.Tensor,
w_kc: torch.Tensor
) -> torch.Tensor

Return cat([q_nope @ w_kc (per head), q_pe], -1) as one contiguous tensor without the concat copy.

Parameters:

q_nope
torch.Tensor

Non-rope query of shape [tokens, heads, qk_nope_head_dim].

q_pe
torch.Tensor

Rotated rope query of shape [tokens, heads, qk_rope_head_dim] in q_nope’s dtype.

w_kc
torch.Tensor

Key up-projection of shape [heads, qk_nope_head_dim, latent] in q_nope’s dtype.

Returns: torch.Tensor

Contiguous tensor of shape [tokens, heads, latent + qk_rope_head_dim] in q_nope’s dtype.

nemo_automodel.components.models.glm_moe_dsa.layers.hadamard_transform(
x: torch.Tensor,
scale: float
) -> torch.Tensor

Fallback hadamard_transform when fast_hadamard_transform is not available.

nemo_automodel.components.models.glm_moe_dsa.layers.hadamard_transform_torch(
u,
scale: float,
normalize = False
)

Multiply H_n @ u where H_n is the Hadamard matrix of dimension n x n. n must be a power of 2. Parameters: u: Tensor of shape (…, n) normalize: if True, divide the result by 2^{m/2} where m = log_2(n). Returns: product: Tensor of shape (…, n)

nemo_automodel.components.models.glm_moe_dsa.layers._FAST_HADAMARD_AVAILABLE = True
nemo_automodel.components.models.glm_moe_dsa.layers.glm_dsa_indexer_replay: RecomputeReplay[Tensor] = RecomputeReplay('GLM DSA frozen indexer selection')