Skip to navigation

nemo_automodel.components.models.common

View as MarkdownOpen in Claude

Common/shared components for model implementations.

Subpackages

Submodules

Package Contents

Classes

NameDescription
BackendConfigBackend configuration for model components.
CudaGraphConfigConfiguration for scoped partial CUDA graphs.
HFCheckpointingMixinMixin providing HF-compatible API using NeMo’s checkpointing infrastructure.
LMHeadnn.Linear vocabulary head that returns logits_dtype logits whatever its weight dtype.
MoKBackendConfigConfiguration for the optional Mixture-of-Kittens MoE backend.
NcclEpConfigConfiguration for the optional NCCL-EP token dispatcher (dispatcher="nccl_ep").

Functions

NameDescription
get_rope_configExtract rope configuration from config.rope_parameters.
initialize_linear_moduleInitialize Linear module with the specified backend.
initialize_rms_norm_moduleInitialize RMSNorm module with the specified backend.
slice_logits_to_keepSelect the positions of hidden states whose logits a forward returns, before the head projects them.

Data

AttentionBackend

HAVE_DEEP_EP

HAVE_TE

API

class nemo_automodel.components.models.common.utils.BackendConfig(
sparse_attn: typing.Literal['generic', 'msa'] = 'generic',
linear: typing.Literal['torch', 'te', 'quack'] = 'te' if HAVE_TE and torch.c...,
rms_norm: typing.Literal['torch', 'torch_fp32', 'te', 'quack'] = 'torch_fp32',
rope: typing.Literal['torch', 'quack', 'triton'] = 'torch',
rope_fusion: bool = HAVE_TE and torch.cuda.is_a...,
experts: typing.Literal['torch', 'te', 'gmm', 'torch_mm', 'torch_mm_mxfp8'] = 'torch_mm' if torch.cuda.is...,
dispatcher: typing.Literal['torch', 'deepep', 'hybridep', 'uccl_ep', 'nccl_ep', 'mok'] = 'deepep' if HAVE_DEEP_EP an...,
te_grouped_tensor: bool = False,
dispatcher_num_sms: int = 20,
dispatcher_share_token_dispatcher: bool = True,
dispatcher_async_dispatch: bool = False,
dispatcher_capacity_factor: float | None = None,
dispatcher_equal_token_counts: bool = False,
dispatcher_recompute_cache: str = 'none',
dispatcher_hybridep_permute_fusion: bool = False,
dispatcher_hybridep_compact_routing: bool = False,
dispatcher_hybridep_num_sms_preprocessing: int | None = None,
dispatcher_hybridep_num_blocks_permute: int | None = None,
dispatcher_hybridep_num_blocks_unpermute: int | None = None,
dispatcher_hybridep_max_tokens_per_rank: int | None = None,
enable_deepep: bool | None = None,
fake_balanced_gate: bool = False,
fake_gate_noise: float = 0.0,
enable_hf_state_dict_adapter: bool = True,
enable_fsdp_optimizations: bool = False,
gate_precision: str | torch.dtype | None = None,
compile_attn: bool = False,
compile_situ: bool = False,
compile_norm: bool = False,
compile_hc: bool = False,
shared_expert_overlap: bool = False,
compile_router_weight: bool = False,
cp_query_layout: typing.Literal['contiguous', 'head_tail'] = 'contiguous',
benchmark_static_routing: bool = False,
)
Dataclass

Backend configuration for model components.

attn
AttentionBackend

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_static_routing
bool = False

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.

compile_attn
bool = False

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.

compile_hc
bool = False

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.

compile_norm
bool = False

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.

compile_router_weight
bool = False

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.

compile_situ
bool = False

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.

cp_query_layout
Literal['contiguous', 'head_tail'] = 'contiguous'

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.

cuda_graph
CudaGraphConfig = field(default_factory=CudaGraphConfig)

Scoped partial CUDA-graph configuration.

dispatcher
Literal['torch', 'deepep', 'hybridep', 'uccl_ep', 'nccl_ep', 'mok']

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.

