> This page is for version Latest.
> 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.magi_cp

Model-owned packed context parallelism with MagiAttention.

MagiAttention partitions the tokens of a packed row across the context-parallel ranks and exchanges only
the keys and values each rank's queries can attend. A local layer attends at most
`local_attention_window` keys of the query's document, so its exchange is a narrow band; a global layer
exchanges the causal keys of each document. The two masks share one token partition, so the residual
stream never moves between layers.

The plan follows `muse_spark/magi_cp.py`: one dispatch per pack in 512-token chunks, a full-causal key and window
keys that share its token partition, and plans selected per pipeline microbatch. It stays separate because the
input contracts differ: Ergo concatenates the packs of one pipeline microbatch into one token stream and has a
single window, `local_attention_window`; Muse dispatches one pack per microbatch and builds one key per entry of
`layer_sliding_windows`.

## Module Contents

### Classes

| Name                                                                                      | Description                                                                                |
| ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| [`ErgoMagiBatchPlans`](#nemo_automodel-components-models-ergo-magi_cp-ErgoMagiBatchPlans) | Plans of the pipeline microbatches of one step; the pipeline's index tensor selects each.  |
| [`ErgoMagiPlan`](#nemo_automodel-components-models-ergo-magi_cp-ErgoMagiPlan)             | Attention keys of one packed microbatch; every mask keeps the same dispatched token order. |
| [`_ErgoMagiModel`](#nemo_automodel-components-models-ergo-magi_cp-_ErgoMagiModel)         | Ergo model state needed to build model-owned Magi CP inputs.                               |
| [`_MagiAttentionKey`](#nemo_automodel-components-models-ergo-magi_cp-_MagiAttentionKey)   | Magi key fields consumed by the Ergo integration.                                          |

### Functions

| Name                                                                                        | Description                                                                       |
| ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| [`_build_magi_plan`](#nemo_automodel-components-models-ergo-magi_cp-_build_magi_plan)       | Build the full-causal and the local-window key of one packed microbatch.          |
| [`prepare_magi_inputs`](#nemo_automodel-components-models-ergo-magi_cp-prepare_magi_inputs) | Prepare model-owned packed CP, with one independent plan per pipeline microbatch. |

### Data

[`ErgoMagiBatch`](#nemo_automodel-components-models-ergo-magi_cp-ErgoMagiBatch)

[`ErgoMagiBatchValue`](#nemo_automodel-components-models-ergo-magi_cp-ErgoMagiBatchValue)

[`_TOKEN_FIELD_PADDING`](#nemo_automodel-components-models-ergo-magi_cp-_TOKEN_FIELD_PADDING)

[`logger`](#nemo_automodel-components-models-ergo-magi_cp-logger)

### API

```python
class nemo_automodel.components.models.ergo.magi_cp.ErgoMagiBatchPlans(
    plans: tuple[nemo_automodel.components.models.ergo.magi_cp.ErgoMagiPlan, ...]
)
```

Dataclass

Plans of the pipeline microbatches of one step; the pipeline's index tensor selects each.

**`plans`** `tuple[ErgoMagiPlan, ...]`

One plan per microbatch, in batch order.

---

```python
nemo_automodel.components.models.ergo.magi_cp.ErgoMagiBatchPlans.select(
    microbatch_index: torch.Tensor
) -> nemo_automodel.components.models.ergo.magi_cp.ErgoMagiPlan
```

Return the plan of one microbatch.

**Parameters:**

**`microbatch_index`** `torch.Tensor`

Int64 tensor of shape \[1]: the microbatch's position in the step's batch,
split from an `arange` by the pipeline schedule.

---

**Returns:** `ErgoMagiPlan`

The immutable plan of that microbatch.

```python
class nemo_automodel.components.models.ergo.magi_cp.ErgoMagiPlan(
    keys: dict[int, nemo_automodel.components.models.ergo.magi_cp._MagiAttentionKey]
)
```

Dataclass

Attention keys of one packed microbatch; every mask keeps the same dispatched token order.

**`keys`** `dict[int, _MagiAttentionKey]`

Magi key by window length, with zero for full causal attention.

---

```python
nemo_automodel.components.models.ergo.magi_cp.ErgoMagiPlan.attention(
    query: torch.Tensor,
    key: torch.Tensor,
    value: torch.Tensor,
    window: int,
    scale: float
) -> torch.Tensor
```

Compute local THD output with Magi's own key/value communication.

**Parameters:**

**`query`** `torch.Tensor`

CP-local queries of shape \[tokens, heads, head_dim].

---

**`key`** `torch.Tensor`

CP-local keys of shape \[tokens, kv_heads, head_dim].

---

**`value`** `torch.Tensor`

CP-local values of shape \[tokens, kv_heads, head_dim].

---

**`window`** `int`

Sliding-window length in tokens, the query included, or zero for full causal attention.

---

**`scale`** `float`

Attention score scale.

---

**Returns:** `torch.Tensor`

Attention output of shape \[tokens, heads, head_dim] in the local token order.

```python
class nemo_automodel.components.models.ergo.magi_cp._ErgoMagiModel()
```

Protocol

Ergo model state needed to build model-owned Magi CP inputs.

**`config`** `ErgoConfig`

---

**`cp_mesh`** `DeviceMesh | None`

---

```python
class nemo_automodel.components.models.ergo.magi_cp._MagiAttentionKey()
```

Protocol

Magi key fields consumed by the Ergo integration.

**`total_seqlen_q`** `int`

---

```python
nemo_automodel.components.models.ergo.magi_cp._build_magi_plan(
    cu_seqlens: torch.Tensor,
    config: nemo_automodel.components.models.ergo.config.ErgoConfig,
    group: torch.distributed.ProcessGroup
) -> nemo_automodel.components.models.ergo.magi_cp.ErgoMagiPlan
```

Build the full-causal and the local-window key of one packed microbatch.

**Parameters:**

**`cu_seqlens`** `torch.Tensor`

CPU int32 padded document boundaries of shape \[documents + 1].

---

**`config`** `ErgoConfig`

Ergo attention configuration.

---

**`group`** `torch.distributed.ProcessGroup`

This pipeline stage's context-parallel process group.

---

**Returns:** `ErgoMagiPlan`

Keys for full causal attention and for the local window, with identical local token ownership.

```python
nemo_automodel.components.models.ergo.magi_cp.prepare_magi_inputs(
    model: nemo_automodel.components.models.ergo.magi_cp._ErgoMagiModel,
    batch: nemo_automodel.components.models.ergo.magi_cp.ErgoMagiBatch,
    num_chunks: int
) -> dict[str, nemo_automodel.components.distributed.context_parallel.sharder.ContextParallelSharder]
```

Prepare model-owned packed CP, with one independent plan per pipeline microbatch.

**Parameters:**

**`model`** `_ErgoMagiModel`

Ergo model or pipeline stage with a bound context-parallel mesh.

---

**`batch`** `ErgoMagiBatch`

Global token IDs, labels and positions of shape \[batch, sequence] and packed document
lengths of shape \[batch, documents].

---

**`num_chunks`** `int`

Number of pipeline microbatches, which evenly divides the batch size. The packed rows of
one microbatch form one token stream.

---

**Returns:** `dict[str, ContextParallelSharder]`

A model-owned CP sharder. Token IDs stay global with shape \[chunks, tokens]; labels, positions,

```python
nemo_automodel.components.models.ergo.magi_cp.ErgoMagiBatch = dict[str, ErgoMagiBatchValue]
```

```python
nemo_automodel.components.models.ergo.magi_cp.ErgoMagiBatchValue = torch.Tensor | str | int | float | bool | ErgoMagiPlan | ErgoMagiBatchPlans | No...
```

```python
nemo_automodel.components.models.ergo.magi_cp._TOKEN_FIELD_PADDING: dict[str, int | bool] = {'position_ids': 0, 'labels': -100, 'loss_mask': 0, 'padding_mask': True}
```

```python
nemo_automodel.components.models.ergo.magi_cp.logger = logging.getLogger(__name__)
```