nemo_automodel.components.models.common
nemo_automodel.components.models.common
Common/shared components for model implementations.
Subpackages
Submodules
nemo_automodel.components.models.common.bidirectionalnemo_automodel.components.models.common.cudnn_sparse_attentionnemo_automodel.components.models.common.gated_delta_net_fp32nemo_automodel.components.models.common.hf_checkpointing_mixinnemo_automodel.components.models.common.inbatch_neg_utilsnemo_automodel.components.models.common.lm_headnemo_automodel.components.models.common.packed_seqnemo_automodel.components.models.common.packingnemo_automodel.components.models.common.rope_tritonnemo_automodel.components.models.common.sinkhornnemo_automodel.components.models.common.tie_word_embeddingsnemo_automodel.components.models.common.utils
Package Contents
Classes
Functions
Data
API
Backend configuration for model components.
Attention backend (“torch”, “te”, “sdpa”, “flex”, “eager”, “tilelang”, “cudnn”, “fa4”, or “magi”). “fa4” selects native FlashAttention-4 (CuTe) and requires an INSTALL_FA4=true image. HF-dispatched models use “flash_attention_4”. A rank-2 binary padding mask is converted to varlen metadata, while dense/block masks and indexed document masks without explicit packed metadata are rejected. Inputs must use BSHD layout; pre-packed THD is unsupported. Packed Qwen3Next and DeepSeek V3.2 sparse attention do not support FA4. For DeepSeek V4, “tilelang” enables the TileLang sparse attention, indexer, and Sinkhorn kernels together; “cudnn” keeps the TileLang indexer/Sinkhorn and selects FlashMLA forward with cuDNN backward. For GLM DSA, “tilelang” and “cudnn” select their respective packed sparse-attention kernels. For Qwen3.8-Flash-Next, “flex” selects FlexAttention sparse GQA on CUDA BF16, “fa4” selects FlashAttention 4 sparse GQA (SM90 or SM100-family BF16), and “cudnn” selects cuDNN Frontend indexed QSA on SM100/SM103 with compression ratio four and CP=1, preserving the existing indexer. CPU execution retains the PyTorch numerical oracle. For Kimi K3, “fa4” runs MLA through FlashAttention 4 (varlen, with and without context parallelism). “fa4” requires the optional flash_attn.cute package; models without an FA4 path reject it.
Benchmark-only. Requires fake_balanced_gate=True
with fake_gate_noise=0.0, where routing metadata (tokens per expert,
permuted token counts) is identical for every microbatch. Skips the
per-microbatch device-to-host reads of that metadata (.tolist() /
count_nonzero / dispatcher size checks) by caching the first
microbatch’s values, removing recurring host-sync stalls on the hot
path. Never enable with a learned gate: cached metadata would go
stale and silently corrupt expert dispatch.
torch.compile(fullgraph) the attention module’s forward — both the DeepSeek-V3 MLA and standard GQA attention (e.g. Qwen3-MoE) honor it. Requires attn=“sdpa”, linear=“torch”, rms_norm=“torch”, rope_fusion=False. Qwen3-MoE also supports attn=“fa4”: only the padded projections, Q/K normalization and RoPE are compiled; packed varlen attention runs between those fixed-shape graphs with its document metadata preserved.
torch.compile the mHC (hyper-connection) cores of models that opt in
(currently DeepSeek V4 / V4.1 and GLM-5.3-Flash): coefficient projection, stream collapse and stream
expand, fusing their elementwise chains with static shapes (a new sequence length compiles them again; past
dynamo’s recompile limit a core runs eager). Same lazy once-per-process pattern as
compile_situ; numerics are allclose to eager but not bitwise-identical.
torch.compile the fp32 RMSNorm chain of models that opt in
(currently Kimi K3, DeepSeek V4.1 and GLM-5.3-Flash decoder/final norms),
fusing cast/pow/mean/rsqrt/mul into one kernel.
Same lazy once-per-process pattern as compile_situ; numerics are
allclose to eager but not bitwise-identical.
torch.compile the fp32 router-weight multiply applied to
expert outputs (GroupedExperts / GroupedExpertsDeepEP / GroupedExpertsTE, all MoE models),
so each pass is one fused kernel instead of the eager per-chunk cast/multiply/
cast/slice-assign loop. Same lazy once-per-process pattern as compile_situ;
numerics are allclose to eager but not bitwise-identical.
torch.compile the SiTU expert activation of models that opt in
(currently Kimi K3): the weighted-SiTU forward and backward run as one fused
whole-tensor kernel each (low-precision in/out, fp32 math inside, no chunk loop),
the dense / shared-expert SituAndMul uses a compiled core, and the attn-res
mixing chain is compiled as well. Compiled numerics are allclose to eager but
not bitwise-identical.
Which global query positions each context-parallel rank owns for models
whose attention gathers K/V inside the model (GLM-5.x DSA). "contiguous" (default):
rank r keeps tokens [r * T/cp, (r + 1) * T/cp). "head_tail": the sequence is cut
into 2 * cp chunks and rank r keeps chunks r and 2 * cp - 1 - r. This balances
causal indexer work for a single unpadded document. With packed documents or padding,
the split depends on the document boundaries. The padded length must be divisible by 2 * cp.
Scoped partial CUDA-graph configuration.
MoE token dispatcher. “torch” uses DTensor all-gather/reduce-scatter, “deepep” uses DeepEP, “hybridep” uses HybridEP, “uccl_ep” uses UCCL-EP, “nccl_ep” uses Transformer Engine NCCL-EP, and “mok” uses Mixture-of-Kittens’ fused communication and SwiGLU megakernel.
Whether DeepEP/UCCL-EP dispatch and combine should return asynchronously and allocate their outputs on the communication stream.
HybridEP only, dynamic routing. Run HybridEP dispatch in its
non-blocking mode with output buffers sized to the first microbatch’s permuted row
count times this factor (EP-group max, 4-token aligned) instead of letting every
dispatch drain the compute stream to read the exact count. Overflow trips a
device-side assert. None (default) keeps the blocking reference path. The capacity is
calibrated once per communication manager from its first real batch and kept for the
run; with dispatcher_share_token_dispatcher=True (default) that is one calibration,
taken on the first local MoE layer’s first microbatch, for every layer, so choose a factor
that covers the largest routing skew expected across layers and batches. Not supported
for experts with expert_bias (GroupedExpertsDeepEP rejects the combination) or by
GroupedExpertsTE, which HybridEP uses for every experts value other than
torch_mm, gmm and torch_mm_mxfp8.
HybridEP only. Declare that every EP rank dispatches the same row count, so the per-dispatch EP-group max all-reduce (and its host sync) that derives the pad size is skipped and the count is only aligned. Default False; keep it False for variable-length or in-batch-packed inputs.
Send compact top-k expert indices to HybridEP instead of the dense Boolean routing map. This can reduce metadata traffic, but remains opt-in because its latency depends on topology and model shape.
HybridEP only. Allocate the process-global
HybridEP buffer for this many tokens per rank on the first dispatch instead of the
first micro-batch’s token count. HybridEP grows the buffer when a later micro-batch
is larger; in multi-node mode that reallocation re-creates the RDMA queue pairs, is
slow and has been seen to abort (Failed to create ... QP). Set it to the largest
micro-batch token count (e.g. the dynamic-batching token cap). The buffer is resident
GPU memory for the whole run, so do not pad it. None keeps the lazy behaviour.
Optional number of dispatch permutation
blocks. None preserves HybridEP’s default.
Optional number of combine
unpermutation blocks. None preserves HybridEP’s default.
Optional number of SMs used by HybridEP routing-metadata preprocessing.
Fuse HybridEP token permutation into dispatch and unpermutation into combine. Has no effect for other dispatcher backends.
HybridEP only; effective under full-block activation checkpointing (not
installed for checkpoint_moe_only regions, which end at the combine the recompute never re-runs).
"none" (default) recomputes the whole MoE layer in the backward. "combine" keeps
a clone of every MoE layer’s combine output ([tokens, hidden] in the activation dtype)
from the checkpoint forward and returns it in the recompute instead of re-running the
unpermute, the EP-group barrier and the combine all-to-all. "moe_tail" additionally
builds the down projection’s autograd node in the recompute without running its GEMM
(its output only fed the skipped combine; torch_mm experts without expert bias and with
the router weight applied inside the activation) (a post-expert callback that reads the output keeps the GEMM). Costs one [tokens, hidden] activation
per MoE layer per in-flight microbatch; gradients are unchanged.
Whether flex token dispatchers share a communication manager instance across MoE layers. NCCL-EP always keeps routing state layer-local.
Removed and ignored. Logs a warning if set; configure “dispatcher” and “experts” explicitly instead.
Whether to enable FSDP2 optimizations.
Whether to enable HuggingFace state dict adapter.
MoE expert GEMM backend. “torch” uses per-expert loop, “te” uses TE GroupedLinear, “torch_mm” uses torch._grouped_mm, “gmm” is a deprecated compatibility alias for “torch_mm”, and “torch_mm_mxfp8” uses torch._grouped_mm dispatch but routes the expert grouped GEMMs through torchao’s MXFP8 scaled grouped GEMM (training-only; GB200/sm_100+ with torchao installed, else falls back to torch._grouped_mm at runtime).
If True, replace the learned Gate with FakeBalancedGate that assigns tokens to experts without learned routing weights.
Noise level [0, 1] for FakeBalancedGate. When > 0, uses biased topk selection seeded from the input content so routing varies dynamically across training steps (like real Gate) while remaining deterministic for activation checkpointing recompute (same input = same routing). Only used when fake_balanced_gate=True.
Optional dtype override for the gate computation. Accepts torch.dtype or string (e.g., “torch.float32”, “float32”).
Linear layer backend (“torch”, “te”, or “quack”).
Mixture-of-Kittens tuning settings used when dispatcher="mok".
NCCL-EP settings; max_tokens_per_rank is required when selecting
“nccl_ep”. NCCL-EP sizes its own kernels and ignores dispatcher_num_sms.
RMSNorm backend (“torch”, “torch_fp32”, “te”, or “quack”).
Rotary embedding backend (“torch”, “quack” or “triton”). QuACK is currently integrated for Llama-family rotary embeddings; “triton” selects the fused Triton rotation of DeepSeek V4 / V4.1 (other models keep the torch path).
Whether to use fused RoPE (requires TE).
run the shared experts of MoE models (the shared MoE class, e.g. DeepSeek V4 / V4.1, and Kimi K3)
on a side CUDA stream so their GEMMs overlap the expert-parallel dispatch / combine
communication of the routed path; numerics unchanged. Default False.
Sparse-attention backend. “generic” preserves each model’s
existing sparse mask plus attn path; “msa” selects the optional
SM100 MSA kernels a model provides for its sparse layers only.
Prefer TE 2.19 native grouped-tensor GEMMs for experts="te".
Requires dispatcher="deepep", "hybridep", or "uccl_ep".
Device and precision support follows TE’s GroupedLinear contract.
Parameters and checkpoints retain their existing layouts.
The te_fp8 or te_nvfp4 config, whichever is set.
Configuration for scoped partial CUDA graphs.
Per-layer modules to capture with Transformer Engine, following
Megatron Core’s module names. AutoModel supports whole attn,
moe_router, and moe_preprocess scopes, plus the
AutoModel-specific narrow te_dpa scope. An empty list disables
CUDA graphs.
Validate the declarative CUDA-graph configuration.
Mixin providing HF-compatible API using NeMo’s checkpointing infrastructure.
Provides save_pretrained() and from_pretrained() methods that use Checkpointer for unified distributed/async support with HF format conversion.
Key design: We do NOT override state_dict() or load_state_dict() because PyTorch’s DCP expects these to behave like standard nn.Module methods.
For PreTrainedModel subclasses:
- super().from_pretrained() handles: downloads, quantization config, meta device init
- Checkpointer.load_base_model() handles: actual weight loading with format conversion
For nn.Module subclasses (no parent from_pretrained):
- Falls back to manual config loading + Checkpointer
For PreTrainedModel subclasses, a vocabulary resize keeps the model’s LMHead.
Resize the output head as Transformers does, keeping an LMHead and its settings.
Transformers builds a plain nn.Linear for the resized vocabulary. An LMHead takes that module’s
resized parameters instead, so its class, logits_dtype and softcap survive the resize.
Parameters:
The output head, with weight of shape [vocab, hidden].
New vocabulary size; None returns the head unchanged.
Whether the head’s weight is stored as [hidden, vocab].
Initialize added rows from the mean and covariance of the existing rows.
Returns: nn.Linear
The resized head, with weight of shape [new_num_tokens, hidden].
Save model in HF-compatible format using Checkpointer infrastructure.
Supports distributed saving, sharding, and async checkpointing.
Parameters:
Output path
Checkpointer instance. Uses self._checkpointer if not provided.
Optional tokenizer to save alongside model
Additional arguments, including peft_config and
is_final_checkpoint. Direct callers that do not have recipe
step-scheduler context default is_final_checkpoint to
False.
Bases: Linear
nn.Linear vocabulary head that returns logits_dtype logits whatever its weight dtype.
With logits_dtype set, the GEMM reads the input in the weight’s dtype, accumulates in FP32 and
writes FP32 logits (vLLM’s head_dtype=float32), unaffected by autocast, then casts them; the
backward casts the gradient to the weight’s dtype. Chunked losses, which gather the weight themselves, call
project, so subclasses that change the logits override it.
Repo models take logits_dtype as a constructor argument and build their head with it; their forwards pick
positions with slice_logits_to_keep before calling the head.
Project hidden states with the head’s own weight.
Parameters:
Tensor of shape […, hidden].
Returns: torch.Tensor
Logits of shape […, vocab], as project returns them.
Wrap the plain linear head a Hugging Face parent class built, sharing its weight and bias.
Ties, optimizer identity and checkpoint keys are unchanged.
Parameters:
Plain nn.Linear whose weight is a Tensor of shape [vocab, hidden] and whose bias is a Tensor
of shape [vocab] or None.
Dtype of the logits; None keeps the weight’s dtype, which autocast may lower.
Returns: Self
Head that shares head’s weight and bias Parameters without copying, in head’s training mode.
Raises:
ValueError: Ifheadis not a plainnn.Linear, so it has its own projection.
Project hidden states with a supplied weight and bias, without a softcap.
Parameters:
Tensor of shape […, hidden], cast to the weight’s dtype. With logits_dtype set, a DTensor
sharded on a leading dimension is replicated first.
Tensor of shape [vocab, hidden]; a column-parallel DTensor uses Shard(0), with the input replicated on the same mesh.
Optional tensor of shape [vocab].
Dtype of the logits. None runs a plain linear in the weight’s dtype that autocast may lower; otherwise the GEMM accumulates and writes FP32 logits, which are cast to this dtype.
Returns: torch.Tensor
Logits of shape […, vocab], sharded on the vocabulary axis for a column-parallel weight.
Project hidden states with a supplied vocabulary weight.
Parameters:
Tensor of shape […, hidden], with arbitrary leading dimensions. It is cast to the supplied weight’s dtype before projection.
Tensor of shape [vocab, hidden], on the input’s device. Chunked losses supply their gathered weight here. For column-parallel DTensors these are global shapes: the weight uses Shard(0), and the input is replicated on the same mesh.
Returns: torch.Tensor
Logits of shape […, vocab], with leading axes unchanged and the configured softcap applied.
Configuration for the optional Mixture-of-Kittens MoE backend.
Routing all-gather chunk size in bytes.
Communication SMs reserved during the backward megakernel.
Communication SMs reserved during the forward megakernel.
Routed-token ring-buffer capacity and a multiple of
minibatch_size.
Routed-token overlap granularity, divisible by 256.
Routed-expert compute precision. "bf16" passes the
materialized BF16 weights directly to MoK; "mxfp8" quantizes
them with MoK’s E4M3 data and E8M0 block-scale format.
Worst-case fraction of routes sent to one EP rank.
Validate settings that do not depend on a CUDA device or EP group.
Build the optional MoK runtime configuration.
Returns: _MoKFunctionalConfig
A mok.functional.MoKConfig with these declarative settings.
Raises:
UnavailableError: If Mixture-of-Kittens is not installed.
Configuration for the optional NCCL-EP token dispatcher (dispatcher="nccl_ep").
Every EP rank and every NCCL-EP layer in a process must use the same settings.
NCCL-EP sizes its dispatch and combine kernels itself; its NCCL_EP_COMM_SMS
environment variable tunes that budget.
Upper bound on tokens entering one MoE layer per microbatch on one rank, including masked tokens. Required when selecting NCCL-EP. The transport rounds it up to a multiple of 64; inputs may be shorter. Receive buffers remain dropless and are sized per dispatch.
Validate settings that do not depend on a CUDA device or EP group.
Extract rope configuration from config.rope_parameters.
Parameters:
A HuggingFace model config object.
Returns: tuple[float, dict, float]
Tuple of (rope_theta, rope_parameters, partial_rotary_factor).
Initialize Linear module with the specified backend.
For TE backend, creates TE module directly on specified device. Call reset_parameters() to materialize weights if created on meta device.
Parameters:
Backend implementation (“te”, “torch”, or “quack”)
Input features
Output features
Whether to use bias
Device to create module on (None uses PyTorch default, typically CPU)
Parameter dtype
Returns: nn.Module
Linear module
Initialize RMSNorm module with the specified backend.
For TE backend, creates TE module directly on specified device. Call reset_parameters() to materialize weights if created on meta device.
Parameters:
Backend implementation (“te”, “torch”, “torch_fp32”, or “quack”)
- “te”: Transformer Engine fused RMSNorm kernel
- “torch”: PyTorch native nn.RMSNorm (computes in input dtype)
- “torch_fp32”: torch.compiled fp32 RMSNorm for training stability
- “quack”: QuACK CuTe DSL RMSNorm kernel
Normalized dimension
Epsilon for numerical stability
Device to create module on (None uses PyTorch default, typically CPU)
Parameter dtype
Returns: nn.Module
RMSNorm module
Select the positions of hidden states whose logits a forward returns, before the head projects them.
Hugging Face’s slice_logits_to_keep (newer than the pinned transformers), for an int or a 1D index tensor.
Parameters:
Tensor of shape [batch, sequence, hidden], or packed (THD) [tokens, hidden].
0 keeps every position and returns hidden_states itself, since a full
slice(0, None) of a DTensor has raised on aten.alias under sequence parallelism. A positive int
keeps the last N positions; an integer tensor of shape [kept] keeps those positions.
Returns: torch.Tensor
Tensor of shape [batch, kept, hidden], or [kept, hidden] for packed input: a view of hidden_states for