dispatcher_async_dispatch
bool = False

Whether DeepEP/UCCL-EP dispatch and combine should return asynchronously and allocate their outputs on the communication stream.

dispatcher_capacity_factor
float | None = None

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.

dispatcher_equal_token_counts
bool = False

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.

dispatcher_hybridep_compact_routing
bool = False

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.

dispatcher_hybridep_max_tokens_per_rank
int | None = None

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.

dispatcher_hybridep_num_blocks_permute
int | None = None

Optional number of dispatch permutation blocks. None preserves HybridEP’s default.

dispatcher_hybridep_num_blocks_unpermute
int | None = None

Optional number of combine unpermutation blocks. None preserves HybridEP’s default.

dispatcher_hybridep_num_sms_preprocessing
int | None = None

Optional number of SMs used by HybridEP routing-metadata preprocessing.

dispatcher_hybridep_permute_fusion
bool = False

Fuse HybridEP token permutation into dispatch and unpermutation into combine. Has no effect for other dispatcher backends.

dispatcher_num_sms
int = 20
dispatcher_recompute_cache
str = 'none'

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.

dispatcher_share_token_dispatcher
bool = True

Whether flex token dispatchers share a communication manager instance across MoE layers. NCCL-EP always keeps routing state layer-local.

enable_deepep
bool | None = None

Removed and ignored. Logs a warning if set; configure “dispatcher” and “experts” explicitly instead.

enable_fsdp_optimizations
bool = False

Whether to enable FSDP2 optimizations.

enable_hf_state_dict_adapter
bool = True

Whether to enable HuggingFace state dict adapter.

experts
Literal['torch', 'te', 'gmm', 'torch_mm', 'torch_mm_mxfp8']

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).

fake_balanced_gate
bool = False

If True, replace the learned Gate with FakeBalancedGate that assigns tokens to experts without learned routing weights.

fake_gate_noise
float = 0.0

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.

gate_precision
str | dtype | None = None

Optional dtype override for the gate computation. Accepts torch.dtype or string (e.g., “torch.float32”, “float32”).

linear
Literal['torch', 'te', 'quack']

Linear layer backend (“torch”, “te”, or “quack”).

mok
MoKBackendConfig = field(default_factory=MoKBackendConfig)

Mixture-of-Kittens tuning settings used when dispatcher="mok".

nccl_ep
NcclEpConfig = field(default_factory=NcclEpConfig)

NCCL-EP settings; max_tokens_per_rank is required when selecting “nccl_ep”. NCCL-EP sizes its own kernels and ignores dispatcher_num_sms.

rms_norm
Literal['torch', 'torch_fp32', 'te', 'quack'] = 'torch_fp32'

RMSNorm backend (“torch”, “torch_fp32”, “te”, or “quack”).

rope
Literal['torch', 'quack', 'triton'] = 'torch'

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).

rope_fusion
bool = HAVE_TE and torch.cuda.is_available()

Whether to use fused RoPE (requires TE).

shared_expert_overlap
bool = False

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_attn
Literal['generic', 'msa'] = 'generic'

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.

te_fp8
TEFp8Config | None = None
te_grouped_tensor
bool = False

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.

te_nvfp4
TENvfp4Config | None = None
te_quantization
TEQuantizationConfig | None

The te_fp8 or te_nvfp4 config, whichever is set.

nemo_automodel.components.models.common.utils.BackendConfig.__post_init__() -> None
class nemo_automodel.components.models.common.utils.CudaGraphConfig(
modules: list[typing.Literal['attn', 'te_dpa', 'moe_router', 'moe_preprocess']] = list()
)
Dataclass

Configuration for scoped partial CUDA graphs.

modules
list[Literal['attn', 'te_dpa', 'moe_router', 'moe_preprocess']] = field(default_factory=list)

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.

nemo_automodel.components.models.common.utils.CudaGraphConfig.__post_init__() -> None

