> This page is for version 0.7.0 · 26.10.
> For other versions, use one of these documentation indexes:
> - Nightly (default): https://docs.nvidia.com/nemo/automodel/nightly/llms.txt
> - Latest: https://docs.nvidia.com/nemo/automodel/latest/llms.txt
> - 0.7.0 · 26.10: https://docs.nvidia.com/nemo/automodel/v0.7/llms.txt
> - 0.5.0 · 26.06: https://docs.nvidia.com/nemo/automodel/v0.5/llms.txt
> - 0.4.0 · 26.04: https://docs.nvidia.com/nemo/automodel/v0.4/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.nvidia.com/nemo/automodel/llms.txt.

# nemo_automodel.components.models.ergo.layers

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

| Name                                                                                         | Description                                                             |
| -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| [`ErgoAttention`](#nemo_automodel-components-models-ergo-layers-ErgoAttention)               | GQA with Q/K norm, local interleaved RoPE and every-fourth global NoPE. |
| [`ErgoBlock`](#nemo_automodel-components-models-ergo-layers-ErgoBlock)                       | One FP32 residual block with explicitly rounded branch computation.     |
| [`ErgoComputeRMSNorm`](#nemo_automodel-components-models-ergo-layers-ErgoComputeRMSNorm)     | Q/K and shared-expert normalization in the incoming compute dtype.      |
| [`ErgoDenseFFN`](#nemo_automodel-components-models-ergo-layers-ErgoDenseFFN)                 | Non-gated ReLU-squared FFN using the selected linear backend.           |
| [`ErgoExpertOutputNorm`](#nemo_automodel-components-models-ergo-layers-ErgoExpertOutputNorm) | Per-expert FP32 scale, sharded on the same expert axis as the MLP.      |
| [`ErgoMoE`](#nemo_automodel-components-models-ergo-layers-ErgoMoE)                           | Common routed experts plus independently normalized shared ReLU² FFN.   |
| [`ErgoRMSNorm`](#nemo_automodel-components-models-ergo-layers-ErgoRMSNorm)                   | Learned FP32 RMSNorm; callers explicitly own any branch-output cast.    |
| [`ErgoResidual`](#nemo_automodel-components-models-ergo-layers-ErgoResidual)                 | Learned variance-preserving residual blend with stable live gradients.  |
| [`ErgoTokenEmbedding`](#nemo_automodel-components-models-ergo-layers-ErgoTokenEmbedding)     | FP32 token table \[vocab, hidden].                                      |

### Functions

| Name                                                                                           | Description                                                                      |
| ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| [`_compiled_expert_norm`](#nemo_automodel-components-models-ergo-layers-_compiled_expert_norm) | Cache pure compiled math, without retaining parameters or activations.           |
| [`_expert_norm_core`](#nemo_automodel-components-models-ergo-layers-_expert_norm_core)         | Normalize \[routes, hidden] with an FP32 \[hidden] scale and retain input dtype. |

### Data

[`FP32_OWNER_MARKER`](#nemo_automodel-components-models-ergo-layers-FP32_OWNER_MARKER)

[`FP32_OWNER_MODULE_NAMES`](#nemo_automodel-components-models-ergo-layers-FP32_OWNER_MODULE_NAMES)

### API

```python
class nemo_automodel.components.models.ergo.layers.ErgoAttention(
    config: nemo_automodel.components.models.ergo.config.ErgoConfig,
    layer_id: int,
    backend: nemo_automodel.components.models.common.BackendConfig,
    dtype: torch.dtype,
    rotary_frequencies: nemo_automodel.components.models.ergo.rope.ErgoRotaryFrequencies | None = None
)
```

**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`**

---

```python
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.

```python
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 | None` — default: None

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

---

**`**attn_kwargs`** `Any` — default: \{}

Backend-specific packed attention metadata.

---

**Returns:** `torch.Tensor`

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

```python
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.

```python
class nemo_automodel.components.models.ergo.layers.ErgoBlock(
    config: nemo_automodel.components.models.ergo.config.ErgoConfig,
    layer_id: int,
    backend: nemo_automodel.components.models.common.BackendConfig,
    dtype: torch.dtype,
    rotary_frequencies: nemo_automodel.components.models.ergo.rope.ErgoRotaryFrequencies | None = None
)
```

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

---

```python
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 | None` — default: 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 | None` — default: None

Optional boolean padding flags with the leading shape of `residual`.

---

**`**attn_kwargs`** `Any` — default: \{}

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

---

**Returns:** `torch.Tensor`

FP32 residual states with the shape of `residual`.

```python
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

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

**Bases:** [ErgoRMSNorm](#nemo_automodel-components-models-ergo-layers-ErgoRMSNorm)

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

```python
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.

```python
class nemo_automodel.components.models.ergo.layers.ErgoDenseFFN(
    hidden_size: int,
    inner_size: int,
    backend: nemo_automodel.components.models.common.BackendConfig,
    dtype: torch.dtype
)
```

**Bases:** `Module`

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

**`down`**

---

**`up`**

---

```python
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.

```python
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.

```python
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`**

---

```python
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`.

```python
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 | None` — default: 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`.

```python
class nemo_automodel.components.models.ergo.layers.ErgoMoE(
    config: nemo_automodel.components.models.ergo.config.ErgoConfig,
    moe_config: nemo_automodel.components.moe.config.MoEConfig,
    backend: nemo_automodel.components.models.common.BackendConfig
)
```

**Bases:** [MoE](/nemo/automodel/v0.7/nemo-automodel/nemo_automodel/components/moe/layers#nemo_automodel-components-moe-layers-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`**

---

```python
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.

```python
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 | None` — default: 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

```python
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.

```python
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`**

---

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

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

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

**Bases:** `Module`

Learned variance-preserving residual blend with stable live gradients.

**`scale`**

---

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

```python
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.

```python
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.

```python
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.

```python
nemo_automodel.components.models.ergo.layers.FP32_OWNER_MARKER = 'fp32_owner'
```

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