Skip to content
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
4de7e0c
feat(speculative): add dfly2 draft training for deepseek v4.1
kashif Nov 27, 2026
7651ce3
fix(speculative): export a hf config for the dfly2 draft
kashif Nov 27, 2026
4035067
test(speculative): drop plumbing-only dfly2 tests
kashif Nov 27, 2026
0612838
fix(speculative): address dfly2 review findings
kashif Nov 28, 2026
11dc847
test(speculative): pin dfly2 read rows, bf16 fsdp and consolidated save
kashif Nov 28, 2026
85eceb9
docs(speculative): align dfly2 guide and example with the recipe
kashif Nov 28, 2026
e52f1ee
fix(speculative): record dfly2 provenance, check fsdp expert split
kashif Nov 28, 2026
90e733c
test(speculative): restore dfly2 init coverage, check required reads
kashif Nov 28, 2026
8d33349
docs(speculative): note the dfly2 rank count rule
kashif Nov 28, 2026
16170da
fix(speculative): keep dfly2 router bias fp32, skip rank check withou…
kashif Nov 29, 2026
d9633a7
test(speculative): tighten dfly2 init, bf16 and rank check tests
kashif Nov 29, 2026
800ed14
Merge remote-tracking branch 'upstream/main' into kashif/feat/dfly2-d…
kashif Nov 29, 2026
77ff201
fix(speculative): drop dfly2 rank check now that main maps chunked sh…
kashif Nov 29, 2026
e73bd22
test(speculative): pin dfly2 router bias warm start and chunked ce
kashif Nov 29, 2026
108e5a7
style(speculative): annotate dfly2 return types, drop unused test setup
kashif Dec 1, 2026
320033d
test(speculative): share dfly2 test helpers
kashif Dec 1, 2026
dc6e543
test(speculative): pass module pairs to dfly2 copy check
HuiyingLi Dec 2, 2026
ddfed8b
test(speculative): enable compile in dfly2 fsdp test workers
HuiyingLi Dec 2, 2026
f53116e
Merge remote-tracking branch 'origin/main' into pr4971-work
HuiyingLi Dec 2, 2026
17fc88c
Merge branch 'main' into kashif/feat/dfly2-drafter
HuiyingLi Dec 2, 2026
ba1f503
docs(speculative): apply tech pubs edits to dfly2 and speculative docs
HuiyingLi Dec 2, 2026
5529937
Merge remote-tracking branch 'origin/main' into pr4971-work
HuiyingLi Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/fern/versions/nightly.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1115,6 +1115,9 @@ navigation:
- page: "Train a DSpark Drafter for Speculative Decoding"
path: ../../guides/speculative/dspark.mdx
slug: dspark-speculative-decoding
- page: "Train a DFly2 Drafter for Speculative Decoding"
path: ../../guides/speculative/dfly2.mdx
slug: dfly2-speculative-decoding
- page: "Finetune a Model's Native MTP Head for Speculative Decoding"
path: ../../guides/speculative/mtp.mdx
slug: mtp-speculative-decoding
Expand Down
111 changes: 111 additions & 0 deletions docs/guides/speculative/dfly2.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
---
title: "Train a DFly2 Drafter for Speculative Decoding"
description: "Train a DFly2 block-parallel speculative-decoding drafter for DeepSeek-V4.1-Flash with NeMo AutoModel, reading the target's own sparse-attention keys."
---

