Repository navigation
feat(speculative): add dfly2 draft training for deepseek v4.1 #4971
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 11 commits
4de7e0c
7651ce3
4035067
0612838
11dc847
85eceb9
e52f1ee
90e733c
8d33349
16170da
d9633a7
800ed14
77ff201
e73bd22
108e5a7
320033d
dc6e543
ddfed8b
f53116e
17fc88c
ba1f503
5529937
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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? | ||||||||||
|
|
||||||||||
| [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 | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
| 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 | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
| 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. | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
| 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 | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
| 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 | | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
| 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 | | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
| | `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 | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
| 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> | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
|
||||||||||
| ## 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. | ||||||||||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -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 | ||||||
|
|
@@ -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 | ||||||
|
|
@@ -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 | | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| | 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 | ||||||
|
|
@@ -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. | ||||||
|
|
||||||
| 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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.