Skip to navigation

nemo_automodel.components.models.ergo.layers

View as MarkdownOpen in Claude

Differentiable Ergo layers built on AutoModel attention and expert engines.

The mathematical contract was inspected in the supplied Ergo SGLang release, revision bd598c4f927288ea5c2bb9e84359f51d9c0b5aaf, python/sglang/srt/models/ergo.py (Apache-2.0). This implementation is independent; inference-only coefficient caching and kernels are not reused. Numerical operation order is also validated against the release’s python/sglang/test/ergo_naive_reference.py at that revision.

Module Contents

Classes

NameDescription
ErgoAttentionGQA with Q/K norm, local interleaved RoPE and every-fourth global NoPE.
ErgoBlockOne FP32 residual block with explicitly rounded branch computation.
ErgoComputeRMSNormQ/K and shared-expert normalization in the incoming compute dtype.
ErgoDenseFFNNon-gated ReLU-squared FFN using the selected linear backend.
ErgoExpertOutputNormPer-expert FP32 scale, sharded on the same expert axis as the MLP.
ErgoMoECommon routed experts plus independently normalized shared ReLU² FFN.
ErgoRMSNormLearned FP32 RMSNorm; callers explicitly own any branch-output cast.
ErgoResidualLearned variance-preserving residual blend with stable live gradients.
ErgoTokenEmbeddingFP32 token table [vocab, hidden].

Functions

NameDescription
_compiled_expert_normCache pure compiled math, without retaining parameters or activations.
_expert_norm_coreNormalize [routes, hidden] with an FP32 [hidden] scale and retain input dtype.

Data

FP32_OWNER_MARKER

FP32_OWNER_MODULE_NAMES

API

class nemo_automodel.components.models.ergo.layers.ErgoAttention(
layer_id: int,
dtype: torch.dtype,
)

Bases: Module

GQA with Q/K norm, local interleaved RoPE and every-fourth global NoPE.

cp_mesh
DeviceMesh | None = None
is_local
k_norm
q_norm
rotary_frequencies
scaling
= config.head_dim ** -0.5
widths
window_size
= (left_window, 0) if self.is_local else (-1, 0)
wo
wqkv
nemo_automodel.components.models.ergo.layers.ErgoAttention._rotate(
x: torch.Tensor,
positions: torch.Tensor
) -> torch.Tensor

Rotate adjacent pairs using the source’s CPU-rounded frequency table.

Parameters:

x
torch.Tensor

Queries or keys [batch, sequence, heads, channels] or [tokens, heads, channels], on the same device as positions.

positions
torch.Tensor

Integer IDs [batch, sequence] or [tokens].

Returns: torch.Tensor

Rotated queries or keys with the input shape, dtype and device.

nemo_automodel.components.models.ergo.layers.ErgoAttention.forward(
x: torch.Tensor,
positions: torch.Tensor,
attention_mask: torch.Tensor | None = None,
attn_kwargs: typing.Any = {}
) -> torch.Tensor

Attend local queries to global keys, preserving document boundaries.

Parameters:

x
torch.Tensor

Branch states [batch, local_sequence, hidden], or native THD [tokens, hidden]. SDPA CP shards contiguous sequence intervals.

positions
torch.Tensor

RoPE positions matching the local token axes.

attention_mask
torch.Tensor | NoneDefaults to None

Document IDs [batch, local_sequence], zero for padding. Without CP, also accepts a boolean allow-mask [batch, 1, sequence, sequence].

**attn_kwargs
AnyDefaults to {}

Backend-specific packed attention metadata.

Returns: torch.Tensor

Attention output with x’s shape and dtype. Differentiable CP key

nemo_automodel.components.models.ergo.layers.ErgoAttention.setup_cp_attention(
cp_mesh: torch.distributed.device_mesh.DeviceMesh
) -> None

Bind a stage-local CP group through the shared MoE attention contract.

class nemo_automodel.components.models.ergo.layers.ErgoBlock(
layer_id: int,
dtype: torch.dtype,
)

Bases: Module

One FP32 residual block with explicitly rounded branch computation.

_compile_expert_norm
attention
attention_norm
feed_forward
ffn_norm
layer_type
str

Select window-compatible TE transport in the shared MoE parallelizer.

mlp
ErgoDenseFFN | ErgoMoE

Expose the checkpoint-named FFN to shared EP/FSDP discovery.

post_attention_norm
post_attention_residual
= ErgoResidual(config.hidden_size)
post_ffn_norm
post_ffn_residual
= ErgoResidual(config.hidden_size)
self_attn
ErgoAttention

