> 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.speculative.dfly2.loss

DFly2 training objective: D-PACE-weighted LK distillation plus an optional confidence head.

Per drafted slot, with `p` the target distribution and `q` the draft's:

* `TV = 1/2 sum|p - q|` and `KL = sum p (log p - log q)` over the full vocabulary;
* the LK hybrid `lambda * KL + (1 - lambda) * TV` with `lambda = exp(-eta * sg(1 - TV))`,
  which distills while the draft is far from the target and turns to the acceptance
  probability `1 - TV` as it gets close;
* D-PACE position weights (arXiv:2605.18810), computed detached from the draft's
  cross entropy on the corpus token, weight both terms;
* the confidence head regresses the slot's acceptance probability `sum min(p, q)`.

Every term is a weighted sum over the local slots divided by the weight sum of all
data-parallel ranks, and the backward loss is scaled by the world size, so the
averaged gradient equals the global weighted mean regardless of how slots split
across ranks (the DSpark objective's convention).

## Module Contents

### Functions

| Name                                                                                             | Description                                                                                |
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ |
| [`_compute_distances`](#nemo_automodel-components-speculative-dfly2-loss-_compute_distances)     | Compute per-slot TV and KL without full-vocabulary FP32 temporaries for every slot.        |
| [`_distance_chunk`](#nemo_automodel-components-speculative-dfly2-loss-_distance_chunk)           | Compute FP32 total variation and forward KL for a chunk of slots.                          |
| [`_token_cross_entropy`](#nemo_automodel-components-speculative-dfly2-loss-_token_cross_entropy) | Compute the draft's FP32 cross entropy on the corpus tokens, chunked and without autograd. |
| [`compute_dfly2_loss`](#nemo_automodel-components-speculative-dfly2-loss-compute_dfly2_loss)     | Compute the DFly2 objective and its logged terms for one micro-batch.                      |

### Data

[`_PROBABILITY_CHUNK_TOKENS`](#nemo_automodel-components-speculative-dfly2-loss-_PROBABILITY_CHUNK_TOKENS)

### API

```python
nemo_automodel.components.speculative.dfly2.loss._compute_distances(
    draft_logits: torch.Tensor,
    target_logits: torch.Tensor,
    chunk_size: int = _PROBABILITY_CHUNK_TOKENS
) -> tuple[torch.Tensor, torch.Tensor]
```

Compute per-slot TV and KL without full-vocabulary FP32 temporaries for every slot.

Each chunk is recomputed in the backward pass, so only one chunk's probabilities are
alive at a time.

**Parameters:**

**`draft_logits`** `torch.Tensor`

Tensor of shape \[..., vocab].

---

**`target_logits`** `torch.Tensor`

Tensor of shape \[..., vocab], detached.

---

**`chunk_size`** `int` — default: \_PROBABILITY_CHUNK_TOKENS

Slots per chunk.

---

**Returns:** `tuple[torch.Tensor, torch.Tensor]`

`(tv, kl)`, each of shape \[...].

```python
nemo_automodel.components.speculative.dfly2.loss._distance_chunk(
    draft_logits: torch.Tensor,
    target_logits: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]
```

Compute FP32 total variation and forward KL for a chunk of slots.

**Parameters:**

**`draft_logits`** `torch.Tensor`

Tensor of shape \[tokens, vocab].

---

**`target_logits`** `torch.Tensor`

Tensor of shape \[tokens, vocab].

---

**Returns:** `tuple[torch.Tensor, torch.Tensor]`

`(tv, kl)`, each of shape \[tokens].

```python
nemo_automodel.components.speculative.dfly2.loss._token_cross_entropy(
    draft_logits: torch.Tensor,
    target_ids: torch.Tensor,
    chunk_size: int = _PROBABILITY_CHUNK_TOKENS
) -> torch.Tensor
```

Compute the draft's FP32 cross entropy on the corpus tokens, chunked and without autograd.

It only sets the detached D-PACE weights and the logged `ce`, so no full-vocabulary
log-softmax is kept for the backward pass.

**Parameters:**

**`draft_logits`** `torch.Tensor`

Tensor of shape \[..., vocab].

---

**`target_ids`** `torch.Tensor`

Integer tensor of shape \[...].

---

**`chunk_size`** `int` — default: \_PROBABILITY_CHUNK_TOKENS

Slots per chunk.

---

**Returns:** `torch.Tensor`

Tensor of shape \[...].

```python
nemo_automodel.components.speculative.dfly2.loss.compute_dfly2_loss(
    outputs: nemo_automodel.components.speculative.dspark.common.DSparkForwardOutput,
    dpace_alpha: float,
    lk_eta: float,
    confidence_head_alpha: float
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]
```

Compute the DFly2 objective and its logged terms for one micro-batch.

**Parameters:**

**`outputs`** `DSparkForwardOutput`

Draft outputs over the drafted slots only: `draft_logits` and
`aligned_target_logits` of shape \[batch, num_anchors, drafted, vocab],
`target_ids` and `eval_mask` of shape \[batch, num_anchors, drafted],
`block_keep_mask` of shape \[batch, num_anchors], and an optional
`confidence_pred` of shape \[batch, num_anchors, drafted].

---

**`dpace_alpha`** `float`

D-PACE smoothing in `[0, 1]`.

---

**`lk_eta`** `float`

Sharpness of the LK mixing weight; larger values switch to TV sooner.

---

**`confidence_head_alpha`** `float`

Weight of the confidence loss; ignored without a head.

---

**Returns:** `torch.Tensor`

The backward loss (scaled by the data-parallel world size, see the module

**Raises:**

* `ValueError`: `aligned_target_logits` is missing.

```python
nemo_automodel.components.speculative.dfly2.loss._PROBABILITY_CHUNK_TOKENS = 128
```