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

Gated MLA with learnable sinks for Hy4-flash: sliding-window and compressed-indexer sparse layers.

Both layer types run the same absorbed latent attention: the per-head key up-projection is folded into the query,
every head attends over one shared `[kv_lora_rank + rope]` latent per token, and the value up-projection is
applied to the output. This equals the reference's expanded attention and is what the shared sparse kernel
(`models/common/cudnn_sparse_attention`) consumes, with per-document index lists:

* `sliding_attention`: the last `sliding_window` tokens of the query's document.
* `indexed_attention`: dense causal attention while a document is not longer than `index_topk`; otherwise the
  `index_topk // index_kpool - 1` best-scoring complete groups plus the query's own group.

Indices only ever point into the query's own document, and groups are document-local.

## Module Contents

### Classes

| Name                                                                                                               | Description                                                                                         |
| ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- |
| [`HYV4FlashAttention`](#nemo_automodel-components-models-hy_v4_flash-attention-HYV4FlashAttention)                 | Gated MLA of one decoder layer (`attention_type` selects heads, indices and rotary theta).          |
| [`HYV4FlashCompressedIndexer`](#nemo_automodel-components-models-hy_v4_flash-attention-HYV4FlashCompressedIndexer) | Group-pooled lightning indexer. Selection is discrete, so the indexer receives no loss gradient.    |
| [`HYV4FlashDocLayout`](#nemo_automodel-components-models-hy_v4_flash-attention-HYV4FlashDocLayout)                 | Document boundaries and layer-independent key lists of one packed row, built once per forward pass. |
| [`HYV4FlashRope`](#nemo_automodel-components-models-hy_v4_flash-attention-HYV4FlashRope)                           | Interleaved M-RoPE tables of one attention type over the *global* sequence.                         |
| [`HYV4FlashSparsePlan`](#nemo_automodel-components-models-hy_v4_flash-attention-HYV4FlashSparsePlan)               | Kernel-ready key lists of this rank's queries.                                                      |

### Functions

| Name                                                                                                                             | Description                                                                                |
| -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| [`causal_prefix_plan`](#nemo_automodel-components-models-hy_v4_flash-attention-causal_prefix_plan)                               | Keys of the last `width` tokens (including the query) of each query, inside its document.  |
| [`reference_sparse_latent_attention`](#nemo_automodel-components-models-hy_v4_flash-attention-reference_sparse_latent_attention) | PyTorch implementation of the shared sparse latent attention kernel (CPU/CUDA, any dtype). |

### API

```python
class nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashAttention(
    config: nemo_automodel.components.models.hy_v4_flash.config.HYV4FlashTextConfig,
    layer_idx: int,
    backend: nemo_automodel.components.models.common.BackendConfig
)
```

**Bases:** `Module`

Gated MLA of one decoder layer (`attention_type` selects heads, indices and rotary theta).

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

---

**`compressed_indexer`**

---

**`gate_proj`**

---

**`index_topk`** `= config.index_topk`

---

**`kv_a_layernorm`**

---

**`kv_a_proj_with_mqa`**

---

**`kv_b_proj`**

---

**`kv_lora_rank`** `= config.kv_lora_rank`

---

**`num_heads`** `= config.attention_heads(self.attention_type)`

---

**`o_proj`**

---

**`q_a_layernorm`**

---

**`q_a_proj`**

---

**`q_b_proj`**

---

**`scale`** `= (self.nope_dim + self.rope_dim) ** -0.5`

---

**`sinks_param`**

---

```python
nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashAttention._absorbed_weights(
    dtype: torch.dtype,
    device: torch.device
) -> tuple[torch.Tensor, torch.Tensor]
```

Per-head key / value up-projections of `kv_b_proj` as `[heads, dim, latent]` tensors.

Evaluating the module on an identity keeps the result differentiable through LoRA adapters and valid
when FSDP shards `kv_b_proj` (a direct `.weight` read would see the sharded DTensor).

**Raises:**

* `RuntimeError`: If `kv_b_proj` carries a LoRA adapter with active training dropout. One absorbed weight
  cannot represent per-token dropout.

```python
nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashAttention._attend(
    query: torch.Tensor,
    kv: torch.Tensor,
    plan: nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashSparsePlan,
    sinks: torch.Tensor,
    layout: nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashDocLayout
) -> torch.Tensor
```

Run the sparse latent attention kernel (or its PyTorch twin).

**Parameters:**

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

Tensor of shape \[queries, heads, kv_lora_rank + rope_dim].

---

**`kv`** `torch.Tensor`

Tensor of shape \[keys, kv_lora_rank + rope_dim].

---

**`plan`** `HYV4FlashSparsePlan`

Key lists of the queries (`indices` \[queries, width] into `kv` rows, `lengths` \[queries]).

---

**`sinks`** `torch.Tensor`

fp32 tensor of shape \[heads], the learned sink logits.

---

**`layout`** `HYV4FlashDocLayout`

Supplies the padding-row metadata the kernel's backward needs.

---

**Returns:** `torch.Tensor`

Tensor of shape \[queries, heads, kv_lora_rank]; zero for queries without keys.

```python
nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashAttention._gather_keys(
    kv_local: torch.Tensor,
    token_keys: torch.Tensor | None,
    cp_group: torch.distributed.ProcessGroup | None
) -> tuple[torch.Tensor, torch.Tensor | None]
```

Return the latent keys (and index token keys) over the global sequence.

Under context parallelism only the latent keys `kv_local` \[local_tokens, kv_lora_rank + rope_dim]
(differentiable: backward reduce-scatters their gradients to the owning rank) and the index `token_keys`
\[local_tokens, index_head_dim] (no gradient) travel, not the hidden states.

```python
nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashAttention._select(
    layout: nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashDocLayout,
    rope: nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashRope,
    q_resid: torch.Tensor,
    hidden_states: torch.Tensor,
    token_keys: torch.Tensor
) -> nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashSparsePlan
```

Key lists of a sparse layer: dense for short documents, the indexer's selection for long ones.

`q_resid` \[local_tokens, q_lora_rank] and `hidden_states` \[local_tokens, hidden] are this rank's queries;
`token_keys` \[global_tokens, index_head_dim] are the normalized index keys. The plan holds global key rows.

```python
nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashAttention.forward(
    hidden_states: torch.Tensor,
    layout: nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashDocLayout,
    rope: nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashRope
) -> torch.Tensor
```

Attend within documents.

`hidden_states` \[1, local_tokens, hidden] is the local interval of the packed row; `rope` holds this layer
type's tables over the global sequence. The result has the same shape; positions outside every document are
zero.

```python
nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashAttention.reset_parameters(
    std: float,
    sink_init: float
) -> None
```

Initialize as the reference does: normal projections, constant sinks, unit norm weights, then the indexer.

```python
nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashAttention.setup_cp_attention(
    cp_mesh: torch.distributed.device_mesh.DeviceMesh
) -> None
```

Accept the context-parallel mesh from the shared parallelizer without storing it.

The parallelizer offers the mesh to sliding-window blocks only, so a group stored here would be missing on
the sparse layers. Every layer instead reads the group from the forward's `HYV4FlashDocLayout.cp_group`
(keys are gathered over it, queries stay local).

```python
class nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashCompressedIndexer(
    config: nemo_automodel.components.models.hy_v4_flash.config.HYV4FlashTextConfig
)
```

**Bases:** `Module`

Group-pooled lightning indexer. Selection is discrete, so the indexer receives no loss gradient.

Token keys are pooled `index_kpool` at a time through a softmax over fp32 value / gate projections
(`key_value_projection` / `key_gate_projection` biased by `intra_group_ape`), normalized, and rotated
with the sparse layer's RoPE at the first token of each group. Queries come from the attention's
`q_a_layernorm` output.

**`group_topk`** `= config.index_topk // config.index_kpool`

---

**`head_dim`** `= config.index_head_dim`

---

**`head_weight_projection`**

---

**`intra_group_ape`**

---

**`key_gate_projection`**

---

**`key_norm`**

---

**`key_value_projection`**

---

**`kpool`** `= config.index_kpool`

---

**`n_heads`** `= config.index_n_heads`

---

**`query_projection`**

---

**`rope_dim`** `= config.qk_rope_head_dim`

---

**`score_block_bytes`** `= 2 ** 29`

---

**`token_key_norm`**

---

**`token_key_projection`**

---

```python
nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashCompressedIndexer.enter_pooling_units(
    reference: torch.Tensor
) -> None
```

Enter the fp32 pooling modules once with an empty input.

Pooling runs only for documents longer than `index_topk`, so how often (and whether) a rank calls these
modules depends on its data. Under FSDP each call of a sharded unit is a collective (all-gather), and ranks
that issue different collective sequences deadlock. Entering the units here, unconditionally and in the same
order on every rank, makes that sequence data independent; later calls find the parameters unsharded.

**Parameters:**

**`reference`** `torch.Tensor`

Any tensor on the compute device (its values are unused).

---

```python
nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashCompressedIndexer.pool_groups(
    token_keys: torch.Tensor
) -> torch.Tensor
```

Pool one document's token keys into complete-group keys.

**Parameters:**

**`token_keys`** `torch.Tensor`

Tensor of shape \[document_tokens, index_head_dim].

---

**Returns:** `torch.Tensor`

Tensor of shape \[document_tokens // index_kpool, index_head_dim] (a trailing partial group has no key).

```python
nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashCompressedIndexer.reset_parameters(
    std: float
) -> None
```

Initialize as the reference does: normal projections and pooling bias, unit norm weights.

```python
nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashCompressedIndexer.select(
    q_resid: torch.Tensor,
    hidden_states: torch.Tensor,
    query_rope: nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashRope,
    group_keys: torch.Tensor,
    group_rope: nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashRope,
    first_query_slot: int
) -> nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashSparsePlan
```

Select the document-local tokens every query of one contiguous query interval attends to.

A query recalls the `index_topk // index_kpool - 1` best-scoring groups that closed before its own group
(ties towards the earlier group), plus its own group up to itself. The fp32 `[queries, heads, groups]`
scores are materialized a chunk of queries at a time, within `score_block_bytes`.

**Parameters:**

**`q_resid`** `torch.Tensor`

Tensor of shape \[queries, q_lora_rank]; consecutive tokens of one document.

---

**`hidden_states`** `torch.Tensor`

Tensor of shape \[queries, hidden].

---

**`query_rope`** `HYV4FlashRope`

Tables of shape \[queries, rope_dim // 2] at the queries' positions.

---

**`group_keys`** `torch.Tensor`

Tensor of shape \[groups, index_head_dim], unrotated pooled keys of the document's leading
complete groups; must cover every group that closes before the last query's group.

---

**`group_rope`** `HYV4FlashRope`

Tables of shape \[groups, rope_dim // 2] at the first token of each group.

---

**`first_query_slot`** `int`

Document-local token index of the first query.

---

**Returns:** `HYV4FlashSparsePlan`

Plan with `indices` \[queries, index_topk] of document-local token indices and `lengths` \[queries].

```python
nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashCompressedIndexer.token_keys(
    hidden_states: torch.Tensor
) -> torch.Tensor
```

Normalized per-token index keys.

**Parameters:**

**`hidden_states`** `torch.Tensor`

Tensor of shape \[tokens, hidden].

---

**Returns:** `torch.Tensor`

Tensor of shape \[tokens, index_head_dim].

```python
class nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashDocLayout(
    doc_ranges: tuple[tuple[int, int], ...],
    local_start: int,
    local_end: int,
    window_plan: nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashSparsePlan,
    dense_plan: nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashSparsePlan,
    all_rows_nonempty: bool,
    valid_rows: torch.Tensor | None,
    cp_group: torch.distributed.ProcessGroup | None = None
)
```

Dataclass

Document boundaries and layer-independent key lists of one packed row, built once per forward pass.

**`all_rows_nonempty`** `bool`

Whether this rank holds no padding token (every query has at least its own key).

---

**`cp_group`** `ProcessGroup | None = None`

Context-parallel group whose ranks hold the consecutive shards of the global sequence, or `None`
when this rank holds all of it. Every layer gathers its keys over this group.

---

**`dense_plan`** `HYV4FlashSparsePlan`

Key lists of every sparse layer before selection (width `index_topk`): exact for documents
not longer than `index_topk`; rows of longer documents are replaced by the indexer's selection.

---

**`doc_ranges`** `tuple[tuple[int, int], ...]`

`(start, end)` token intervals of the real documents in the *global* sequence
(`end` exclusive); padding is not listed.

---

**`local_end`** `int`

One past the last global token held by this rank.

---

**`local_start`** `int`

First global token held by this rank (0 without context parallelism).

---

**`valid_rows`** `Tensor | None`

Int64 tensor of shape \[valid_local_tokens] of the non-padding local queries, or `None` when
`all_rows_nonempty`.

---

**`window_plan`** `HYV4FlashSparsePlan`

Key lists of every sliding-window layer (width `sliding_window`).

---

```python
class nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashRope(
    cos: torch.Tensor,
    sin: torch.Tensor
)
```

Dataclass

Interleaved M-RoPE tables of one attention type over the *global* sequence.

**`cos`** `Tensor`

Tensor of shape \[global_tokens, rope_dim // 2].

---

**`sin`** `Tensor`

Tensor of shape \[global_tokens, rope_dim // 2].

---

```python
class nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashSparsePlan(
    indices: torch.Tensor,
    lengths: torch.Tensor
)
```

Dataclass

Kernel-ready key lists of this rank's queries.

**`indices`** `Tensor`

Int32 tensor of shape \[local_tokens, width] of global key rows: an ascending valid prefix followed
by `-1`.

---

**`lengths`** `Tensor`

Int32 tensor of shape \[local_tokens], the valid-prefix length of each query (0 for padding).

---

```python
nemo_automodel.components.models.hy_v4_flash.attention.causal_prefix_plan(
    position: torch.Tensor,
    doc_start: torch.Tensor,
    width: int
) -> nemo_automodel.components.models.hy_v4_flash.attention.HYV4FlashSparsePlan
```

Keys of the last `width` tokens (including the query) of each query, inside its document.

This is the whole key list of a sliding-window layer (`width = sliding_window`) and of a sparse layer for
documents not longer than `index_topk` (`width = index_topk`, i.e. dense causal attention).

**Parameters:**

**`position`** `torch.Tensor`

Integer tensor of shape \[queries], global token index of each query.

---

**`doc_start`** `torch.Tensor`

Integer tensor of shape \[queries], global index of each query's document start
(`position + 1` for padding, which leaves the query without keys).

---

**`width`** `int`

Maximum number of keys per query.

---

**Returns:** `HYV4FlashSparsePlan`

The plan, with `indices` of shape \[queries, width] and `lengths` of shape \[queries].

```python
nemo_automodel.components.models.hy_v4_flash.attention.reference_sparse_latent_attention(
    q: torch.Tensor,
    kv: torch.Tensor,
    indices: torch.Tensor,
    sink: torch.Tensor,
    scale: float,
    value_dim: int,
    chunk: int = 64
) -> torch.Tensor
```

PyTorch implementation of the shared sparse latent attention kernel (CPU/CUDA, any dtype).

**Parameters:**

**`q`** `torch.Tensor`

Tensor of shape \[queries, heads, latent_dim + rope_dim].

---

**`kv`** `torch.Tensor`

Tensor of shape \[keys, latent_dim + rope_dim], shared by all heads.

---

**`indices`** `torch.Tensor`

Integer tensor of shape \[queries, width] into `kv` rows, `-1` marking unused slots.

---

**`sink`** `torch.Tensor`

fp32 tensor of shape \[heads], learned sink logits (scaled-logit space).

---

**`scale`** `float`

Softmax scale applied to `q . k`.

---

**`value_dim`** `int`

Leading channels of `kv` used as the value (the latent width).

---

**`chunk`** `int` — default: 64

Queries processed at a time.

---

**Returns:** `torch.Tensor`

Tensor of shape \[queries, heads, value_dim] in the dtype of `q`.