Expose the checkpoint-named attention to shared CP discovery.

nemo_automodel.components.models.ergo.layers.ErgoBlock.forward(
residual: torch.Tensor,
positions: torch.Tensor,
attention_mask: torch.Tensor | None = None,
padding_mask: torch.Tensor | None = None,
attn_kwargs: typing.Any = {}
) -> torch.Tensor

Return FP32 residual states with unchanged token shape and ownership.

Parameters:

residual
torch.Tensor

FP32 residual states [batch, sequence, hidden] (the CP-local sequence under context parallelism), or [tokens, hidden] for native THD inputs.

positions
torch.Tensor

Integer RoPE positions with the leading shape of residual.

attention_mask
torch.Tensor | NoneDefaults to None

Optional document IDs [batch, sequence], zero for padding, or a boolean allow-mask [batch, 1, sequence, sequence]; see ErgoAttention.forward.

padding_mask
torch.Tensor | NoneDefaults to None

Optional boolean padding flags with the leading shape of residual.

**attn_kwargs
AnyDefaults to {}

Backend-specific packed attention metadata, passed to the attention.

Returns: torch.Tensor

FP32 residual states with the shape of residual.

nemo_automodel.components.models.ergo.layers.ErgoBlock.nemo_checkpoint_context_fn(
context_fn: collections.abc.Callable[[], tuple[contextlib.AbstractContextManager, contextlib.AbstractContextManager]] | None
) -> collections.abc.Callable[[], tuple[contextlib.AbstractContextManager, contextlib.AbstractContextManager]] | None

Preserve the caller’s compilation budget on checkpoint worker threads.

Parameters:

context_fn
Callable[[], tuple[AbstractContextManager, AbstractContextManager]] | None

Existing forward/recompute context factory, if present.

Returns: Callable[[], tuple[AbstractContextManager, AbstractContextManager]] | None

Composed contexts retaining the caller’s Dynamo limits, following

class nemo_automodel.components.models.ergo.layers.ErgoComputeRMSNorm()

Bases: ErgoRMSNorm

Q/K and shared-expert normalization in the incoming compute dtype.

nemo_automodel.components.models.ergo.layers.ErgoComputeRMSNorm.forward(
x: torch.Tensor
) -> torch.Tensor

Normalize expert outputs with FP32 weights inside weighted RMSNorm.

Parameters:

x
torch.Tensor

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

Returns: torch.Tensor

Tensor with the same shape, dtype and device as x.

class nemo_automodel.components.models.ergo.layers.ErgoDenseFFN(
hidden_size: int,
inner_size: int,
dtype: torch.dtype
)

Bases: Module

Non-gated ReLU-squared FFN using the selected linear backend.

down
up
nemo_automodel.components.models.ergo.layers.ErgoDenseFFN.forward(
x: torch.Tensor,
padding_mask: torch.Tensor | None = None
) -> torch.Tensor

Return […, hidden] after BF16/FP32 projection and ReLU² rounding.

nemo_automodel.components.models.ergo.layers.ErgoDenseFFN.set_cp_mesh(
cp_mesh: torch.distributed.device_mesh.DeviceMesh
) -> None

Accept the stage’s context-parallel mesh; the dense FFN has no router that needs it.

class nemo_automodel.components.models.ergo.layers.ErgoExpertOutputNorm(
num_experts: int,
hidden_size: int,
eps: float,
compile_norm: bool = False
)

Bases: Module

Per-expert FP32 scale, sharded on the same expert axis as the MLP.

The grouped GEMM expert paths call it through per_expert_output with the row counts of the expert segments, which say which expert produced each row.

_compiled_core
= _compiled_expert_norm() if compile_norm else None
scale
nemo_automodel.components.models.ergo.layers.ErgoExpertOutputNorm._normalize(
values: torch.Tensor,
scale: torch.Tensor
) -> torch.Tensor

Keep compiled normalization scratch operations outside SAC caching.

Expert slicing and distributed operations stay outside this pure tensor core. As in Muse Spark, autograd and enclosing checkpoint recomputation remain active while selective-checkpoint dispatch accounting is suspended.

Parameters:

values
torch.Tensor

Rows of one expert, shape [rows, hidden], in the compute dtype.

scale
torch.Tensor

That expert’s FP32 scale, shape [hidden].

Returns: torch.Tensor

Normalized rows of shape [rows, hidden] in the dtype of values.