Validate the declarative CUDA-graph configuration.

class nemo_automodel.components.models.common.hf_checkpointing_mixin.HFCheckpointingMixin()

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.

nemo_automodel.components.models.common.hf_checkpointing_mixin.HFCheckpointingMixin._get_resized_lm_head(
old_lm_head: torch.nn.Linear,
new_num_tokens: int | None = None,
transposed: bool = False,
mean_resizing: bool = True
) -> torch.nn.Linear

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:

old_lm_head
nn.Linear

The output head, with weight of shape [vocab, hidden].

new_num_tokens
int | NoneDefaults to None

New vocabulary size; None returns the head unchanged.

transposed
boolDefaults to False

Whether the head’s weight is stored as [hidden, vocab].

mean_resizing
boolDefaults to True

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].

nemo_automodel.components.models.common.hf_checkpointing_mixin.HFCheckpointingMixin.save_pretrained(
save_directory: str,
tokenizer: typing.Optional[transformers.tokenization_utils.PreTrainedTokenizerBase] = None,
kwargs = {}
) -> None

Save model in HF-compatible format using Checkpointer infrastructure.

Supports distributed saving, sharding, and async checkpointing.

Parameters:

save_directory
str

Output path

checkpointer
Optional[Checkpointer]Defaults to None

Checkpointer instance. Uses self._checkpointer if not provided.

tokenizer
Optional[PreTrainedTokenizerBase]Defaults to None

Optional tokenizer to save alongside model

**kwargs
Defaults to {}

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.

class nemo_automodel.components.models.common.lm_head.LMHead(
in_features: int,
out_features: int,
bias: bool = False,
logits_dtype: torch.dtype | None = None,
logit_softcapping: float | None = None,
device: torch.device | str | None = None,
dtype: torch.dtype | None = None
)

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.

nemo_automodel.components.models.common.lm_head.LMHead.forward(
input: torch.Tensor
) -> torch.Tensor

Project hidden states with the head’s own weight.

Parameters:

input
torch.Tensor

Tensor of shape […, hidden].

Returns: torch.Tensor

Logits of shape […, vocab], as project returns them.

nemo_automodel.components.models.common.lm_head.LMHead.from_linear(
head: torch.nn.Linear,
logits_dtype: torch.dtype | None
) -> typing.Self
classmethod

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:

head
nn.Linear

Plain nn.Linear whose weight is a Tensor of shape [vocab, hidden] and whose bias is a Tensor of shape [vocab] or None.

logits_dtype
torch.dtype | 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: If head is not a plain nn.Linear, so it has its own projection.
nemo_automodel.components.models.common.lm_head.LMHead.linear(
input: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor | None = None,
logits_dtype: torch.dtype | None
) -> torch.Tensor
staticmethod

Project hidden states with a supplied weight and bias, without a softcap.

Parameters:

input
torch.Tensor

Tensor of shape […, hidden], cast to the weight’s dtype. With logits_dtype set, a DTensor sharded on a leading dimension is replicated first.

weight
torch.Tensor

Tensor of shape [vocab, hidden]; a column-parallel DTensor uses Shard(0), with the input replicated on the same mesh.

bias
torch.Tensor | NoneDefaults to None

Optional tensor of shape [vocab].

logits_dtype
torch.dtype | None

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.

nemo_automodel.components.models.common.lm_head.LMHead.project(
input: torch.Tensor,
weight: torch.Tensor
) -> torch.Tensor

Project hidden states with a supplied vocabulary weight.

Parameters:

input
torch.Tensor

Tensor of shape […, hidden], with arbitrary leading dimensions. It is cast to the supplied weight’s dtype before projection.

weight
torch.Tensor

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.

class nemo_automodel.components.models.common.utils.MoKBackendConfig(
precision: typing.Literal['bf16', 'mxfp8'] = 'bf16',
fwd_num_comm_sms: int = 40,
bwd_num_comm_sms: int = 28,
minibatch_size: int = 4096,
macrobatch_size: int = 131072,
schedule_capacity_multiplier: float = 0.5,
all_gather_top_experts_chunk_bytes: int = 2048
)
Dataclass

