> This page is for version 0.4.0 · 26.04.
> 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.speculative.dfly2

DFly2 speculative-decoding draft training (arXiv:2611.34776).

A block-parallel drafter for sparse-attention targets: each draft layer is paired with
one target sparse-attention layer and reads that layer's keys (KV sharing) at the
positions it attends from the row before the anchor (index sharing), so the served
drafter keeps no KV cache and runs no indexer of its own.

## Submodules

* **[`nemo_automodel.components.speculative.dfly2.common`](/nemo/automodel/v0.4/nemo-automodel/nemo_automodel/components/speculative/dfly2/common)**
* **[`nemo_automodel.components.speculative.dfly2.core`](/nemo/automodel/v0.4/nemo-automodel/nemo_automodel/components/speculative/dfly2/core)**
* **[`nemo_automodel.components.speculative.dfly2.loss`](/nemo/automodel/v0.4/nemo-automodel/nemo_automodel/components/speculative/dfly2/loss)**
* **[`nemo_automodel.components.speculative.dfly2.target`](/nemo/automodel/v0.4/nemo-automodel/nemo_automodel/components/speculative/dfly2/target)**

## Package Contents

### Classes

| Name                                                                                                           | Description                                                                       |
| -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| [`DFly2TargetFeatureProvider`](#nemo_automodel-components-speculative-dfly2-target-DFly2TargetFeatureProvider) | Target model that exposes the attention state its paired DFly2 draft layers read. |
| [`DFly2TargetFeatures`](#nemo_automodel-components-speculative-dfly2-common-DFly2TargetFeatures)               | Frozen target state one DFly2 training step reads.                                |
| [`DFly2TargetModel`](#nemo_automodel-components-speculative-dfly2-target-DFly2TargetModel)                     | Run a frozen target that implements `DFly2TargetFeatureProvider`.                 |
| [`DFly2TrainerModule`](#nemo_automodel-components-speculative-dfly2-core-DFly2TrainerModule)                   | DFly2 online training wrapper computing the D-PACE-weighted LK objective.         |
| [`ModelOwnedDFly2Provider`](#nemo_automodel-components-speculative-dfly2-target-ModelOwnedDFly2Provider)       | Target config that owns construction of its architecture-specific DFly2 draft.    |

### Functions

| Name                                                                                                     | Description                                                                           |
| -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| [`build_block_key_indices`](#nemo_automodel-components-speculative-dfly2-common-build_block_key_indices) | Build every draft query's key list: the target's picks for its block, then its block. |

### API

```python
class nemo_automodel.components.speculative.dfly2.target.DFly2TargetFeatureProvider()
```

Protocol

Target model that exposes the attention state its paired DFly2 draft layers read.

```python
nemo_automodel.components.speculative.dfly2.target.DFly2TargetFeatureProvider.dfly2_target_features(
    input_ids: torch.Tensor,
    attention_mask: torch.Tensor,
    layer_ids: collections.abc.Sequence[int]
) -> nemo_automodel.components.speculative.dfly2.common.DFly2TargetFeatures
```

Run the frozen forward and return the paired layers' keys and key lists.

**Parameters:**

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

Integer tensor of shape \[batch, sequence].

---

**`attention_mask`** `torch.Tensor`

Binary right-padding tensor of shape \[batch, sequence].

---

**`layer_ids`** `Sequence[int]`

Target layers paired with the draft layers, in draft-layer order.

---

```python
class nemo_automodel.components.speculative.dfly2.common.DFly2TargetFeatures(
    context_keys: tuple[torch.Tensor, ...],
    context_indices: tuple[torch.Tensor, ...],
    last_hidden_states: torch.Tensor
)
```

Dataclass

Frozen target state one DFly2 training step reads.

**`context_indices`** `tuple[Tensor, ...]`

One integer tensor per draft layer, of shape \[batch, sequence,
slots]. Row `r` lists the `context_keys` rows the paired target layer
attended from token `r`, with `-1` marking unused slots. Every listed key
lies at or before `r` in `r`'s document.

---

**`context_keys`** `tuple[Tensor, ...]`

One tensor per draft layer, of shape \[batch, context_keys, key_dim]:
the keys and values the paired target layer attended over, in that layer's
own row order (for example a sliding-window segment followed by a shared
global segment).

---

**`last_hidden_states`** `Tensor`

Tensor of shape \[batch, sequence, hidden], the target's final
normalized hidden state (the input of its LM head).

---

```python
nemo_automodel.components.speculative.dfly2.common.DFly2TargetFeatures.__post_init__() -> None
```

```python
class nemo_automodel.components.speculative.dfly2.target.DFly2TargetModel(
    model: torch.nn.Module,
    target_layer_ids: collections.abc.Sequence[int]
)
```

Run a frozen target that implements `DFly2TargetFeatureProvider`.

**`model`** `= model.eval()`

---

**`target_layer_ids`** `= [(int(layer_id)) for layer_id in target_layer_ids]`

---

```python
nemo_automodel.components.speculative.dfly2.target.DFly2TargetModel.generate_batch(
    input_ids: torch.Tensor,
    attention_mask: torch.Tensor,
    loss_mask: torch.Tensor
) -> nemo_automodel.components.speculative.dfly2.target.DFly2TargetBatch
```

Run the target once and collect the DFly2 features.

**Parameters:**

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

Integer tensor of shape \[batch, sequence].

---

**`attention_mask`** `torch.Tensor`

Binary right-padding tensor of shape \[batch, sequence].

---

**`loss_mask`** `torch.Tensor`

Tensor of shape \[batch, sequence] selecting supervised tokens.

---

**Returns:** `DFly2TargetBatch`

The batch with the features of `DFly2TargetFeatureProvider.dfly2_target_features`.

```python
nemo_automodel.components.speculative.dfly2.target.DFly2TargetModel.get_input_embeddings() -> torch.nn.Module
```

Return the target's input embedding.

```python
nemo_automodel.components.speculative.dfly2.target.DFly2TargetModel.get_output_embeddings() -> torch.nn.Module
```

Return the target's LM head.

```python
class nemo_automodel.components.speculative.dfly2.core.DFly2TrainerModule(
    draft_model: torch.nn.Module,
    dpace_alpha: float = 0.5,
    lk_eta: float = 3.0,
    confidence_head_alpha: float = 0.0
)
```

**Bases:** `Module`

DFly2 online training wrapper computing the D-PACE-weighted LK objective.

**`confidence_head_alpha`** `= float(confidence_head_alpha)`

---

**`dpace_alpha`** `= float(dpace_alpha)`

---

**`lk_eta`** `= float(lk_eta)`

---

```python
nemo_automodel.components.speculative.dfly2.core.DFly2TrainerModule.forward(
    input_ids: torch.Tensor,
    loss_mask: torch.Tensor,
    context_keys: collections.abc.Sequence[torch.Tensor],
    context_indices: collections.abc.Sequence[torch.Tensor],
    target_last_hidden_states: torch.Tensor
) -> nemo_automodel.components.speculative.dspark.core.DSparkStepMetrics
```

Run the draft on the target features and compute the DFly2 loss.

**Parameters:**

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

Target-token tensor of shape \[batch, sequence].

---

**`loss_mask`** `torch.Tensor`

Supervision tensor of shape \[batch, sequence].

---

**`context_keys`** `Sequence[torch.Tensor]`

One tensor per draft layer of shape \[batch, context_keys,
key_dim], as in `DFly2TargetFeatures`.

---

**`context_indices`** `Sequence[torch.Tensor]`

One integer tensor per draft layer of shape \[batch,
sequence, slots], as in `DFly2TargetFeatures`.

---

**`target_last_hidden_states`** `torch.Tensor`

Tensor of shape \[batch, sequence, hidden].

---

**Returns:** `DSparkStepMetrics`

Step metrics. The per-position acceptance sums have `block_size` entries,

```python
class nemo_automodel.components.speculative.dfly2.target.ModelOwnedDFly2Provider()
```

Protocol

Target config that owns construction of its architecture-specific DFly2 draft.

```python
nemo_automodel.components.speculative.dfly2.target.ModelOwnedDFly2Provider.build_dfly2_draft(
    options: nemo_automodel.components.speculative.dfly2.target._DFly2DraftOptions
) -> torch.nn.Module
```

Build a draft from the recipe's declarative options.

```python
nemo_automodel.components.speculative.dfly2.common.build_block_key_indices(
    context_indices: torch.Tensor,
    anchor_positions: torch.Tensor,
    block_keep_mask: torch.Tensor,
    num_context_keys: int,
    block_size: int,
    causal: bool
) -> torch.Tensor
```

Build every draft query's key list: the target's picks for its block, then its block.

Each block reads the key list of the target row just before its anchor, the last token
the target has verified when the block is drafted. Every query of a block shares that
list and then sees its own block's draft keys, which follow the `num_context_keys`
context rows in the draft attention's key tensor. A block never sees another block. An
anchor at the sequence start has no verified row before it and sees only its own block;
a dropped block (`block_keep_mask` false) sees no key at all, so its output is zero.

**Parameters:**

**`context_indices`** `torch.Tensor`

Integer tensor of shape \[batch, sequence, slots] with `-1`
unused, as in `DFly2TargetFeatures`.

---

**`anchor_positions`** `torch.Tensor`

Integer tensor of shape \[batch, num_anchors].

---

**`block_keep_mask`** `torch.Tensor`

Boolean tensor of shape \[batch, num_anchors].

---

**`num_context_keys`** `int`

Number of context rows preceding the draft keys.

---

**`block_size`** `int`

Draft slots per block, the anchor slot included.

---

**`causal`** `bool`

Whether a draft query sees only the earlier slots of its block.

---

**Returns:** `torch.Tensor`

Int32 tensor of shape \[batch, num_anchors \* block_size, padded_slots], the context