nemo_automodel.components.models.ergo.layers.ErgoExpertOutputNorm.forward(
values: torch.Tensor,
tokens_per_expert: torch.Tensor | None = None
) -> torch.Tensor

Apply each expert’s weighted RMSNorm in the incoming compute dtype.

Parameters:

values
torch.Tensor

Tensor of shape [routes, hidden], grouped in local expert order.

tokens_per_expert
torch.Tensor | NoneDefaults to None

Integer tensor of shape [local_experts], with segment lengths.

Returns: torch.Tensor

Tensor of shape [routes, hidden], preserving input dtype and device.

Raises:

  • ValueError: If the expert path did not pass tokens_per_expert.

Bases: MoE

Common routed experts plus independently normalized shared ReLU² FFN.

Routing is the shared Gate in FP32: experts are chosen by the corrected sigmoid scores and weighted by the uncorrected scores, normalised and scaled (score_func="sigmoid_with_bias" with norm_topk_prob).

_expert_norm_attached
bool = True
shared
shared_norm
nemo_automodel.components.models.ergo.layers.ErgoMoE.__setattr__(
name: str,
value: torch.Tensor | torch.nn.Module | None
) -> None

Keep the output norm with the experts when LoRA replaces the expert module, and freeze it.

nemo_automodel.components.models.ergo.layers.ErgoMoE.forward(
x: torch.Tensor,
padding_mask: torch.Tensor | None = None
) -> torch.Tensor

Normalize routes before weighted reduction; add normalized shared rows.

Parameters:

x
torch.Tensor

Branch input of shape […, hidden], e.g. [batch, sequence, hidden], in the compute dtype.

padding_mask
torch.Tensor | NoneDefaults to None

Optional boolean padding flags with the leading shape of x; padded tokens are not routed.

Returns: torch.Tensor

Tensor with the shape and dtype of x: the routed experts’ weighted sum plus the normalized shared

nemo_automodel.components.models.ergo.layers.ErgoMoE.set_cp_mesh(
cp_mesh: torch.distributed.device_mesh.DeviceMesh
) -> None

Bind the stage’s context-parallel mesh, which the router passes to the shared gate.

class nemo_automodel.components.models.ergo.layers.ErgoRMSNorm(
hidden_size: int,
eps: float
)

Bases: Module

Learned FP32 RMSNorm; callers explicitly own any branch-output cast.

weight
nemo_automodel.components.models.ergo.layers.ErgoRMSNorm.forward(
x: torch.Tensor
) -> torch.Tensor

Normalize […, hidden] in FP32 and return FP32 on the input device.

class nemo_automodel.components.models.ergo.layers.ErgoResidual(
hidden_size: int
)

Bases: Module

Learned variance-preserving residual blend with stable live gradients.

scale
nemo_automodel.components.models.ergo.layers.ErgoResidual.forward(
branch: torch.Tensor,
residual: torch.Tensor
) -> torch.Tensor

Blend matching […, hidden] branch/residual tensors in FP32.

Match the source operation order while its exponential is normal. Clamp unselected branches and factor the extreme positive tail to avoid sqrt(0) derivatives without detaching learned coefficients.

Parameters:

branch
torch.Tensor

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

residual
torch.Tensor

Tensor with the same shape as branch.

Returns: torch.Tensor

FP32 blended tensor of shape […, hidden].

class nemo_automodel.components.models.ergo.layers.ErgoTokenEmbedding(
vocab_size: int,
hidden_size: int
)

Bases: Embedding

FP32 token table [vocab, hidden].

The shared FSDP flows shard the input embedding as a unit of its own and hand over the bare module, so the table names itself an FP32 owner with a parameter-free child. The child adds no state-dict entry.

nemo_automodel.components.models.ergo.layers._compiled_expert_norm() -> collections.abc.Callable[[torch.Tensor, torch.Tensor, float], torch.Tensor]

Cache pure compiled math, without retaining parameters or activations.

nemo_automodel.components.models.ergo.layers._expert_norm_core(
values: torch.Tensor,
scale: torch.Tensor,
eps: float
) -> torch.Tensor

Normalize [routes, hidden] with an FP32 [hidden] scale and retain input dtype.

nemo_automodel.components.models.ergo.layers.FP32_OWNER_MARKER = 'fp32_owner'
nemo_automodel.components.models.ergo.layers.FP32_OWNER_MODULE_NAMES: frozenset[str] = frozenset({'embed_tokens', 'norm', 'attention_norm', 'q_norm', 'k_norm', 'post_a...