This guide shows you how to train a DFly2 speculative-decoding drafter for
DeepSeek-V4.1-Flash with [NeMo AutoModel](https://github.com/NVIDIA-NeMo/Automodel).

## What is DFly2?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
## What is DFly2?
## What Is DFly2?


[DFly2](https://arxiv.org/abs/2611.34776) is a block-parallel drafter for
sparse-attention targets. Each draft layer is paired with one of the target's
sparse-attention layers and owns no context projection of its own:

- **KV sharing**: the draft layer reads the keys its paired target layer

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
- **KV sharing**: the draft layer reads the keys its paired target layer
- **KV sharing**: The draft layer reads the keys its paired target layer

attends over, so the served drafter keeps no KV cache of its own.
- **Index sharing**: it reads them at the positions that layer attends from the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
- **Index sharing**: it reads them at the positions that layer attends from the
- **Index sharing**: It reads them at the positions that layer attends from the

row before the block's anchor, so the drafter runs no indexer and its context
read has a fixed size at any context length.

On DeepSeek-V4.1-Flash the paired layers are the ratio-1 layers 28, 32, and 36.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
On DeepSeek-V4.1-Flash the paired layers are the ratio-1 layers 28, 32, and 36.
On DeepSeek-V4.1-Flash, the paired layers are the ratio-1 layers 28, 32, and 36.

Each one attends over its own 128-token sliding window plus the shared global
latents at its indexer's top-512 picks. Around the backbone, the target's final
hidden state is fused into the anchor slot, and a hidden correction (a SwiGLU
plus an attentive correction over the last layer's context and the block's
prefix) adjusts every slot before the frozen LM head. A block of `block_size`
slots holds the anchor and drafts `block_size - 1` tokens.

The draft shares and freezes the target's embedding and LM head. The recipe,
`TrainDFly2Recipe`, reuses the DSpark recipe's frozen EP/FSDP2 target, anchor

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
`TrainDFly2Recipe`, reuses the DSpark recipe's frozen EP/FSDP2 target, anchor
`TrainDFly2Recipe`, reuses the DSpark recipe's frozen EP and FSDP2 target, anchor

sampling, gradient accumulation, metrics, and checkpointing.

## Objective

Each drafted slot is trained toward the target's distribution at the token
before its label:

| Term | Meaning |
|------|---------|
| LK distillation | `lambda * KL + (1 - lambda) * TV` with `lambda = exp(-lk_eta * (1 - TV))`: distills while the draft is far from the target, then optimizes the acceptance probability `1 - TV` |
| D-PACE weights (`dpace_alpha`, default 0.5) | detached per-slot weights from the draft's confidence on the corpus token, emphasizing the slots that decide the accepted length |
| `L_conf` (`confidence_head_alpha`, default 0.0) | optional BCE training a confidence head, on the detached final-normalized states, against the slot's acceptance probability |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
| `L_conf` (`confidence_head_alpha`, default 0.0) | optional BCE training a confidence head, on the detached final-normalized states, against the slot's acceptance probability |
| `L_conf` (`confidence_head_alpha`, default 0.0) | optional binary cross-entropy (BCE) training a confidence head, on the detached final-normalized states, against the slot's acceptance probability |


The logs report the corpus cross entropy (`ce`), the TV term (`tv`), the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
The logs report the corpus cross entropy (`ce`), the TV term (`tv`), the
The logs report the corpus cross-entropy (`ce`), the TV term (`tv`), the

per-position acceptance `accept_rate@k`, and the expected accepted block length
`tau`.

As in the DSpark recipe, a block is supervised up to its first unsupervised label,
and the D-PACE weights ignore slots past the end of the sequence.

## Data

Use a chat dataset of OpenAI-format `messages` rows with the responses
regenerated by the target model, as for DSpark: training is teacher-forced, and
regenerating avoids a training and inference distribution mismatch. Point
`recipe_args.train_data_path` at the dataset and set `chat_template` to the
target's training template.

## Train

The example configuration follows the released
[AngelSlim/DS-V4.1-Flash-DFly2-B6](https://huggingface.co/AngelSlim/DS-V4.1-Flash-DFly2-B6)
layout. Launch the same command on every node, varying `--node-rank`:

```bash
torchrun --nnodes=16 --node-rank=0 --nproc_per_node=4 \
--master-addr=<NODE0_IP> --master-port=29500 \
-m nemo_automodel.recipes.speculative_decoding.train_dfly2 \
-c examples/speculative/dfly2/deepseek_v41_flash_dfly2.yaml
```

The key settings in `recipe_args` are:

| Key | Value | Meaning |
|-----|-------|---------|
| `target_layer_ids` | `[28, 32, 36]` | paired ratio-1 target layers, one per draft layer |
| `block_size` | `6` | slots per block: the anchor plus five drafted tokens |
| `mask_token_id` | `128799` | token filling the non-anchor slots |
| `draft_attn_backend` | `tilelang` | the sparse kernel reads each key list directly; `sdpa` builds a dense mask and suits only short rows |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
| `draft_attn_backend` | `tilelang` | the sparse kernel reads each key list directly; `sdpa` builds a dense mask and suits only short rows |
| `draft_attn_backend` | `tilelang` | the sparse kernel reads each key list directly, while `sdpa` builds a dense mask and suits only short rows |

| `draft_weights_path` | unset | warm-start every draft weight from a released draft or an earlier run |

Without `draft_weights_path`, each draft layer's attention, norms, mHC mixes, and
shared expert start from its paired target layer. The routed experts and the router
start fresh, where the paper draws 128 of the paired layer's experts with their router
rows (its "attention only" ablation reaches 3.51 instead of 3.57 accepted tokens). A
warm start checks the paired layers, block size, and mask token recorded in the
checkpoint's `config.json` against the run's.

The example trains with AdamW and FP32 master weights at a global batch of 256
sequences; the paper uses Muon. Its learning rate is for a fresh draft: when
warm-starting from the released draft, lower it (for example to `5.0e-6`), or the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
sequences; the paper uses Muon. Its learning rate is for a fresh draft: when
warm-starting from the released draft, lower it (for example to `5.0e-6`), or the
sequences. The paper uses Muon. Its learning rate is for a fresh draft: when
warm-starting from the released draft, lower it (for example, to `5.0e-6`), or the

first steps move the converged draft away from its optimum.

<Note>
The number of ranks must split the draft's 128 routed experts the way its checkpoint
expects: FSDP2 shards them like `torch.chunk`, the export expects an even split. Of the
rank counts from 12 to 128 that divide the target's 384 experts, only 16, 32, 64, and
128 qualify; setup refuses the others rather than hang at the first checkpoint.
</Note>

<Note>
The DFly2 path trains against a colocated text target on unpacked rows. Sequence
packing, image inputs, the precomputed and remote target backends, and TP, PP,
and CP are not supported.
</Note>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
</Note>
</Note>


## Checkpoints

Consolidated checkpoints use the released layout (`model.layers.*`,
`model.mtp_fusion.*`, `model.hidden_correction.*`), so a trained draft and the
released one load the same way.
1 change: 1 addition & 0 deletions docs/repository-structure.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ $ tree -L 2 nemo_automodel/recipes/
│ ├── serve_dspark_target.py - DSpark remote target server.
│ ├── train_dflash.py - DFlash speculative training.
│ ├── train_dflash2.py - DFlash 2 speculative training.
│ ├── train_dfly2.py - DFly2 speculative training.
│ ├── train_domino.py - Domino speculative training.
│ ├── train_dspark.py - DSpark speculative training.
│ ├── train_eagle1.py - EAGLE-1 speculative training.
Expand Down
7 changes: 7 additions & 0 deletions examples/speculative/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ inference engine (SGLang or vLLM). The training code lives in
| **Domino** | DFlash backbone plus a serial GRU correction head (`prefix_gru` / `embed_proj`) that refines each block position on the previous ones. | `TrainDominoRecipe` | `dflash/qwen3_domino.yaml` |
| **JetSpec** | DFlash backbone trained as a *causal* parallel tree drafter: causal in-block attention plus forward-KL distillation against the target distribution. | `TrainJetSpecRecipe` | `jetspec/` |
| **DSpark** | Semi-autoregressive parallel drafting: a parallel backbone drafts the block, a lightweight serial Markov head adds intra-block dependency, and a confidence head predicts per-position acceptance. | `TrainDSparkRecipe` | `dspark/` |
| **DFly2** | Block-parallel drafting for sparse-attention targets: each draft layer reads its paired target layer's cached keys at the positions that layer's indexer selected, so the drafter keeps no KV cache and runs no indexer of its own. | `TrainDFly2Recipe` | `dfly2/` |

EAGLE-1, EAGLE-2, and EAGLE-3 keep their separate code paths: `*_v12.py` files are the **EAGLE-1 and EAGLE-2**
(v1 and v2) implementation. The unsuffixed files are the EAGLE-3 and EAGLE-3.1 path. Inside
Expand Down Expand Up @@ -90,6 +91,10 @@ The shipped example configs only cover a subset.
multimodal data path through `recipe_args.multimodal: true`). MiniMax-M3.1-Flash
ships `dspark/config.json`, so its draft follows that contract and exports the
released layout (`dspark/minimax_m3_1_flash_dspark.yaml`).
- **DFly2**: DeepSeek-V4.1-Flash (`DeepseekV41ForCausalLM`), following the released
`AngelSlim/DS-V4.1-Flash-DFly2-B6` layout (`dfly2/deepseek_v41_flash_dfly2.yaml`). The
draft is model-owned: the target pairs its ratio-1 sparse layers with the draft layers and
exposes their cached keys and key lists. Colocated, unpacked, text-only targets only.

Qwen3-MoE is handled exactly like a dense target: the draft only consumes
post-block hidden states, never per-expert routing. gpt-oss uses a dedicated
Expand Down Expand Up @@ -140,6 +145,7 @@ Select them in the config. All degrade gracefully when a dependency is missing.
| P-EAGLE | `flex_attention` (compiled when CUDA + head_dim ≥ 16, else eager flex) | automatic |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
| P-EAGLE | `flex_attention` (compiled when CUDA + head_dim ≥ 16, else eager flex) | automatic |
| P-EAGLE | `flex_attention` (compiled when CUDA and head_dim ≥ 16, else eager flex) | automatic |

| DFlash / DFlash 2 / Domino / JetSpec | `flex_attention`, `sdpa` | `recipe_args.attention_backend` (default `flex_attention`) |
| DSpark | `flex_attention` (Qwen3 / Gemma4 / MiniMax M3 drafts), `sdpa` (V4 / GLM MLA drafts, fixed) | `recipe_args.attention_backend` |
| DFly2 | `tilelang`, `cudnn` (sparse key lists, needed for long rows), `sdpa`, `eager` (dense mask, short rows) | `recipe_args.draft_attn_backend` (default `sdpa`) |

For EAGLE-3, FlashAttention-2 is real FA2 over the TTT attention pattern: FA2
computes the `T×T` causal block and returns `softmax_lse`, and the diagonal
Expand Down Expand Up @@ -623,6 +629,7 @@ such caveat.
| DFlash 2 | not yet wired here (`--speculative-algorithm DFLASH` upstream) | not yet wired here (`dflash` method upstream) |
| Domino | no | no (the GRU correction head has no engine runtime) |
| DSpark | no | not yet (runtime in development upstream, unreleased) |
| DFly2 | no | not yet (runtime in development upstream, unreleased) |

`serve_sglang.py` rejects P-EAGLE drafts with an actionable error. Serve those on
vLLM.
Expand Down
151 changes: 151 additions & 0 deletions examples/speculative/dfly2/deepseek_v41_flash_dfly2.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
# DFly2 draft training for DeepSeek-V4.1-Flash.
#
# The draft follows the released AngelSlim/DS-V4.1-Flash-DFly2-B6 layout: three
# latent-MQA + MoE + mHC draft layers, each paired with one of the target's
# ratio-1 sparse-attention layers 28/32/36. A draft layer reads that layer's own
# keys (its sliding window plus the shared 1:1 global latents) at the slots the
# layer attends from the row before the anchor, so the served draft shares the
# target's KV cache and indexer. Blocks of 6 slots draft 5 tokens; the target's
# last hidden state is fused into the anchor slot, and a hidden correction with
# an attentive correction adjusts every slot before the frozen LM head.
#
# The draft layers start from their paired target layers (attention, norms, mHC
# mixes and shared expert); the routed experts and the router start fresh. Set recipe_args.draft_weights_path
# to warm-start every draft weight from the released checkpoint instead. Use
# restore_from below to resume an AutoModel DFly2 training checkpoint.
#
# The frozen 40-layer target and its 384 experts are sharded with EP/FSDP2; the
# draft is independently FSDP2-sharded and is the only trainable model. TP, PP,
# CP, sequence packing, image inputs, and the precomputed or remote target
# backends are not supported by the DFly2 training path.
#
# This is a production-scale configuration. Adapt the node count, EP size,
# accumulation, data paths, and checkpoint path to the cluster. EP size must
# divide the target's 384 routed experts, and the number of ranks must split the
# draft's 128 routed experts the way its checkpoint expects: of the rank counts
# from 12 to 128 that divide 384, only 16, 32, 64 and 128 do (setup refuses the
# others rather than hang at the first checkpoint).
#
# Launch the same command on every node and vary --node-rank:
# torchrun --nnodes=16 --node-rank=0 --nproc_per_node=4 \
# --master-addr=<NODE0_IP> --master-port=29500 \
# -m nemo_automodel.recipes.speculative_decoding.train_dfly2 \
# -c examples/speculative/dfly2/deepseek_v41_flash_dfly2.yaml

recipe: TrainDFly2Recipe

dist_env:
backend: nccl
timeout_minutes: 120

wandb:
enable: false # opt-in: flip to true to log this run (needs W&B credentials)
project: deepseek-v41-dfly2
tags: [dfly2, deepseek-v41-flash, hybridep]

distributed:
strategy: fsdp2
defer_fsdp_grad_sync: true
tp_size: 1
cp_size: 1
pp_size: 1
ep_size: 64
activation_checkpointing: true
moe:
reshard_after_forward: true
wrap_outer_model: true
lm_head_precision: float32
mp_policy:
_target_: torch.distributed.fsdp.MixedPrecisionPolicy
param_dtype: bfloat16
reduce_dtype: float32
output_dtype: null
cast_forward_inputs: false

recipe_args:
target_model_name_or_path: deepseek-ai/DeepSeek-V4.1-Flash
# Or a local path to a downloaded V4.1-Flash checkpoint:
# target_model_name_or_path: /path/to/DeepSeek-V4.1-Flash
# Start every draft weight from the released DFly2 draft:
# draft_weights_path: /path/to/DS-V4.1-Flash-DFly2-B6
train_data_path: /path/to/open-perfectblend-regenerated
train_split: "train[4096:]"
val_data_path: /path/to/open-perfectblend-regenerated
val_split: "train[:4096]"
output_dir: ./outputs/dfly2_deepseek_v41_flash
seq_length: 32768
micro_batch_size: 1
# 64 ranks (the launch line above) x 1 x 4 = 256 sequences per update, the paper's global batch.
grad_accumulation_steps: 4
num_workers: 2
num_epochs: 3
ckpt_every_steps: 500
save_checkpoint_every_epoch: true

# --- chat template ---
# The released chat_template.jinja plus {% generation %} loss spans, defaulting
# to chat mode. For thinking-mode data, uncomment chat_template_kwargs.
chat_template: examples/llm_finetune/deepseek_v41/deepseek_v41_flash_training_chat_template.jinja
# chat_template_kwargs: {thinking_mode: thinking}

# --- released DFly2 architecture ---
# One draft layer per paired ratio-1 target layer.
target_layer_ids: [28, 32, 36]
block_size: 6
num_anchors: 512
mask_token_id: 128799
freeze_embeddings: true
# The sparse kernel reads each query's key list directly; SDPA would build a
# dense mask over the whole 32K-row context.
draft_attn_backend: tilelang

# --- objective: D-PACE-weighted LK distillation + confidence ---
dpace_alpha: 0.5
lk_eta: 3.0
# The released draft has no confidence head; a positive weight adds one, trained
# on the detached final-normalized draft states (confidence_head_stop_gradient).
confidence_head_alpha: 0.0

# --- frozen DeepSeek V4.1 target backend ---
target_attn_backend: tilelang
target_dispatcher: hybridep
target_experts: torch_mm
target_enable_fsdp_optimizations: true

trust_remote_code: false
shuffle_seed: 42
log_every_steps: 10
max_grad_norm: 1.0

# FP32 master weights: the draft is stored in BF16, where small updates to norm gains and
# other near-unit parameters round away. The paper trains with Muon (Section 5.1); this
# example uses AdamW. When warm-starting from the released draft through
# draft_weights_path, lower lr (for example to 5.0e-6): the peak below is for a fresh draft
# and moves a converged one away from its optimum within a few steps.
optimizer:
_target_: transformer_engine.pytorch.optimizers.fused_adam.FusedAdam
lr: 5.0e-4
betas: [0.9, 0.95]
eps: 1.0e-8
weight_decay: 0.0
adam_w_mode: true
bias_correction: true
master_weights: true
master_weight_dtype: torch.float32
store_param_remainders: true
exp_avg_dtype: torch.float32
exp_avg_sq_dtype: torch.float32
warmup_ratio: 0.04
min_lr_ratio: 0.1

checkpoint:
enabled: true
checkpoint_dir: ./outputs/dfly2_deepseek_v41_flash/checkpoints
model_save_format: safetensors
save_consolidated: final
dequantize_base_checkpoint: true
# restore_from: LATEST

ci:
nemo_ci_schedule: skipped
cluster_tag: h100
Loading
Loading