Configuration for the optional Mixture-of-Kittens MoE backend.

all_gather_top_experts_chunk_bytes
int = 2048

Routing all-gather chunk size in bytes.

bwd_num_comm_sms
int = 28

Communication SMs reserved during the backward megakernel.

fwd_num_comm_sms
int = 40

Communication SMs reserved during the forward megakernel.

macrobatch_size
int = 131072

Routed-token ring-buffer capacity and a multiple of minibatch_size.

minibatch_size
int = 4096

Routed-token overlap granularity, divisible by 256.

precision
Literal['bf16', 'mxfp8'] = 'bf16'

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.

schedule_capacity_multiplier
float = 0.5

Worst-case fraction of routes sent to one EP rank.

nemo_automodel.components.models.common.utils.MoKBackendConfig.__post_init__() -> None

Validate settings that do not depend on a CUDA device or EP group.

nemo_automodel.components.models.common.utils.MoKBackendConfig.build() -> nemo_automodel.components.models.common.utils._MoKFunctionalConfig

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.
class nemo_automodel.components.moe.config.NcclEpConfig(
max_tokens_per_rank: int | None = None
)
Dataclass

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.

max_tokens_per_rank
int | None = None

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.

nemo_automodel.components.moe.config.NcclEpConfig.__post_init__() -> None

Validate settings that do not depend on a CUDA device or EP group.

nemo_automodel.components.models.common.utils.get_rope_config(
config
) -> tuple[float, dict, float]

Extract rope configuration from config.rope_parameters.

Parameters:

config

A HuggingFace model config object.

Returns: tuple[float, dict, float]

Tuple of (rope_theta, rope_parameters, partial_rotary_factor).

nemo_automodel.components.models.common.utils.initialize_linear_module(
linear_impl: str,
in_features: int,
out_features: int,
bias: bool = False,
device: torch.device | str | None = None,
dtype: torch.dtype = torch.bfloat16
) -> torch.nn.Module

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:

linear_impl
str

Backend implementation (“te”, “torch”, or “quack”)

in_features
int

Input features

out_features
int

Output features

bias
boolDefaults to False

Whether to use bias

device
torch.device | str | NoneDefaults to None

Device to create module on (None uses PyTorch default, typically CPU)

dtype
torch.dtypeDefaults to torch.bfloat16

Parameter dtype

Returns: nn.Module

Linear module

nemo_automodel.components.models.common.utils.initialize_rms_norm_module(
rms_norm_impl: str,
dim: int,
eps: float = 1e-05,
device: torch.device | str | None = None,
dtype: torch.dtype = torch.bfloat16
) -> torch.nn.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:

rms_norm_impl
str

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
dim
int

Normalized dimension

eps
floatDefaults to 1e-05

Epsilon for numerical stability

device
torch.device | str | NoneDefaults to None

Device to create module on (None uses PyTorch default, typically CPU)

dtype
torch.dtypeDefaults to torch.bfloat16

Parameter dtype

Returns: nn.Module

RMSNorm module

nemo_automodel.components.models.common.lm_head.slice_logits_to_keep(
hidden_states: torch.Tensor,
logits_to_keep: int | torch.Tensor
) -> torch.Tensor

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:

hidden_states
torch.Tensor

Tensor of shape [batch, sequence, hidden], or packed (THD) [tokens, hidden].

logits_to_keep
int | torch.Tensor

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

nemo_automodel.components.models.common.utils.AttentionBackend = Literal['torch', 'te', 'sdpa', 'flex', 'eager', 'tilelang', 'cudnn', 'fa4', 'mag...
nemo_automodel.components.models.common.utils.HAVE_DEEP_EP = importlib.util.find_spec('deep_ep') is not None
nemo_automodel.components.models.common.utils.HAVE_TE = importlib.util.find_spec('transformer_engine') is not None