> This page is for version Nightly (default).
> 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.hy_v4_flash.model

Hy4-flash decoder stack for AutoModel training (text backbone; the vision tower is in `vision.py`).

Forward contract (transformers reference `HYV4FlashTextModel`): tokens are embedded and replicated into `hc_mult`
residual streams `[batch, sequence, hc_mult, hidden]`. Each block optionally applies Engram to the streams, then
`attn_hc` -> `input_layernorm` -> gated MLA -> `post_self_attn_layernorm` -> scatter, then `ffn_hc` ->
`post_attention_layernorm` -> dense MLP / latent MoE -> `post_mlp_layernorm` -> scatter. `hc_head` collapses
the streams before the final RMSNorm and the fp32 `lm_head`.

Batch rows and packed documents are flattened into one token axis for attention and never attend to each other.
Context parallelism shards the packed row and gathers keys per layer. Pipeline parallelism is not supported.

## Module Contents

### Classes

| Name                                                                                               | Description                                                                                  |
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| [`HYV4FlashBatch`](#nemo_automodel-components-models-hy_v4_flash-model-HYV4FlashBatch)             | Flattened-token view of one forward pass, shared by all layers.                              |
| [`HYV4FlashBlock`](#nemo_automodel-components-models-hy_v4_flash-model-HYV4FlashBlock)             | One sandwich-normed, hyper-connected decoder layer.                                          |
| [`HYV4FlashCPInputs`](#nemo_automodel-components-models-hy_v4_flash-model-HYV4FlashCPInputs)       | Model-owned context-parallel inputs handed to the training recipe.                           |
| [`HYV4FlashForCausalLM`](#nemo_automodel-components-models-hy_v4_flash-model-HYV4FlashForCausalLM) | Hy4-flash: the decoder stack, the vision tower for image-text inputs, and an fp32 `lm_head`. |
| [`HYV4FlashModel`](#nemo_automodel-components-models-hy_v4_flash-model-HYV4FlashModel)             | Embeddings, hyper-connected blocks and the output collapse.                                  |

### Functions

| Name                                                                                                           | Description                                                                                              |
| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| [`build_moe_config`](#nemo_automodel-components-models-hy_v4_flash-model-build_moe_config)                     | MoE settings of the latent-space sigmoid router (all routed experts run at `routed_expert_hidden_size`). |
| [`compute_mrope_position_ids`](#nemo_automodel-components-models-hy_v4_flash-model-compute_mrope_position_ids) | M-RoPE positions of mixed text / image rows (the reference `get_rope_index`).                            |
| [`vision_position_ids`](#nemo_automodel-components-models-hy_v4_flash-model-vision_position_ids)               | 3-D positions of one image/video: every merged row has `w + 1` tokens (the last is the newline).         |

### Data

[`HYV4FlashForConditionalGeneration`](#nemo_automodel-components-models-hy_v4_flash-model-HYV4FlashForConditionalGeneration)

[`ModelClass`](#nemo_automodel-components-models-hy_v4_flash-model-ModelClass)

### API

```python
class nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashBatch(
    layout: nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashDocLayout,
    ropes: dict[str, nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashRope],
    ngram_tokens: torch.Tensor | None,
    engram_mask: torch.Tensor | None,
    padding_mask: torch.Tensor | None
)
```

Dataclass

Flattened-token view of one forward pass, shared by all layers.

**`engram_mask`** `Tensor | None`

Bool tensor \[batch, sequence] or `None`.

---

**`layout`** `HYV4FlashDocLayout`

Document boundaries over the flattened `batch * sequence` token axis.

---

**`ngram_tokens`** `Tensor | None`

Integer tensor \[batch, sequence, max_ngram_size] or `None` without Engram layers.

---

**`padding_mask`** `Tensor | None`

Bool tensor \[batch, sequence], True at padding, or `None`.

---

**`ropes`** `dict[str, HYV4FlashRope]`

Rotary tables per attention type over the flattened token axis.

---

```python
class nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashBlock(
    config: nemo_automodel.components.models.hy_v4_flash.config.HYV4FlashTextConfig,
    layer_idx: int,
    backend: nemo_automodel.components.models.common.BackendConfig,
    moe_config: nemo_automodel.components.moe.config.MoEConfig,
    engram_process_group: torch.distributed.ProcessGroup | None = None
)
```

**Bases:** `Module`

One sandwich-normed, hyper-connected decoder layer.

**`attention_type`** `= config.attention_types[layer_idx]`

---

**`attn_hc`** `= HYV4FlashHyperConnection(config)`

---

**`engram_layer`**

---

**`ffn_hc`** `= HYV4FlashHyperConnection(config)`

---

**`has_moe`** `= config.mlp_layer_types[layer_idx] == 'sparse'`

---

**`input_layernorm`** `= HYV4FlashRMSNorm(hidden, eps, dtype)`

---

**`mlp`** `= MoE(moe_config, backend)`

---

**`post_attention_layernorm`** `= HYV4FlashRMSNorm(hidden, eps, dtype)`

---

**`post_mlp_layernorm`** `= HYV4FlashRMSNorm(hidden, eps, dtype)`

---

**`post_self_attn_layernorm`** `= HYV4FlashRMSNorm(hidden, eps, dtype)`

---

**`self_attn`** `= HYV4FlashAttention(config, layer_idx, backend)`

---

```python
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashBlock.forward(
    streams: torch.Tensor,
    batch: nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashBatch
) -> torch.Tensor
```

Run the layer on `streams` \[batch, sequence, hc_mult, hidden]; the result has the same shape.

```python
class nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashCPInputs
```

**Bases:** `typing.TypedDict`

Model-owned context-parallel inputs handed to the training recipe.

**`cp_sharder`** `ContextParallelSharder`

---

```python
class nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM(
    config: nemo_automodel.components.models.hy_v4_flash.config.HYV4FlashConfig,
    moe_config: nemo_automodel.components.moe.config.MoEConfig | None = None,
    backend: nemo_automodel.components.models.common.BackendConfig | None = None,
    engram_process_group: torch.distributed.ProcessGroup | None = None,
    logits_dtype: torch.dtype | None = torch.float32
)
```

**Bases:** [HFCheckpointingMixin](/nemo/automodel/nightly/nemo-automodel/nemo_automodel/components/models/common/hf_checkpointing_mixin#nemo_automodel-components-models-common-hf_checkpointing_mixin-HFCheckpointingMixin), `PreTrainedModel`, [MoEFSDPSyncMixin](/nemo/automodel/nightly/nemo-automodel/nemo_automodel/components/moe/fsdp_mixin#nemo_automodel-components-moe-fsdp_mixin-MoEFSDPSyncMixin)

Hy4-flash: the decoder stack, the vision tower for image-text inputs, and an fp32 `lm_head`.

**`_fsdp_shard_across_blocks`**

---

**`_keep_in_fp32_modules_strict`**

---

**`_owns_cp_attention`** `bool = True`

---

**`_packed_cp_attn_backends`** `= ('cudnn', 'sdpa')`

---

**`backend`**

---

**`base_model_prefix`** `= 'model'`

---

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

---

**`image_token_id`** `= config.image_token_id`

---

**`lm_head`**

---

**`model`**

---

**`spatial_merge_size`** `= vision.spatial_merge_size`

---

**`state_dict_adapter`**

---

**`tie_word_embeddings_support`** `TieSupport = TieSupport.UNTIED_ONLY`

---

**`vit`**

---

```python
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM._embed(
    input_ids: torch.Tensor,
    pixel_values: torch.Tensor | None,
    image_grid_thw: torch.Tensor | None
) -> torch.Tensor
```

Token embeddings \[batch, sequence, hidden] with image features scattered into the image pad positions.

`pixel_values` has shape \[patches, channels \* patch_size \* patch_size] and `image_grid_thw` \[images, 3].

```python
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM._nemo_prepare_model_owned_dtensors(
    fsdp_mesh: torch.distributed.device_mesh.DeviceMesh
) -> set[torch.nn.Parameter]
```

Register the row-owner-sharded Engram tables as DTensors before FSDP records its ignored parameters.

**Parameters:**

**`fsdp_mesh`** `DeviceMesh`

One-dimensional shard mesh whose ranks and order equal the Engram owner group.

---

**Returns:** `set[nn.Parameter]`

The table parameters (global shape \[padded_rows, head_dim], `Shard(0)`) that FSDP must not own.

```python
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM.forward(
    input_ids: torch.Tensor,
    position_ids: torch.Tensor | None = None,
    attention_mask: torch.Tensor | None = None,
    padding_mask: torch.Tensor | None = None,
    packed_seq_ids: torch.Tensor | None = None,
    labels: torch.Tensor | None = None,
    loss_mask: torch.Tensor | None = None,
    logits_to_keep: int | torch.Tensor = 0,
    output_hidden_states: bool = False,
    pixel_values: torch.Tensor | None = None,
    image_grid_thw: torch.Tensor | None = None,
    mm_token_type_ids: torch.Tensor | None = None,
    cp_group: torch.distributed.ProcessGroup | None = None,
    seq_lens: torch.Tensor | None = None,
    seq_lens_padded: torch.Tensor | None = None,
    qkv_format: str | None = None
) -> transformers.modeling_outputs.CausalLMOutputWithPast
```

Compute logits (and an optional mean token loss).

**Parameters:**

**`input_ids`** `torch.Tensor`

Integer tensor of shape \[batch, sequence].

---

**`position_ids`** `torch.Tensor | None` — default: None

Optional integer tensor of shape \[batch, sequence] or \[3, batch, sequence].

---

**`attention_mask`** `torch.Tensor | None` — default: None

Optional tensor of shape \[batch, sequence], 1 for real tokens.

---

**`padding_mask`** `torch.Tensor | None` — default: None

Optional bool tensor of shape \[batch, sequence], True at padding (used if no attention_mask).

---

**`packed_seq_ids`** `torch.Tensor | None` — default: None

Optional integer tensor of shape \[batch, sequence] with packed-document ids.

---

**`labels`** `torch.Tensor | None` — default: None

Optional integer tensor of shape \[batch, sequence], -100 ignored. With `seq_lens` the first
token of every document is not supervised.

---

**`loss_mask`** `torch.Tensor | None` — default: None

Consumed by the recipe loss; accepted so the standard batch reaches the model.

---

**`logits_to_keep`** `int | torch.Tensor` — default: 0

Number of final positions, or integer positions to keep.

---

**`output_hidden_states`** `bool` — default: False

Attach the final hidden states \[batch, sequence, hidden].

---

**`pixel_values`** `torch.Tensor | None` — default: None

Optional tensor of shape \[patches, channels \* patch_size \* patch_size].

---

**`image_grid_thw`** `torch.Tensor | None` — default: None

Optional integer tensor of shape \[images, 3] of (time, height, width) patch counts.

---

**`mm_token_type_ids`** `torch.Tensor | None` — default: None

Optional integer tensor of shape \[batch, sequence], 0 text / 1 image.

---

**`cp_group`** `dist.ProcessGroup | None` — default: None

Context-parallel group; the token tensors are then the shard from the model-owned sharder.

---

**`seq_lens`** `torch.Tensor | None` — default: None

Optional integer tensor of shape \[batch, documents] of document lengths of a packed row
(non-CP); `seq_lens_padded` gives the physical spans and `qkv_format` must be `"thd"` or omitted.

---

**Returns:** `CausalLMOutputWithPast`

`CausalLMOutputWithPast` with logits \[batch, kept_sequence, vocab].

```python
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM.from_config(
    config: nemo_automodel.components.models.hy_v4_flash.config.HYV4FlashConfig,
    moe_config: nemo_automodel.components.moe.config.MoEConfig | None = None,
    backend: nemo_automodel.components.models.common.BackendConfig | None = None,
    engram_process_group: torch.distributed.ProcessGroup | None = None,
    logits_dtype: torch.dtype | None = torch.float32
) -> nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM
```

classmethod

Construct using the NeMo registry's configuration entry point.

```python
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM.get_input_embeddings() -> torch.nn.Embedding
```

Return the token embedding.

```python
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM.get_output_embeddings() -> torch.nn.Module
```

Return the independent vocabulary projection.

```python
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM.initialize_weights(
    buffer_device: torch.device | None = None,
    dtype: torch.dtype = torch.bfloat16
) -> None
```

Initialize every weight (checkpoint-free path) as the reference does.

```python
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM.prepare_model_inputs_for_cp(
    batch: dict[str, torch.Tensor],
    num_chunks: int = 1
) -> nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashCPInputs
```

Select contiguous packed sharding (documents are never aligned or reordered).

`batch` holds full tensors \[batch, global_sequence]; the returned model-owned sharder yields local token
tensors of shape \[1, padded_global_sequence / cp_size]. `num_chunks` is unused: this model uses one chunk.

```python
class nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashModel(
    config: nemo_automodel.components.models.hy_v4_flash.config.HYV4FlashTextConfig,
    backend: nemo_automodel.components.models.common.BackendConfig,
    moe_config: nemo_automodel.components.moe.config.MoEConfig,
    engram_process_group: torch.distributed.ProcessGroup | None = None
)
```

**Bases:** `Module`

Embeddings, hyper-connected blocks and the output collapse.

**`embed_tokens`**

---

**`hc_head`** `= HYV4FlashHyperHead(config)`

---

**`layers`**

---

**`norm`**

---

```python
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashModel.forward(
    input_ids: torch.Tensor,
    position_ids: torch.Tensor,
    attention_mask: torch.Tensor | None = None,
    packed_seq_ids: torch.Tensor | None = None,
    inputs_embeds: torch.Tensor,
    image_token_mask: torch.Tensor | None = None,
    cp_group: torch.distributed.ProcessGroup | None = None
) -> torch.Tensor
```

Compute the final hidden states \[batch, sequence, hidden].

`inputs_embeds` \[batch, sequence, hidden] are the token embeddings with image features in place; the other
arguments are those of `prepare_batch`.

```python
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashModel.prepare_batch(
    input_ids: torch.Tensor,
    position_ids: torch.Tensor,
    attention_mask: torch.Tensor | None,
    packed_seq_ids: torch.Tensor | None,
    image_token_mask: torch.Tensor | None,
    cp_group: torch.distributed.ProcessGroup | None = None
) -> nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashBatch
```

Build the flattened-token metadata shared by every layer.

**Parameters:**

**`input_ids`** `torch.Tensor`

Integer tensor of shape \[batch, sequence].

---

**`position_ids`** `torch.Tensor`

Integer tensor of shape \[3, batch, sequence] (time, height, width).

---

**`attention_mask`** `torch.Tensor | None`

Optional bool/int tensor of shape \[batch, sequence], 1 for real tokens.

---

**`packed_seq_ids`** `torch.Tensor | None`

Optional integer tensor of shape \[batch, sequence] with document ids (0 = padding).

---

**`image_token_mask`** `torch.Tensor | None`

Optional bool tensor of shape \[batch, sequence], True at image placeholder tokens.

---

**`cp_group`** `dist.ProcessGroup | None` — default: None

Context-parallel group; all token tensors above then hold this rank's contiguous shard
(batch must be 1) and the returned document layout / rotary tables cover the global sequence.

---

**Returns:** `HYV4FlashBatch`

The shared batch view.

```python
nemo_automodel.components.models.hy_v4_flash.model.build_moe_config(
    text: nemo_automodel.components.models.hy_v4_flash.config.HYV4FlashTextConfig,
    dtype: torch.dtype
) -> nemo_automodel.components.moe.config.MoEConfig
```

MoE settings of the latent-space sigmoid router (all routed experts run at `routed_expert_hidden_size`).

```python
nemo_automodel.components.models.hy_v4_flash.model.compute_mrope_position_ids(
    mm_token_type_ids: torch.Tensor,
    image_grid_thw: torch.Tensor | None,
    attention_mask: torch.Tensor | None,
    merge: int
) -> torch.Tensor
```

M-RoPE positions of mixed text / image rows (the reference `get_rope_index`).

Text advances all three axes by one per token; an image block takes `vision_position_ids` and the next
text token continues at `max + 1`. Padding positions get zero.

**Parameters:**

**`mm_token_type_ids`** `torch.Tensor`

Integer tensor of shape \[batch, sequence], 0 for text and 1 for image tokens.

---

**`image_grid_thw`** `torch.Tensor | None`

Integer tensor of shape \[images, 3] in row-major order of appearance, or `None`.

---

**`attention_mask`** `torch.Tensor | None`

Optional tensor of shape \[batch, sequence], 1 for real tokens.

---

**`merge`** `int`

Spatial merge size.

---

**Returns:** `torch.Tensor`

Integer tensor of shape \[3, batch, sequence].

```python
nemo_automodel.components.models.hy_v4_flash.model.vision_position_ids(
    start: int,
    grid_thw: tuple[int, int, int],
    merge: int
) -> torch.Tensor
```

3-D positions of one image/video: every merged row has `w + 1` tokens (the last is the newline).

All three axes of a frame start at the same offset and each frame starts a new block of `max(h, w + 1)` positions.

**Returns:** `torch.Tensor`

Integer tensor of shape \[3, t \* h \* (w + 1)] (time, height, width), offset by `start`.

```python
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForConditionalGeneration = HYV4FlashForCausalLM
```

```python
nemo_automodel.components.models.hy_v4_flash.model.ModelClass = HYV4FlashForCausalLM
```