diff --git a/docs/fern/versions/nightly.yml b/docs/fern/versions/nightly.yml index 6e437ec5e4..1e11411697 100644 --- a/docs/fern/versions/nightly.yml +++ b/docs/fern/versions/nightly.yml @@ -1124,6 +1124,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 diff --git a/docs/guides/speculative/dfly2.mdx b/docs/guides/speculative/dfly2.mdx new file mode 100644 index 0000000000..a8e1d260fd --- /dev/null +++ b/docs/guides/speculative/dfly2.mdx @@ -0,0 +1,105 @@ +--- +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 + 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 + 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. +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 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 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 +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= --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, 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 +first steps move the converged draft away from its optimum. + + +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. + + + +## 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. diff --git a/docs/repository-structure.mdx b/docs/repository-structure.mdx index 48ecdc1c84..b81108fe7c 100644 --- a/docs/repository-structure.mdx +++ b/docs/repository-structure.mdx @@ -1,12 +1,14 @@ --- title: "Repository Structure" -description: "" +description: "Learn how the NeMo AutoModel repository is organized into components, recipes, and CLI directories, and how they fit together." position: 6 --- This introductory guide presents the structure of the NeMo AutoModel repository, provides a brief overview of its parts, introduces concepts such as components and recipes, and explains how everything fits together. -## What is NeMo AutoModel? +## What Is NeMo AutoModel? + NeMo AutoModel is a PyTorch library for fine-tuning and pretraining large-scale models. In particular, it provides: + - **Optimized implementations** for training efficiency, including fused kernels and memory-saving techniques. - [**Day-0 support**](/model-coverage/overview) for LLMs and VLMs available on the Hugging Face Hub. - **Seamless integration** with Hugging Face datasets, tokenizers, and related tools. @@ -14,18 +16,23 @@ NeMo AutoModel is a PyTorch library for fine-tuning and pretraining large-scale - **End-to-end workflows** with recipes for data preparation, training, and evaluation. ## Repository Structure + The AutoModel source code is available under the [`nemo_automodel`](https://github.com/NVIDIA-NeMo/Automodel/tree/main/nemo_automodel) directory. It is organized into three directories: -- [`components/`](https://github.com/NVIDIA-NeMo/Automodel/tree/main/nemo_automodel/components) - Self-contained modules + +- [`components/`](https://github.com/NVIDIA-NeMo/Automodel/tree/main/nemo_automodel/components) - Self-contained modules - [`recipes/`](https://github.com/NVIDIA-NeMo/Automodel/tree/main/nemo_automodel/recipes) - End-to-end training workflows -- [`cli/`](https://github.com/NVIDIA-NeMo/Automodel/tree/main/nemo_automodel/cli) - CLI entry-point and job launcher dispatch. +- [`cli/`](https://github.com/NVIDIA-NeMo/Automodel/tree/main/nemo_automodel/cli) - CLI entry point and job launcher dispatch ### Components Directory + The `components/` directory contains isolated modules used in training loops. Each component is designed to be dependency-light and reusable without cross-module imports. #### Directory Structure + The following directory listing shows all components along with explanations of their contents. -``` + +```text $ tree -L 1 nemo_automodel/components/ ├── _peft/ - Implementations of PEFT methods, such as LoRA. @@ -49,17 +56,23 @@ $ tree -L 1 nemo_automodel/components/ ``` #### Key Features + +Components have the following characteristics: + - Each component can be used independently in other projects. - Each component has its own dependencies, without cross-module imports. - Unit tests are colocated with the component they cover. ### Recipes Directory + Recipes define **end-to-end workflows** (data and model loading → training with custom loop → saving the output checkpoint) for a variety of tasks, such as training, fine-tuning, and knowledge distillation. #### Available Recipes + The following directory listing shows the top-level recipe domains and their non-private Python modules. Package initializers and underscore-prefixed support modules are omitted. -``` + +```text $ tree -L 2 nemo_automodel/recipes/ ├── diffusion/ │ └── train.py - Diffusion training. @@ -84,6 +97,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. @@ -98,26 +112,31 @@ $ tree -L 2 nemo_automodel/recipes/ #### Run a Recipe -Recipes are launched via the `automodel` CLI: +Recipes are launched using the `automodel` CLI: + ```bash automodel --nproc-per-node 2 examples/llm_finetune/llama3_2/llama3_2_1b_squad.yaml ``` -The above command will fine-tune the Llama3.2-1B model on the SQuAD dataset with two GPUs using the [`llama3_2_1b_squad.yaml`](https://github.com/NVIDIA-NeMo/Automodel/blob/main/examples/llm_finetune/llama3_2/llama3_2_1b_squad.yaml) config. +This command fine-tunes the Llama3.2-1B model on the SQuAD dataset with 2 GPUs using the [`llama3_2_1b_squad.yaml`](https://github.com/NVIDIA-NeMo/Automodel/blob/main/examples/llm_finetune/llama3_2/llama3_2_1b_squad.yaml) config. For a single-GPU run, omit `--nproc-per-node`: + ```bash automodel examples/llm_finetune/llama3_2/llama3_2_1b_squad.yaml ``` Each recipe imports the components it needs from the `nemo_automodel/components/` catalog. -The recipe/components structure enables you to: +The recipe and component structure enables you to: + - Decouple individual components and replace them with custom implementations when needed. - Avoid rigid, class-based trainer structures by using linear scripts that expose training logic for maximum flexibility and control. {/* For an in-depth explanation of the LLM recipe please also see the [LLM recipe deep-dive guide](https://github.com/NVIDIA-NeMo/Automodel/blob/main/docs/llm_recipe_deep_dive). */} #### Configure a Recipe -An example YAML configuration is shown below. The complete config is available [here](https://github.com/NVIDIA-NeMo/Automodel/blob/main/examples/llm_finetune/llama3_2/llama3_2_1b_squad.yaml): + +An example YAML configuration is shown below. The complete config is available in [`llama3_2_1b_squad.yaml`](https://github.com/NVIDIA-NeMo/Automodel/blob/main/examples/llm_finetune/llama3_2/llama3_2_1b_squad.yaml): + ```yaml recipe: TrainFinetuneRecipeForNextTokenPrediction @@ -141,14 +160,16 @@ dataset: More recipe examples are available under the [`examples/`](https://github.com/NVIDIA-NeMo/Automodel/tree/main/examples) directory. ### CLI Directory (`nemo_automodel/cli/`) + The `automodel` (or `am`) CLI application simplifies job execution across different environments, from single-GPU interactive sessions to batch multi-node runs. It dispatches interactive (local), SkyPilot, -and NeMo-Run launchers; Slurm jobs are submitted with `sbatch` scripts directly. The installed CLI +and NeMo Run launchers. Slurm jobs are submitted with `sbatch` scripts directly. The installed CLI implementation lives in `nemo_automodel/cli/`, and both console scripts resolve to `nemo_automodel.cli.app:main`. ## Next Steps Learn how to train models with NeMo AutoModel on: -- **Your local workstation**: See [`docs/launcher/local-workstation.mdx`](/job-launchers/local-workstation). -- **A cluster**: See [`docs/launcher/slurm.mdx`](/job-launchers/slurm-cluster). + +- **Your local workstation**: Refer to [`docs/launcher/local-workstation.mdx`](/job-launchers/local-workstation). +- **A cluster**: Refer to [`docs/launcher/slurm.mdx`](/job-launchers/slurm-cluster). diff --git a/examples/speculative/README.md b/examples/speculative/README.md index b8de4ee4e2..730b35c7f2 100644 --- a/examples/speculative/README.md +++ b/examples/speculative/README.md @@ -1,6 +1,6 @@ # Train Draft Models for Speculative Decoding in NeMo AutoModel -This directory trains the **draft models** used for speculative decoding. A draft +This directory trains the **draft models** used for speculative decoding in NeMo AutoModel. A draft proposes several future tokens cheaply, the frozen **target** model verifies them in one forward pass, and every accepted token is a step the target never had to run autoregressively. The faster and more accurate the draft, the higher the @@ -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 @@ -54,7 +55,7 @@ registry (`eagle/registry.py`, `dflash/registry.py`, `dspark/registry.py`). Capability is per registry, not per (method, target) pair: the EAGLE-3.1 (`fc_norm` and `norm_output`) and P-EAGLE (`parallel_drafting`) toggles ride on the same EAGLE-3 dense draft, so they apply to any target the EAGLE-3 registry maps. -The shipped example configs only cover a subset. +The shipped example configs only cover a subset. The following list shows the target architectures that each method supports: - **EAGLE-1, EAGLE-2, and EAGLE-3 (and the EAGLE-3.1 and P-EAGLE toggles on top of EAGLE-3)**: `LlamaForCausalLM`, `Phi3ForCausalLM`, `Qwen3ForCausalLM`, `Qwen3MoeForCausalLM`. @@ -75,14 +76,14 @@ The shipped example configs only cover a subset. - **DFlash, DFlash 2, Domino, and JetSpec**: `Qwen3ForCausalLM`, `Qwen3MoeForCausalLM`, `Qwen3_5ForCausalLM`, `Qwen3_5ForConditionalGeneration`, `Qwen3_5MoeForCausalLM`, `Qwen3_5MoeForConditionalGeneration` (the Qwen3.5 family, which `Qwen/Qwen3.8-27B` - belongs to; its decoder config is read from the nested `text_config`). All + belongs to, and its decoder config is read from the nested `text_config`). All DFlash-family recipes reject `distributed.pp_size > 1`: online hidden-state capture hooks one complete, non-pipelined target forward. - **DFlash on Kimi K3** (`KimiK3ForCausalLM`, `KimiK3ForConditionalGeneration`): using a dedicated dense MLA draft class. Plain DFlash only (Domino's projector head is Qwen3-only, and there is no DFlash 2 draft for it), and it requires `attention_backend: sdpa`. Sequence packing and context parallelism are - rejected, because K3 owns both itself. See `dflash/README-kimi-k3.md`. + rejected, because K3 owns both itself. Refer to `dflash/README-kimi-k3.md`. - **DSpark**: `Qwen3ForCausalLM`, `Qwen3MoeForCausalLM`, `DeepseekV4ForCausalLM`, GLM-5.2 (`GlmMoeDsaForCausalLM`), Gemma4 (`Gemma4ForConditionalGeneration`, `Gemma4UnifiedForConditionalGeneration`), @@ -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 @@ -137,9 +142,10 @@ Select them in the config. All degrade gracefully when a dependency is missing. |---|---|---| | EAGLE-3 / 3.1 | `eager`, `flash_attention_2` | `recipe_args.draft_attn_implementation` (default `eager`) | | EAGLE-1/2 | `eager` only | n/a | -| 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 @@ -161,9 +167,9 @@ normalizes by valid-position count. ### Draft-Vocab Compression (d2t and t2d) EAGLE-3 can shrink the draft `lm_head` to `draft_vocab_size < target_vocab_size`. -Training carries two tensors: `selected_token_ids` (draft index to target id, the -"d2t" direction) and `selected_token_mask` (a boolean membership mask over the -full target vocab, the "t2d" direction). The mapping is built and cached by +Training carries two tensors: `selected_token_ids` (draft index to target ID, the +`d2t` direction) and `selected_token_mask` (a boolean membership mask over the +full target vocab, the `t2d` direction). The mapping is built and cached by `components/datasets/llm/eagle3.py`. Set `recipe_args.draft_vocab_size` to enable, or point `recipe_args.selected_token_ids_path` at a precomputed map. `t2d` is unset when the draft vocab is uncompressed. @@ -171,17 +177,17 @@ unset when the draft vocab is uncompressed. ### FP8 Draft Training All spec-decode recipes (EAGLE-1/2, EAGLE-3, P-EAGLE, DFlash, Domino, -JetSpec, and DSpark) accept the same top-level `fp8:` block as the SFT recipes (see +JetSpec, and DSpark) accept the same top-level `fp8:` block as the SFT recipes (refer to `components/quantization/fp8.py`). When enabled, the draft's `nn.Linear` layers are swapped to torchao `Float8Linear` before the DDP or FSDP2 wrap, so the -draft's forward and backward GEMMs run in FP8. Requires SM89+ (H100 or newer); +draft's forward and backward GEMMs run in FP8. Requires SM89+ (H100 or newer). `emulate: true` runs the FP8 numerics on older GPUs for testing. The frozen target model is never converted (it already supports FP8-quantized checkpoints through dequant-on-load in the DSpark V4 and GLM paths). Linears with a weight dim not divisible by 16 are skipped automatically. Use `filter_fqns` to exclude more (for example, `["lm_head"]`). On DSpark's FSDP2 path, `enable_fsdp_float8_all_gather` and `precompute_float8_dynamic_scale_for_fsdp` reduce the cost of computing -scales at each step. The SFT recipes use the same optimization. See +scales at each step. The SFT recipes use the same optimization. Refer to `eagle3/qwen3_eagle3_fp8.yaml`. **Pair `fp8:` with `compile:`.** The recipes also accept the SFT recipes' @@ -228,7 +234,7 @@ target distribution). EAGLE-3 supports three ways to run it. | Backend | `recipe_args.target_model_backend` | When to Use | |---|---|---| | **Co-located (default)** | `colocated` | Target and draft share the same GPUs. Simplest, default for every config. | -| **Remote** | `remote` | Target served on separate GPUs/host. Training streams supervision over HTTP (control) and NCCL (data, with a binary wire fallback). Numerically identical to co-located. | +| **Remote** | `remote` | Target served on separate GPUs or hosts. Training streams supervision over HTTP (control) and NCCL (data, with a binary wire fallback). Numerically identical to co-located. | | **Offline cache** | set `cached_target_path` | Precompute target outputs once to disk, then train without the target loaded. Disk-heavy and largely superseded by the remote backend. | Remote serving (`eagle3/llama_eagle3_remote.yaml`): start a server first, then @@ -285,10 +291,10 @@ in the same directory. After precompute finishes, set DSpark supports the co-located and remote backends too. Its remote server, `serve_dspark_target`, reads the same YAML as the training run, so both sides -load the same target and capture layers; at setup the trainer still checks the +load the same target and capture layers. At setup, the trainer still checks the served layer count, hidden size, vocab size, and `target_layer_ids` against its config. The server captures the features with the same code as the co-located -path, so training is numerically unchanged. See +path, so training is numerically unchanged. Refer to `dspark/qwen3_0.6b_dspark_remote.yaml`: ```bash @@ -311,7 +317,7 @@ The loss-mask options live under `recipe_args` in the speculative recipes (not u `mask_generation_prompt` drops the prefix of each assistant turn that the chat template's generation prompt supplies at inference (the role header and any empty reasoning block such as the `\n\n\n\n` Qwen3 inserts). Only a generation prompt the template appends to the -unchanged conversation prefix, and that the rendered turn reproduces in full, is removed; anything +unchanged conversation prefix, and that the rendered turn reproduces in full, is removed. Anything else leaves the turn supervised. Both default to `false`. The offline cache stores the loss mask, so a cache is tied to the options it was produced with: the producer takes the same two flags, records them in the manifest, and the cached trainer refuses to start when the recipe setting @@ -324,7 +330,7 @@ earlier turns the same way as the conversation grows. The stock Qwen3 template ( does not: it drops the `` block from every assistant turn before the last user query, so a multi-turn sample fails while rendering its first assistant turn, whether or not the flags are set. With that template keep the data single-turn (PerfectBlend holds 2–72-turn conversations), -or supply a prefix-stable or `{% generation %}` template; Qwen3-Instruct-2507 renders history +or supply a prefix-stable or `{% generation %}` template. Qwen3-Instruct-2507 renders history stably and needs no filtering. ```python @@ -356,7 +362,7 @@ recipe_args: ``` The online backends (`colocated`, `remote`) need only the `recipe_args` key, under the same -template constraint; see the commented line in `eagle3/qwen3_eagle3_perfectblend.yaml`. +template constraint. Refer to the commented line in `eagle3/qwen3_eagle3_perfectblend.yaml`. For DSpark targets too large to fit on one node (DeepSeek-V4-Flash, GLM-5.2), a **distributed** precompute (`precompute_dspark_dist.py`) loads the target frozen @@ -373,7 +379,7 @@ torchrun --nnodes=4 --node-rank=0 --nproc_per_node=8 \ ``` Then set the matching training config's `recipe_args.cached_target_path` to that -`cache_output_dir` to train the draft with no live target. See +`cache_output_dir` to train the draft with no live target. Refer to `dspark/deepseek_v4_flash_dspark_precompute.yaml` and `dspark/glm_5.2_dspark_precompute.yaml`. @@ -409,7 +415,7 @@ OpenAI-compatible server works too. python -m nemo_automodel.components.speculative.regenerate --input-data Aeala/ShareGPT_Vicuna_unfiltered --output-dir ./regenerated/sharegpt_llama31_8b --target-server http://localhost:30000/v1 --model meta-llama/Llama-3.1-8B-Instruct --concurrency 64 --shard-size 1000 ``` -For each sample the script loads the `messages` column (HF Hub id, local +For each sample the script loads the `messages` column (HF Hub ID, local parquet, or JSON/JSONL, same loader as `ChatDataset`), drops every trailing `assistant` turn while keeping the leading `system`, `user`, and later context (intermediate assistant turns in multi-turn conversations are kept), calls @@ -437,14 +443,14 @@ recipe_args: | Flag | Default | Notes | |---|---|---| -| `--concurrency` | 32 | In-flight requests; raise to saturate the target server. | +| `--concurrency` | 32 | In-flight requests. Raise to saturate the target server. | | `--shard-size` | 1000 | Smaller shards mean more frequent checkpointing and more files. | | `--max-new-tokens` | 1024 | Cap per-answer length. | -| `--temperature` | 0.0 | Greedy by default; drafters are typically trained against argmax answers. | +| `--temperature` | 0.0 | Greedy by default. Drafters are typically trained against argmax answers. | | `--top-p` | 1.0 | Only relevant with `temperature > 0`. | -| `--timeout-s` | 600 | Per-request timeout; bump for very long generations. | +| `--timeout-s` | 600 | Per-request timeout. Bump for very long generations. | | `--max-retries` | 3 | Retries on 5xx, 429, and transport errors with exponential backoff. | -| `--split` | `train` | Supports HF slice syntax, e.g., `train[:10000]`. | +| `--split` | `train` | Supports HF slice syntax, for example, `train[:10000]`. | | `--shuffle-seed` | unset | Optional shuffle before slicing. | ### Regeneration Pitfalls @@ -456,7 +462,7 @@ recipe_args: script retries then fails on the first batch. - **Tokenizer mismatch.** The regenerated dataset is consumed by `ChatDataset`, which applies the target model's chat template at training time. Make sure the - recipe's tokenizer comes from the same model id you used for `--model`, or the + recipe's tokenizer comes from the same model ID you used for `--model`, or the loss-mask alignment silently drifts. Datasets are consumed by `ChatDataset`: a `messages` list of `{role, content}`, @@ -475,10 +481,10 @@ setup rather than training something subtly wrong. | Constraint | Applies To | |---|---| | Cannot combine with sequence packing (`packed_sequence_size > 0`). CP shards the sequence and strips the block-causal mask packing relies on | EAGLE-1/2, EAGLE-3, DFlash, DSpark | -| Co-located target backend only; the remote backend runs the target out-of-process | EAGLE-3 | +| Co-located target backend only. The remote backend runs the target out-of-process | EAGLE-3 | | Cannot combine with tensor parallelism (`tp_size > 1`) | DFlash | | Dense Qwen3-style draft only | DSpark | -| EAGLE-3 draft attention must be the `Eagle3LlamaAttention` ring path; architectures without it (the DeepSeek MLA draft) raise `NotImplementedError` | EAGLE-3 | +| EAGLE-3 draft attention must be the `Eagle3LlamaAttention` ring path. Architectures without it (the DeepSeek MLA draft) raise `NotImplementedError` | EAGLE-3 | ## During-Training Tools (EAGLE-3) @@ -565,9 +571,9 @@ vLLM's registered names, and `--num-speculative-tokens` defaults to `num_depths` resolved `vllm serve` command without launching. DFlash notes: vLLM reserves `1 + K` query tokens per sequence, so a large block size might need a smaller `--max-num-seqs` (forward it through the trailing extra args, for example, -`-- --max-num-seqs 32`); a JetSpec draft carries `dflash_config.causal=true` so +`-- --max-num-seqs 32`). A JetSpec draft carries `dflash_config.causal=true` so vLLM matches its causal in-block attention (pass `--dflash-causal` for -checkpoints trained before the recipe stamped it); Domino drafts are rejected +checkpoints trained before the recipe stamped it). Domino drafts are rejected because their GRU correction head has no vLLM runtime. `bench_vllm.py` measures the same metrics against a running vLLM server, reading @@ -594,11 +600,11 @@ acceptance and speedup on: MT-Bench (first turn), HumanEval (code), GSM8K (math), and Alpaca (single-turn instruction-following). None of these ship a chat-messages column, so each is read through `--prompt-column` (a raw text field wrapped into a fresh single-turn user message) rather than -`--messages-column`; both flags are also available on `bench_sglang.py` +`--messages-column`. Both flags are also available on `bench_sglang.py` and `bench_vllm.py` directly for a single custom dataset. Pass `--engine vllm` to sweep a vLLM server instead, `--baseline-server` for the speedup column, `--datasets ` to run a subset, and `--datasets-config ` to -swap in an entirely custom dataset list (see +swap in an entirely custom dataset list (refer to `bench_sweep/spec_bench_datasets.yaml`, which mirrors the built-in default and doubles as a template). One dataset failing to load or benchmark is reported as an error row and excluded from the aggregate rather than aborting the sweep. @@ -618,11 +624,12 @@ such caveat. |---|---|---| | EAGLE-1/2/3, EAGLE-3.1 | yes | yes | | EAGLE-4 | through the EAGLE-4 engine plugin, after `export_eagle4` (stock SGLang has no EAGLE-4 runtime) | through the EAGLE-4 engine plugin, after `export_eagle4` (stock vLLM has no EAGLE-4 runtime) | -| P-EAGLE | no (tracked upstream) | yes (parallel-drafting runtime, >= 0.16) | -| DFlash, JetSpec | no | yes (`dflash` method, >= 0.20) | +| P-EAGLE | no (tracked upstream) | yes (parallel-drafting runtime, 0.16 or later) | +| DFlash, JetSpec | no | yes (`dflash` method, 0.20 or later) | | 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. @@ -644,9 +651,9 @@ blocks) instead. | `distributed` | Optional; only for MoE / large targets. `strategy: fsdp2`, `tp_size`, `pp_size`, `cp_size`, `ep_size`, `activation_checkpointing`, `sequence_parallel`. Absent means DDP. | | `optimizer` | `lr`, `betas`, `weight_decay`, optional `warmup_ratio` (0.05), `min_lr_ratio` (0.1). | | `checkpoint` | `enabled`, `checkpoint_dir`, `model_save_format: safetensors`, `save_consolidated`, optional `restore_from` (`LATEST` / subdir / path). | -| `fp8` | Optional; torchao FP8 draft training, same surface as the SFT recipes. See [FP8 Draft Training](#fp8-draft-training). | +| `fp8` | Optional; torchao FP8 draft training, same surface as the SFT recipes. Refer to [FP8 Draft Training](#fp8-draft-training). | | `compile` | Optional; in-place torch.compile of the draft (`CompileConfig`). Strongly recommended with `fp8`. | -| `peft` | Optional, EAGLE-3 only; LoRA draft adaptation (`PeftConfig`). See [LoRA Draft Adaptation (EAGLE-3 Only)](#lora-draft-adaptation-eagle-3-only). | +| `peft` | Optional, EAGLE-3 only; LoRA draft adaptation (`PeftConfig`). Refer to [LoRA Draft Adaptation (EAGLE-3 Only)](#lora-draft-adaptation-eagle-3-only). | | `wandb` | Optional; `project`, `entity`, `name`. | ### DFlash-Family Validation Metrics @@ -688,8 +695,8 @@ checkpoint cadence: `ckpt_every_steps`, `save_checkpoint_every_epoch`. | `draft_attn_implementation` | EAGLE-3 | `eager` (default) or `flash_attention_2`. | | `fc_norm`, `norm_output` | EAGLE-3.1 | Both default false; either alone is a valid intermediate config. | | `eagle4.sliding_window`, `eagle4.candidate_head.{rank,num_candidates}` | EAGLE-4 | `candidate_head` selects stage 2 and needs `draft_weights_path`; leave `draft_vocab_size` unset. | -| `draft_weights_path` | EAGLE-3 / DSpark | Warm-start the draft from a consolidated safetensors export (file or directory); required for meaningful LoRA adaptation. DSpark also reads released drafts; see the [DSpark guide](../../docs/guides/speculative/dspark.mdx). | -| `target_model_backend`, `remote_urls`, `remote_timeout`, `remote_max_retries` | EAGLE-3 / DSpark remote | See [Target Backends](#target-backends). `target_prefetch_depth` is EAGLE-3 only. | +| `draft_weights_path` | EAGLE-3 / DSpark | Warm-start the draft from a consolidated safetensors export (file or directory); required for meaningful LoRA adaptation. DSpark also reads released drafts. Refer to the [DSpark guide](../../docs/guides/speculative/dspark.mdx). | +| `target_model_backend`, `remote_urls`, `remote_timeout`, `remote_max_retries` | EAGLE-3 / DSpark remote | Refer to [Target Backends](#target-backends). `target_prefetch_depth` is EAGLE-3 only. | | `cached_target_path` | EAGLE-3 / DSpark offline | Path to a cache produced by `precompute_eagle3.py`, `precompute_dspark.py`, or (large sharded targets) `precompute_dspark_dist.py`. | | `parallel_drafting`, `num_depths`, `num_draft_layers`, `down_sample_ratio`, `down_sample_ratio_min`, `mask_token_id`, `sequence_partitions` | P-EAGLE | `mask_token_id` is required (no default). `sequence_partitions > 1` splits each sequence by dependency lineage to bound long-context memory. | | `block_size`, `num_anchors`, `loss_decay_gamma`, `mask_token_id`, `target_layer_ids`, `attention_backend` | DFlash (LLM recipe) | Block drafting knobs. | @@ -705,7 +712,7 @@ checkpoint cadence: `ckpt_every_steps`, `save_checkpoint_every_epoch`. The following tree shows the configs in this folder: -``` +```text examples/speculative/ eagle1/ eagle2/ eagle3/ eagle3_1/ eagle4/ p-eagle/ dflash/ # DFlash + DFlash 2 (qwen3_dflash2.yaml, @@ -719,7 +726,7 @@ examples/dllm_sft/ # DFlash DLLM SFT configs (standard SFT schema) The following tree shows the implementation layout: -``` +```text nemo_automodel/components/speculative/ eagle/ core(.py/_v12), draft_llama(.py/_v12), draft_gpt_oss, draft_deepseek, draft_gemma, draft_kimi_k3, backend, registry, diff --git a/examples/speculative/dfly2/deepseek_v41_flash_dfly2.yaml b/examples/speculative/dfly2/deepseek_v41_flash_dfly2.yaml new file mode 100644 index 0000000000..716498c773 --- /dev/null +++ b/examples/speculative/dfly2/deepseek_v41_flash_dfly2.yaml @@ -0,0 +1,148 @@ +# 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. +# +# Launch the same command on every node and vary --node-rank: +# torchrun --nnodes=16 --node-rank=0 --nproc_per_node=4 \ +# --master-addr= --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 diff --git a/nemo_automodel/components/loss/dllm_loss.py b/nemo_automodel/components/loss/dllm_loss.py index b9053fab55..a4e6ecdbfc 100644 --- a/nemo_automodel/components/loss/dllm_loss.py +++ b/nemo_automodel/components/loss/dllm_loss.py @@ -758,6 +758,73 @@ def forward( _DPACE_LOSS_TYPES = _DFLASH_LOSS_TYPES - {"dflash"} +def dpace_position_weights( + token_nll: torch.Tensor, + binary_mask: torch.Tensor, + binary_mask_bool: torch.Tensor, + *, + dpace_alpha: float, + loss_type: str = "dpace", +) -> torch.Tensor: + """Compute detached D-PACE position weights (arXiv:2605.18810). + + Args: + token_nll: Per-token NLL of the draft on the target token, shape + ``[batch, blocks, k]``; the draft confidence is ``exp(-token_nll)``. + Taken as the NLL rather than the confidence so the smoothed + log-confidence stays finite even where ``exp(-token_nll)`` + underflows. + binary_mask: Float valid-position mask, same shape. + binary_mask_bool: Boolean valid-position mask, same shape. + dpace_alpha: Smoothing alpha for the confidence products, in ``[0, 1]``. + loss_type: One of the ``"dpace*"`` variants. + + Returns: + Detached weights of shape ``[batch, blocks, k]``, in ``token_nll``'s + dtype. The ``cumprod`` / reverse-``cumsum`` run over the last (``k``) + axis, so the confidence product resets at every block boundary by + construction. Accumulated in float32: the per-block products span many + orders of magnitude at small ``dpace_alpha``, which bf16's 8-bit + mantissa cannot carry. + """ + nll = token_nll.float() + smooth = (1.0 - dpace_alpha) * torch.exp(-nll) + dpace_alpha + smooth = torch.where(binary_mask_bool, smooth, torch.ones_like(smooth)) + prefix = torch.cumprod(smooth, dim=-1) + + if loss_type == "dpace-cumulative-confidence-only": + return prefix.to(token_nll.dtype) + + if loss_type == "dpace": + suffix = torch.flip( + torch.cumsum(torch.flip(prefix * binary_mask.to(prefix.dtype), dims=[-1]), dim=-1), + dims=[-1], + ) + return suffix.to(token_nll.dtype) + + if loss_type == "dpace-continuation-value-only": + # The same suffix/prefix ratio, evaluated in log space. Computing it as a + # division underflows for small dpace_alpha: alpha=0 leaves a bare product + # of block_size-1 confidences, so a merely lukewarm draft (0.3 per position + # over 15 positions) already reaches 1e-8 and keeps falling, and once both + # operands flush to zero the ratio is lost. log(smooth) is built from the + # NLL via logaddexp, so it stays finite even where exp(-nll) is zero. + log_alpha = nll.new_tensor(dpace_alpha).log() + log_one_minus_alpha = torch.log1p(nll.new_tensor(-dpace_alpha)) + log_smooth = torch.logaddexp(log_one_minus_alpha - nll, log_alpha.expand_as(nll)) + log_smooth = torch.where(binary_mask_bool, log_smooth, torch.zeros_like(log_smooth)) + log_prefix = torch.cumsum(log_smooth, dim=-1) + log_suffix = torch.flip( + torch.logcumsumexp( + torch.flip(log_prefix.masked_fill(~binary_mask_bool, float("-inf")), dims=[-1]), + dim=-1, + ), + dims=[-1], + ) + return torch.exp(log_suffix - log_prefix).to(token_nll.dtype) + raise ValueError(f"unknown D-PACE loss_type {loss_type!r}") + + class DFlashDecayLoss(nn.Module): """Position-decay cross-entropy loss for DFlash draft model training. @@ -858,61 +925,19 @@ def _dpace_weight( binary_mask: torch.Tensor, binary_mask_bool: torch.Tensor, ) -> torch.Tensor: - """Compute detached D-PACE position weights. + """Compute detached D-PACE position weights with this loss's alpha and variant. Args: - token_nll: Per-token NLL of the draft on the target token, shape - ``[batch, blocks, k]``; the draft confidence is ``exp(-token_nll)``. - Taken as the NLL rather than the confidence so the smoothed - log-confidence stays finite even where ``exp(-token_nll)`` - underflows. + token_nll: Per-token NLL of shape ``[batch, blocks, k]``. binary_mask: Float valid-position mask, same shape. binary_mask_bool: Boolean valid-position mask, same shape. Returns: - Detached weights of shape ``[batch, blocks, k]``, in ``token_nll``'s - dtype. The ``cumprod`` / reverse-``cumsum`` run over the last (``k``) - axis, so the confidence product resets at every block boundary by - construction. Accumulated in float32: the per-block products span many - orders of magnitude at small ``dpace_alpha``, which bf16's 8-bit - mantissa cannot carry. + Detached weights of shape ``[batch, blocks, k]``; see :func:`dpace_position_weights`. """ - nll = token_nll.float() - smooth = (1.0 - self.dpace_alpha) * torch.exp(-nll) + self.dpace_alpha - smooth = torch.where(binary_mask_bool, smooth, torch.ones_like(smooth)) - prefix = torch.cumprod(smooth, dim=-1) - - if self.loss_type == "dpace-cumulative-confidence-only": - return prefix.to(token_nll.dtype) - - if self.loss_type == "dpace": - suffix = torch.flip( - torch.cumsum(torch.flip(prefix * binary_mask.to(prefix.dtype), dims=[-1]), dim=-1), - dims=[-1], - ) - return suffix.to(token_nll.dtype) - - if self.loss_type == "dpace-continuation-value-only": - # The same suffix/prefix ratio, evaluated in log space. Computing it as a - # division underflows for small dpace_alpha: alpha=0 leaves a bare product - # of block_size-1 confidences, so a merely lukewarm draft (0.3 per position - # over 15 positions) already reaches 1e-8 and keeps falling, and once both - # operands flush to zero the ratio is lost. log(smooth) is built from the - # NLL via logaddexp, so it stays finite even where exp(-nll) is zero. - log_alpha = nll.new_tensor(self.dpace_alpha).log() - log_one_minus_alpha = torch.log1p(nll.new_tensor(-self.dpace_alpha)) - log_smooth = torch.logaddexp(log_one_minus_alpha - nll, log_alpha.expand_as(nll)) - log_smooth = torch.where(binary_mask_bool, log_smooth, torch.zeros_like(log_smooth)) - log_prefix = torch.cumsum(log_smooth, dim=-1) - log_suffix = torch.flip( - torch.logcumsumexp( - torch.flip(log_prefix.masked_fill(~binary_mask_bool, float("-inf")), dims=[-1]), - dim=-1, - ), - dims=[-1], - ) - return torch.exp(log_suffix - log_prefix).to(token_nll.dtype) - raise ValueError(f"unknown D-PACE loss_type {self.loss_type!r}") + return dpace_position_weights( + token_nll, binary_mask, binary_mask_bool, dpace_alpha=self.dpace_alpha, loss_type=self.loss_type + ) def position_weights(self, token_nll: torch.Tensor, block_mask: torch.Tensor) -> torch.Tensor: """Per-position loss weights for this instance's ``loss_type``, unreduced. diff --git a/nemo_automodel/components/models/deepseek_v41/config.py b/nemo_automodel/components/models/deepseek_v41/config.py index c3ba70cd55..8a673b8cbe 100644 --- a/nemo_automodel/components/models/deepseek_v41/config.py +++ b/nemo_automodel/components/models/deepseek_v41/config.py @@ -27,6 +27,7 @@ import torch from nemo_automodel.components.distributed.config import DistributedSetup + from nemo_automodel.components.models.deepseek_v41.dfly2 import DeepseekV41DFly2Model from nemo_automodel.components.models.deepseek_v41.dspark import DeepseekV41DSparkModel from nemo_automodel.components.models.deepseek_v41.model import DeepseekV41ForCausalLM @@ -46,6 +47,18 @@ class _DSparkDraftOptions(Protocol): confidence_head_stop_gradient: bool +class _DFly2DraftOptions(Protocol): + """Declarative DFly2 settings supplied by the DFly2 training recipe.""" + + target_layer_ids: list[int] + block_size: int + num_anchors: int + mask_token_id: int + enable_confidence_head: bool + confidence_head_stop_gradient: bool + attn_backend: str + + class DeepseekV41TextConfig(PretrainedConfig): """Declarative configuration of the CSA2, single-pass mHC and Engram backbone. @@ -520,6 +533,30 @@ def build_dspark_draft(self, options: _DSparkDraftOptions) -> DeepseekV41DSparkM quantization_config=copy.deepcopy(getattr(self, "quantization_config", None)), ).build() + def build_dfly2_draft(self, options: _DFly2DraftOptions) -> DeepseekV41DFly2Model: + """Build the model-owned DFly2 draft. + + Args: + options: Declarative draft settings supplied by the DFly2 recipe. + + Returns: + Freshly initialized DeepSeek V4.1 DFly2 draft ready for device placement. + """ + from nemo_automodel.components.models.deepseek_v41.dfly2 import DeepseekV41DFly2Config, default_dfly2_backend + + # The draft runs the default atomic sparse backward; keep the target's selector out of it. + draft_text_config = copy.deepcopy(self.text_config) + draft_text_config.sparse_attention_backward = "atomic" + return DeepseekV41DFly2Config( + text_config=draft_text_config, + target_layer_ids=tuple(int(layer_id) for layer_id in options.target_layer_ids), + block_size=int(options.block_size), + num_anchors=int(options.num_anchors), + mask_token_id=int(options.mask_token_id), + enable_confidence_head=bool(options.enable_confidence_head), + confidence_head_stop_gradient=bool(options.confidence_head_stop_gradient), + ).build(default_dfly2_backend(str(options.attn_backend))) + @dataclass(frozen=True) class DeepseekV41DSparkConfig: diff --git a/nemo_automodel/components/models/deepseek_v41/dfly2.py b/nemo_automodel/components/models/deepseek_v41/dfly2.py new file mode 100644 index 0000000000..8930b0bec6 --- /dev/null +++ b/nemo_automodel/components/models/deepseek_v41/dfly2.py @@ -0,0 +1,916 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Code provenance: the attentive correction's gated prefix read (``_prefix_read``) and its start from +# the last draft layer (``DeepseekV41DFly2Model.initialize_attentive_correction``) are adapted from +# Tencent/AngelSpec, https://github.com/Tencent/AngelSpec at revision e02ea36e65d44e6e165c4ba73c139d500e12f2d9, +# file angelspec/models/draft/dsv41_attentive_correction.py, Copyright (C) 2026 Tencent, licensed +# under the Apache License, Version 2.0. Modified by NVIDIA: rewritten for this module's layout. + +"""DFly2 draft for DeepSeek-V4.1-Flash (arXiv:2611.34776). + +Each draft layer is a V4.1 block (latent MQA with an attention sink, routed MoE and +single-pass mHC) paired with one of the target's ratio-1 sparse-attention layers. It owns +no context projection: its queries read the keys that target layer attends over, its own +sliding-window latents followed by the shared 1:1 global latents, at the slots that layer +attends from the row before the anchor (the last 128 tokens plus the indexer's top-512 +picks), together with the draft keys of its own block. The released checkpoint pairs +layers 28, 32 and 36. + +Around the backbone, the target's final hidden state at the row before the anchor is fused +into the anchor slot (MTP fusion), and a teacher-forced hidden correction, a SwiGLU plus +an attentive correction over the last layer's context and the block's own prefix, adjusts +every slot before the frozen LM head. Slot 0 holds the anchor and is not supervised, so a +block of ``block_size`` slots drafts ``block_size - 1`` tokens. +""" + +from __future__ import annotations + +import copy +from collections.abc import Sequence +from dataclasses import dataclass +from functools import partial + +import torch +from torch import nn +from torch.distributed.tensor import DTensor +from torch.nn import functional as F + +from nemo_automodel.components.models.common import BackendConfig, initialize_rms_norm_module +from nemo_automodel.components.models.deepseek_v4.config import DeepseekV4Config +from nemo_automodel.components.models.deepseek_v4.layers import DeepseekV4FP32Parameter, DeepseekV4GroupedLinear +from nemo_automodel.components.models.deepseek_v4.model import DeepseekV4VisionGate +from nemo_automodel.components.models.deepseek_v4.optimized_kernels import dsv4_sparse_attention +from nemo_automodel.components.models.deepseek_v41.attention import DeepseekV41Attention, _apply_rope, _RotaryEmbedding +from nemo_automodel.components.models.deepseek_v41.config import DeepseekV41TextConfig +from nemo_automodel.components.models.deepseek_v41.layers import DeepseekV41HyperConnection, DeepseekV41RMSNorm +from nemo_automodel.components.moe.config import MoEConfig +from nemo_automodel.components.moe.layers import MoE +from nemo_automodel.components.speculative.dfly2.common import build_block_key_indices, context_key_indices +from nemo_automodel.components.speculative.dspark.common import ( + DSparkForwardOutput, + build_eval_mask, + create_noise_embed, + create_position_ids, + sample_anchor_positions, +) +from nemo_automodel.shared.utils import dtype_from_str + +# Width of the per-slot bias tables of the attentive correction's prefix read, so the longest +# supported block. Fixed by the shapes of the released draft's tensors. +MAX_BLOCK_SLOTS = 16 +_SPARSE_BACKENDS = ("tilelang", "cudnn") + + +@dataclass(frozen=True) +class DeepseekV41DFly2Config: + """Validated declarative configuration of the V4.1 DFly2 draft. + + Attributes: + text_config: Target text configuration; the draft reuses its attention, mHC and + MoE shapes and its compressed-layer rotary embedding. + target_layer_ids: Target layers paired with the draft layers, in draft-layer + order. Each must be a ratio-1 sparse-attention layer, whose context rows are + raw tokens. + block_size: Draft slots per block, the anchor slot included. + num_anchors: Blocks sampled per sequence. + mask_token_id: Token filling the non-anchor slots. + enable_confidence_head: Build the acceptance head, absent from the released draft. + confidence_head_stop_gradient: Feed the acceptance head detached states, so its + loss trains only the head. + n_routed_experts: Routed experts per draft layer. + num_experts_per_tok: Experts each token is routed to. + """ + + text_config: DeepseekV41TextConfig + target_layer_ids: tuple[int, ...] + block_size: int + num_anchors: int + mask_token_id: int + enable_confidence_head: bool = False + confidence_head_stop_gradient: bool = True + n_routed_experts: int = 128 + num_experts_per_tok: int = 3 + + def build(self, backend: BackendConfig | None = None) -> DeepseekV41DFly2Model: + """Validate the target pairing and build a freshly initialized draft. + + Args: + backend: Kernel selection for the draft; defaults to :func:`default_dfly2_backend`. + + Returns: + The draft, ready for device placement. + + Raises: + ValueError: A paired layer is not a ratio-1 target layer, or a size is invalid. + """ + text = self.text_config + if not self.target_layer_ids: + raise ValueError("DeepSeek V4.1 DFly2 needs at least one paired target layer") + for layer_id in self.target_layer_ids: + if not 0 <= layer_id < text.num_hidden_layers or text.compress_ratios[layer_id] != 1: + raise ValueError( + f"DeepSeek V4.1 DFly2 pairs ratio-1 target layers, whose context rows are raw tokens; " + f"layer {layer_id} has compress_ratio " + f"{text.compress_ratios[layer_id] if 0 <= layer_id < len(text.compress_ratios) else None}" + ) + if len(text.compress_ratios) < text.num_hidden_layers + len(self.target_layer_ids): + raise ValueError("DeepSeek V4.1 DFly2 needs compress_ratios entries for the draft layers") + if not 2 <= self.block_size <= MAX_BLOCK_SLOTS: + raise ValueError(f"DeepSeek V4.1 DFly2 block_size must be in [2, {MAX_BLOCK_SLOTS}], got {self.block_size}") + if self.num_anchors <= 0: + raise ValueError(f"DeepSeek V4.1 DFly2 requires num_anchors > 0, got {self.num_anchors}") + if not 0 <= self.mask_token_id < text.vocab_size: + raise ValueError(f"mask_token_id={self.mask_token_id} is outside the vocabulary [0, {text.vocab_size})") + return DeepseekV41DFly2Model(self, backend) + + +def default_dfly2_backend(attn: str = "sdpa") -> BackendConfig: + """Return the draft's kernel selection. + + Args: + attn: ``"sdpa"`` or ``"eager"`` scatter the key lists into a dense mask, which suits + short rows; ``"tilelang"`` or ``"cudnn"`` run the shared sparse kernel, which long + rows need. + + Returns: + Backend with torch linears and FP32 RMSNorm. Like BackendConfig's own default, the + experts use grouped GEMMs on CUDA. + """ + return BackendConfig( + attn=attn, + linear="torch", + rms_norm="torch_fp32", + experts="torch_mm" if torch.cuda.is_available() else "torch", + dispatcher="torch", + ) + + +def _listed_latent_attention( + query: torch.Tensor, + kv: torch.Tensor, + indices: torch.Tensor, + sinks: torch.Tensor, + scale: float, + *, + backend: str, +) -> torch.Tensor: + """Attend every query over its listed keys, one shared latent serving as key and value. + + Args: + query: Tensor of shape [batch, queries, heads, head_dim]. + kv: Tensor of shape [batch, keys, head_dim]. + indices: Integer tensor of shape [batch, queries, slots] of ``kv`` rows, ``-1`` + unused. The listed keys of a row must be distinct. + sinks: FP32 tensor of shape [heads], learned logits added to every softmax + denominator only. + scale: Query/key score multiplier. + backend: ``"tilelang"`` or ``"cudnn"`` run the shared sparse kernel; ``"sdpa"`` and + ``"eager"`` scatter the lists into a dense mask. + + Returns: + Tensor of shape [batch, queries, heads, head_dim] in the dtype of ``query``; zero + for a query without keys. + """ + if backend in _SPARSE_BACKENDS: + return dsv4_sparse_attention(query, kv, sinks, indices, scale, backend=backend) + batch, queries, heads, head_dim = query.shape + keys = kv.shape[1] + # A separate sentinel column absorbs the -1 slots, as in the target's dense fallback. + allowed = torch.zeros(batch, queries, keys + 1, dtype=torch.bool, device=query.device) + allowed = allowed.scatter(-1, torch.where(indices >= 0, indices, keys).long(), True)[..., :keys] + # A zero-valued extra key contributes exp(sink) only to the denominator; a query + # without keys then puts all its weight on it and returns zero. + kv = torch.cat((kv, kv.new_zeros(batch, 1, head_dim)), dim=1) + bias = torch.zeros(batch, 1, queries, keys, device=query.device, dtype=torch.float32) + bias = bias.masked_fill(~allowed.unsqueeze(1), -torch.inf).expand(-1, heads, -1, -1) + bias = torch.cat((bias, sinks.float().view(1, heads, 1, 1).expand(batch, -1, queries, -1)), dim=-1) + if backend == "sdpa": + return F.scaled_dot_product_attention( + query.transpose(1, 2), kv.unsqueeze(1), kv.unsqueeze(1), attn_mask=bias, scale=scale + ).transpose(1, 2) + with torch.autocast(device_type=query.device.type, enabled=False): + logits = torch.einsum("bshd,btd->bhst", query.float(), kv.float()) * scale + probabilities = (logits + bias).softmax(dim=-1) + return torch.einsum("bhst,btd->bshd", probabilities, kv.float()).to(query.dtype) + + +class _DeepseekV41DFly2Attention(DeepseekV41Attention): + """Latent MQA over a paired target layer's keys and the draft's own block.""" + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int, backend: BackendConfig) -> None: + super().__init__(config, layer_idx, backend) + if self.compress_ratio != 0 or self.compressor is not None or self.indexer is not None: + raise ValueError("DeepSeek V4.1 DFly2 draft layers must own no compressor or indexer") + # Queries rotate like the keys they read: those of the paired ratio-1 target layers. + self.rotary_emb = _RotaryEmbedding(config, compressed=True) + + def forward( + self, + hidden_states: torch.Tensor, + context_keys: torch.Tensor, + key_indices: torch.Tensor, + *, + position_ids: torch.Tensor, + ) -> torch.Tensor: + """Attend draft queries to their listed target keys and their own block. + + Args: + hidden_states: Normalized draft tensor of shape [batch, draft_sequence, hidden]. + context_keys: Paired target layer's keys of shape [batch, context_keys, head_dim]. + key_indices: Integer tensor of shape [batch, draft_sequence, slots] of rows of + ``cat(context_keys, draft_keys)``, ``-1`` unused. + position_ids: Integer tensor of shape [batch, draft_sequence]. + + Returns: + Tensor of shape [batch, draft_sequence, hidden]. Inputs are not mutated. + """ + batch, draft_sequence, _ = hidden_states.shape + angles = self.rotary_emb(position_ids) + query = self.wq_b(self.q_norm(self.wq_a(hidden_states))).unflatten(-1, (self.num_heads, self.head_dim)) + query = _apply_rope(query, angles) + draft_kv = _apply_rope(self.kv_norm(self.wkv(hidden_states)), angles) + kv = torch.cat((context_keys.to(draft_kv.dtype), draft_kv), dim=1) + attended = _listed_latent_attention( + query, kv, key_indices, self.sinks_param(query), self.head_dim**-0.5, backend=self.backend.attn + ) + valid_tokens = torch.ones(batch, draft_sequence, dtype=torch.bool, device=hidden_states.device) + return self._project_output(attended, angles, valid_tokens) + + +class _DeepseekV41DFly2Block(nn.Module): + """One draft layer: latent MQA, routed MoE and single-pass mHC, as in the target's blocks.""" + + def __init__( + self, config: DeepseekV41TextConfig, layer_idx: int, backend: BackendConfig, moe_config: MoEConfig + ) -> None: + super().__init__() + dtype = dtype_from_str(config.dtype, torch.bfloat16) + self.attn = _DeepseekV41DFly2Attention(config, layer_idx, backend) + self.ffn = MoE(moe_config, backend) + # As in the backbone block, BackendConfig.fake_balanced_gate keeps the + # FakeBalancedGate that MoE built. + if not backend.fake_balanced_gate: + self.ffn.gate = DeepseekV4VisionGate( + DeepseekV4Config(vocab_size=config.vocab_size), + moe_config, + gate_precision=torch.float32, + hash_routing=False, + ) + norm = ( + partial(initialize_rms_norm_module, "te", device=self.attn.wq_a.weight.device) + if backend.rms_norm == "te" + else DeepseekV41RMSNorm + ) + self.attn_norm = norm(config.hidden_size, eps=config.rms_norm_eps, dtype=dtype) + self.ffn_norm = norm(config.hidden_size, eps=config.rms_norm_eps, dtype=dtype) + sinkhorn_backend = "tilelang" if backend.attn == "tilelang" else "torch" + self.attn_hc = DeepseekV41HyperConnection(config, sinkhorn_backend=sinkhorn_backend) + self.ffn_hc = DeepseekV41HyperConnection(config, sinkhorn_backend=sinkhorn_backend) + + @property + def mlp(self) -> MoE: + """Expose the shared parallelizer's MoE interface without duplicate registration.""" + return self.ffn + + def forward( + self, + hidden_states: torch.Tensor, + pre_mix: torch.Tensor, + context_keys: torch.Tensor, + key_indices: torch.Tensor, + *, + position_ids: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Apply one draft layer. + + The attention input collapses the streams with the previous layer's FFN pre-mix + and the FFN input with this layer's attention pre-mix, as the target's blocks do. + + Args: + hidden_states: Tensor of shape [batch, draft_sequence, streams, hidden]. + pre_mix: FP32 tensor of shape [batch, draft_sequence, streams]. + context_keys: Tensor of shape [batch, context_keys, head_dim]. + key_indices: Integer tensor of shape [batch, draft_sequence, slots]. + position_ids: Integer tensor of shape [batch, draft_sequence]. + + Returns: + Updated streams of shape [batch, draft_sequence, streams, hidden] and the FP32 + pre-mix of shape [batch, draft_sequence, streams] for the next layer. + """ + residual = hidden_states + attn_mix = self.attn_hc(hidden_states) + collapsed = self.attn_hc.collapse(hidden_states, pre_mix) + attended = self.attn(self.attn_norm(collapsed), context_keys, key_indices, position_ids=position_ids) + hidden_states = self.attn_hc.expand(attended, residual, attn_mix) + residual = hidden_states + ffn_mix = self.ffn_hc(hidden_states) + collapsed = self.ffn_hc.collapse(hidden_states, attn_mix.pre) + gate = self.ffn.gate + if isinstance(gate, DeepseekV4VisionGate): + gate.set_routing_context(None, None) + output = self.ffn(self.ffn_norm(collapsed), None) + return self.ffn_hc.expand(output, residual, ffn_mix), ffn_mix.pre + + +class _DeepseekV41DFly2MTPFusion(nn.Module): + """Fuse the target's last hidden state into the anchor slot, as the target's MTP layer opens.""" + + def __init__(self, config: DeepseekV41TextConfig, dtype: torch.dtype) -> None: + super().__init__() + self.enorm = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps, dtype=dtype) + self.hnorm = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps, dtype=dtype) + self.eh_proj = nn.Linear(2 * config.hidden_size, config.hidden_size, bias=False, dtype=dtype) + # Per-channel gate, zero at initialization so a fresh draft starts without fusion. + self.gate = nn.Parameter(torch.zeros(config.hidden_size, dtype=dtype)) + + def forward(self, anchor_embeddings: torch.Tensor, target_hidden_states: torch.Tensor) -> torch.Tensor: + """Compute the residual added to every anchor slot. + + Args: + anchor_embeddings: Tensor of shape [batch, num_anchors, hidden], the anchor + tokens' embeddings. + target_hidden_states: Tensor of shape [batch, num_anchors, hidden], the target's + final normalized hidden state at the row before each anchor. + + Returns: + Tensor of shape [batch, num_anchors, hidden]. + """ + fused = self.eh_proj(torch.cat((self.enorm(anchor_embeddings), self.hnorm(target_hidden_states)), dim=-1)) + return self.gate * fused + + +class _DeepseekV41DFly2AttentiveCorrection(nn.Module): + """Per-slot latent MQA over the last draft layer's context plus a gated read of the block prefix. + + The query comes from the slot's normalized hidden state and the normalized embedding of + the token before it. Slot ``k`` reads the context keys the last draft layer read, then, + in a softmax of its own with a sink and a learned bias by distance, the keys of slots + ``0..k`` of its block, added through a per-head ``tanh`` gate. ``wo_b`` and the gate + start at zero, so a fresh correction is an exact no-op. + """ + + def __init__(self, config: DeepseekV41TextConfig, backend: BackendConfig, dtype: torch.dtype) -> None: + super().__init__() + hidden = config.hidden_size + self.num_heads = config.num_attention_heads + self.head_dim = config.head_dim + self.num_groups = config.o_groups + self.backend = backend + self.q_in = nn.Linear(2 * hidden, config.q_lora_rank, bias=False, dtype=dtype) + self.q_norm = DeepseekV41RMSNorm(config.q_lora_rank, eps=config.rms_norm_eps, dtype=dtype) + self.wq_b = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False, dtype=dtype) + self.kv_in = nn.Linear(2 * hidden, self.head_dim, bias=False, dtype=dtype) + self.kv_norm = DeepseekV41RMSNorm(self.head_dim, eps=config.rms_norm_eps, dtype=dtype) + self.wo_a = DeepseekV4GroupedLinear( + self.num_heads * self.head_dim // self.num_groups, self.num_groups * config.o_lora_rank, self.num_groups + ).to(dtype=dtype) + self.wo_b = nn.Linear(self.num_groups * config.o_lora_rank, hidden, bias=False, dtype=dtype) + self.block_gate = nn.Linear(2 * hidden, self.num_heads, bias=False, dtype=dtype) + self.attn_sink = DeepseekV4FP32Parameter(torch.zeros(self.num_heads)) + self.block_sink = DeepseekV4FP32Parameter(torch.zeros(self.num_heads)) + self.block_rel_bias = DeepseekV4FP32Parameter(torch.zeros(self.num_heads, MAX_BLOCK_SLOTS)) + self.block_gate_bias = DeepseekV4FP32Parameter(torch.zeros(self.num_heads, MAX_BLOCK_SLOTS)) + self.rotary_emb = _RotaryEmbedding(config, compressed=True) + + def _prefix_read( + self, query: torch.Tensor, keys: torch.Tensor, inputs: torch.Tensor, block_size: int + ) -> torch.Tensor: + """Gated read of each slot's own block prefix (slots ``0..k`` for slot ``k``). + + The prefix has a softmax of its own: a per-head learned bias indexed by how many slots + back the key is, plus the ``block_sink`` logit in the denominator as an extra column. + Each head scales its read by ``tanh`` of a gate computed from the slot's inputs. + + Args: + query: Tensor of shape [batch, slots, heads, head_dim], whole blocks of ``block_size``. + keys: Tensor of shape [batch, slots, head_dim], each slot's key, also its value. + inputs: Tensor of shape [batch, slots, 2 * hidden], the query inputs. + block_size: Slots per block. + + Returns: + FP32 tensor of shape [batch, slots, heads, head_dim]. + """ + batch, slots, heads, head_dim = query.shape + blocks = slots // block_size + per_block_query = query.float().unflatten(1, (blocks, block_size)) + per_block_keys = keys.float().unflatten(1, (blocks, block_size)) + scores = torch.einsum("bnshd,bntd->bnhst", per_block_query, per_block_keys) * head_dim**-0.5 + # distance[s, t] = s - t: how far back key slot t lies from query slot s. + positions = torch.arange(block_size, device=query.device) + distance = (positions.unsqueeze(1) - positions.unsqueeze(0)).clamp(min=0) + scores = scores + self.block_rel_bias(query).float()[:, distance] + prefix = torch.ones(block_size, block_size, dtype=torch.bool, device=query.device).tril() + scores = scores.masked_fill(~prefix, float("-inf")) + sink = self.block_sink(query).float().view(1, 1, heads, 1, 1).expand(*scores.shape[:-1], 1) + weights = torch.cat((scores, sink), dim=-1).softmax(dim=-1)[..., :-1] + read = torch.einsum("bnhst,bntd->bnshd", weights, per_block_keys).flatten(1, 2) + slot_bias = self.block_gate_bias(query).float()[:, positions.repeat(blocks)] + gate = torch.tanh(self.block_gate(inputs).float() + slot_bias.T) + return read * gate.unsqueeze(-1) + + def forward( + self, + inputs: torch.Tensor, + context_keys: torch.Tensor, + context_indices: torch.Tensor, + *, + position_ids: torch.Tensor, + block_size: int, + ) -> torch.Tensor: + """Compute the correction of every slot. + + Args: + inputs: Tensor of shape [batch, slots, 2 * hidden], the concatenated normalized + hidden state and previous-token embedding of each slot; whole blocks. + context_keys: Last draft layer's context keys of shape [batch, context_keys, head_dim]. + context_indices: Integer tensor of shape [batch, slots, key_slots] of + ``context_keys`` rows, ``-1`` unused. + position_ids: Integer tensor of shape [batch, slots]. + block_size: Slots per block. + + Returns: + Tensor of shape [batch, slots, hidden]. + """ + angles = self.rotary_emb(position_ids) + query = self.wq_b(self.q_norm(self.q_in(inputs))).unflatten(-1, (self.num_heads, self.head_dim)) + query = _apply_rope(query, angles) + keys = _apply_rope(self.kv_norm(self.kv_in(inputs)), angles) + context = _listed_latent_attention( + query, + context_keys.to(query.dtype), + context_indices, + self.attn_sink(query), + self.head_dim**-0.5, + backend=self.backend.attn, + ) + read = (context.float() + self._prefix_read(query, keys, inputs, block_size)).to(query.dtype) + read = _apply_rope(read, angles, inverse=True) + return self.wo_b(self.wo_a(read.reshape(*read.shape[:2], self.num_groups, -1)).flatten(2)) + + +class _DeepseekV41DFly2HiddenCorrection(nn.Module): + """Teacher-forced residual from each slot's hidden state and the token before it.""" + + def __init__( + self, config: DeepseekV41TextConfig, intermediate_size: int, backend: BackendConfig, dtype: torch.dtype + ) -> None: + super().__init__() + hidden = config.hidden_size + self.hidden_norm = DeepseekV41RMSNorm(hidden, eps=config.rms_norm_eps, dtype=dtype) + self.embed_norm = DeepseekV41RMSNorm(hidden, eps=config.rms_norm_eps, dtype=dtype) + self.gate_proj = nn.Linear(2 * hidden, intermediate_size, bias=False, dtype=dtype) + self.up_proj = nn.Linear(2 * hidden, intermediate_size, bias=False, dtype=dtype) + self.down_proj = nn.Linear(intermediate_size, hidden, bias=False, dtype=dtype) + self.attention = _DeepseekV41DFly2AttentiveCorrection(config, backend, dtype) + + def forward( + self, + hidden_states: torch.Tensor, + previous_embeddings: torch.Tensor, + context_keys: torch.Tensor, + context_indices: torch.Tensor, + *, + position_ids: torch.Tensor, + block_size: int, + ) -> torch.Tensor: + """Return the corrected hidden states. + + Args: + hidden_states: Final-normalized draft tensor of shape [batch, slots, hidden]. + previous_embeddings: Tensor of shape [batch, slots, hidden], the embedding of the + token before each slot (the anchor for slots 0 and 1). + context_keys: Tensor of shape [batch, context_keys, head_dim]. + context_indices: Integer tensor of shape [batch, slots, key_slots]. + position_ids: Integer tensor of shape [batch, slots]. + block_size: Slots per block. + + Returns: + Tensor of shape [batch, slots, hidden]. + """ + inputs = torch.cat((self.hidden_norm(hidden_states), self.embed_norm(previous_embeddings)), dim=-1) + delta = self.down_proj(F.silu(self.gate_proj(inputs)) * self.up_proj(inputs)) + delta = delta + self.attention( + inputs, context_keys, context_indices, position_ids=position_ids, block_size=block_size + ) + return hidden_states + delta + + +class _DeepseekV41DFly2ConfidenceHead(nn.Module): + """FP32 acceptance head on the drafted slots' final-normalized states (absent from the released draft).""" + + def __init__(self, hidden_size: int) -> None: + super().__init__() + # Named so the strict FP32 entry also matches inside the head's own FSDP unit. + self.confidence_proj = nn.Linear(hidden_size, 1, dtype=torch.float32) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + """Predict an acceptance logit per slot. + + Args: + hidden_states: Tensor of shape [..., hidden], with arbitrary leading dimensions. + + Returns: + FP32 tensor of shape [...]. + """ + with torch.autocast(device_type=hidden_states.device.type, enabled=False): + return self.confidence_proj(hidden_states.float()).squeeze(-1) + + +class DeepseekV41DFly2Model(nn.Module): + """Model-owned DFly2 draft emitting the shared DSpark loss inputs over its drafted slots.""" + + _no_split_modules = ["_DeepseekV41DFly2Block"] + _keep_in_fp32_modules_strict = [ + "attn_hc", + "ffn_hc", + "attn.sinks_param", + "e_score_correction_bias", + "bias_vl", + "attention.attn_sink", + "attention.block_sink", + "attention.block_rel_bias", + "attention.block_gate_bias", + "confidence_proj", + ] + # Same fp32 holders as DeepseekV41ForCausalLM: the draft's attention sinks share one FSDP + # unit across the draft blocks (parallelizer_utils.fully_shard_across_blocks). + _fsdp_shard_across_blocks = ["attn.sinks_param"] + + def __init__(self, config: DeepseekV41DFly2Config, backend: BackendConfig | None = None) -> None: + backend = backend or default_dfly2_backend() + super().__init__() + text = config.text_config + dtype = dtype_from_str(text.dtype, torch.bfloat16) + self.dfly2_config = config + # The exported config.json: the target's text config with the DFly2 settings in a + # ``dfly_config`` block (block size, paired layers, mask token, correction layout). + self.config = copy.deepcopy(text) + self.config.architectures = ["DeepseekV41DFly2Model"] + self.config.dfly_config = { + "block_size": config.block_size, + "causal_block": False, + "target_kv_layers": list(config.target_layer_ids), + "target_index_layers": list(config.target_layer_ids), + "index_topk": text.index_topk, + "mask_token_id": config.mask_token_id, + "rope": { + "theta": text.compress_rope_theta, + "original_seq_len": (text.rope_scaling or {}).get("original_max_position_embeddings", 0), + "factor": (text.rope_scaling or {}).get("factor", 1.0), + "beta_fast": (text.rope_scaling or {}).get("beta_fast", 32), + "beta_slow": (text.rope_scaling or {}).get("beta_slow", 1), + }, + "mtp_fusion": "slot0", + "hidden_correction": {"intermediate_size": text.hidden_size}, + "attentive_correction": { + "source_layer": -1, + "block_keys": True, + "block_mode": "gated", + "block_kv_in": "hidden_embed", + "max_block_slots": MAX_BLOCK_SLOTS, + }, + "dense_dtype": str(dtype).removeprefix("torch."), + } + self.moe_config = MoEConfig( + dim=text.hidden_size, + inter_dim=text.moe_intermediate_size, + moe_inter_dim=text.moe_intermediate_size, + n_routed_experts=config.n_routed_experts, + n_shared_experts=text.n_shared_experts, + n_activated_experts=config.num_experts_per_tok, + n_expert_groups=0, + n_limited_groups=0, + train_gate=True, + gate_bias_update_factor=0.0, + aux_loss_coeff=0.0, + score_func="sqrtsoftplus", + route_scale=text.routed_scaling_factor, + norm_topk_prob=text.norm_topk_prob, + router_weights_fp32=True, + force_e_score_correction_bias=True, + swiglu_limit=text.swiglu_limit, + dtype=dtype, + ) + # Draft layers take the schedule slots after the target's, which carry no compressor or indexer. + self.layers = nn.ModuleList( + _DeepseekV41DFly2Block(text, text.num_hidden_layers + index, backend, self.moe_config) + for index in range(len(config.target_layer_ids)) + ) + self.final_norm = DeepseekV41RMSNorm(text.hidden_size, eps=text.rms_norm_eps, dtype=dtype) + self.mtp_fusion = _DeepseekV41DFly2MTPFusion(text, dtype) + self.hidden_correction = _DeepseekV41DFly2HiddenCorrection(text, text.hidden_size, backend, dtype) + self.confidence_head = ( + _DeepseekV41DFly2ConfidenceHead(text.hidden_size) if config.enable_confidence_head else None + ) + self.embed_tokens = nn.Embedding(text.vocab_size, text.hidden_size, padding_idx=text.pad_token_id, dtype=dtype) + self.lm_head = nn.Linear(text.hidden_size, text.vocab_size, bias=False, dtype=dtype) + from nemo_automodel.components.models.deepseek_v41.state_dict_adapter import ( + DeepseekV41DFly2StateDictAdapter, + ) + + self.state_dict_adapter = DeepseekV41DFly2StateDictAdapter(text, self.moe_config, backend, dtype=dtype) + # The released keys of the whole draft, recorded before sharding: under FSDP each rank + # exports only its own experts, and the consolidated index must list all of them. + self._pre_shard_hf_state_dict_keys = self.state_dict_adapter.get_hf_state_dict_keys(self.state_dict()) + self.initialize_weights(self.embed_tokens.weight.device) + + @torch.no_grad() + def initialize_weights(self, buffer_device: torch.device | None = None) -> None: + """Initialize every draft parameter for checkpoint-free training. + + The fusion gate, the hidden correction's down projection and the attentive + correction's output start at zero, so a fresh draft is its backbone alone. + + Args: + buffer_device: Device used by grouped expert initialization. Defaults to the + first attention projection's device. + """ + if buffer_device is None: + buffer_device = self.layers[0].attn.wq_a.weight.device + std = self.dfly2_config.text_config.initializer_range + for layer in self.layers: + layer.ffn.init_weights(buffer_device, init_std=std) + layer.attn_hc.reset_parameters(std) + layer.ffn_hc.reset_parameters(std) + nn.init.ones_(layer.attn_norm.weight) + nn.init.ones_(layer.ffn_norm.weight) + if isinstance(layer.ffn.gate, DeepseekV4VisionGate): + layer.ffn.gate.bias_vl.zero_() + layer.attn.reset_parameters(std) + nn.init.ones_(self.final_norm.weight) + fusion = self.mtp_fusion + nn.init.ones_(fusion.enorm.weight) + nn.init.ones_(fusion.hnorm.weight) + nn.init.normal_(fusion.eh_proj.weight, std=std) + fusion.gate.zero_() + correction = self.hidden_correction + nn.init.ones_(correction.hidden_norm.weight) + nn.init.ones_(correction.embed_norm.weight) + nn.init.normal_(correction.gate_proj.weight, std=std) + nn.init.normal_(correction.up_proj.weight, std=std) + correction.down_proj.weight.zero_() + self.initialize_attentive_correction() + if self.confidence_head is not None: + nn.init.normal_(self.confidence_head.confidence_proj.weight, std=std) + nn.init.zeros_(self.confidence_head.confidence_proj.bias) + + @torch.no_grad() + def initialize_attentive_correction(self) -> None: + """Start the attentive correction from the last draft layer's attention, with its output closed. + + Its query and key input projections read ``[hidden; previous embedding]``: the hidden + columns take the layer's ``wq_a`` / ``wkv`` and the embedding columns start at zero. The + norms, ``wq_b``, ``wo_a`` and both sinks take the layer's values; ``wo_b``, the gate and + the per-slot biases start at zero, so the correction contributes nothing until trained. + """ + source = self.layers[-1].attn + correction = self.hidden_correction.attention + correction.q_norm.load_state_dict(source.q_norm.state_dict()) + correction.wq_b.load_state_dict(source.wq_b.state_dict()) + correction.kv_norm.load_state_dict(source.kv_norm.state_dict()) + correction.wo_a.load_state_dict(source.wo_a.state_dict()) + for widened, projection in ((correction.q_in, source.wq_a), (correction.kv_in, source.wkv)): + hidden_columns = projection.weight + widened.weight.copy_(torch.cat((hidden_columns, torch.zeros_like(hidden_columns)), dim=1)) + for sink in (correction.attn_sink, correction.block_sink): + sink.weight.copy_(source.sinks_param.weight) + for closed in (correction.wo_b, correction.block_gate, correction.block_rel_bias, correction.block_gate_bias): + closed.weight.zero_() + + @torch.no_grad() + def initialize_from_target(self, target: nn.Module) -> None: + """Start every draft layer's attention, norms, mHC mixes and shared expert from its paired target layer. + + Collective when the target is sharded: every rank must call it, in the same order. + The routed experts and the router keep their fresh initialization; warm-start them + from an existing draft through ``draft_weights_path`` instead. + + Args: + target: The frozen target ``DeepseekV41ForCausalLM``; its parameters may be + DTensors, which are gathered one at a time. + """ + target_layers = target.model.layers + for layer, layer_id in zip(self.layers, self.dfly2_config.target_layer_ids): + source = target_layers[str(layer_id)] + attn, source_attn = layer.attn, source.attn + pairs = [ + (layer.attn_norm, source.attn_norm), + (layer.ffn_norm, source.ffn_norm), + (attn.wq_a, source_attn.wq_a), + (attn.q_norm, source_attn.q_norm), + (attn.wq_b, source_attn.wq_b), + (attn.wkv, source_attn.wkv), + (attn.kv_norm, source_attn.kv_norm), + (attn.wo_a, source_attn.wo_a), + (attn.wo_b, source_attn.wo_b), + (attn.sinks_param, source_attn.sinks_param), + (layer.attn_hc, source.attn_hc), + (layer.ffn_hc, source.ffn_hc), + (layer.ffn.shared_experts, source.ffn.shared_experts), + ] + for draft_module, target_module in pairs: + for name, parameter in draft_module.named_parameters(): + value = target_module.get_parameter(name) + value = value.full_tensor() if isinstance(value, DTensor) else value + parameter.copy_(value.to(device=parameter.device, dtype=parameter.dtype)) + self.initialize_attentive_correction() + + def initialize_embeddings_and_head( + self, *, embed_tokens: nn.Module, lm_head: nn.Module, freeze: bool = True + ) -> None: + """Copy the target's embedding and vocabulary projection. + + Args: + embed_tokens: Target embedding with weight of shape [vocab, hidden]. + lm_head: Target output projection with weight of shape [vocab, hidden]. + freeze: Must be true: the draft shares the target's frozen embedding and head. + """ + if not freeze: + raise ValueError("DeepSeek V4.1 DFly2 requires frozen copied embedding and LM-head weights") + if self.embed_tokens.weight.shape != embed_tokens.weight.shape: + raise ValueError("DFly2 and target embedding shapes must match") + if self.lm_head.weight.shape != lm_head.weight.shape: + raise ValueError("DFly2 and target LM-head shapes must match") + with torch.no_grad(): + self.embed_tokens.weight.copy_(embed_tokens.weight.detach()) + self.lm_head.weight.copy_(lm_head.weight.detach()) + self.embed_tokens.requires_grad_(False) + self.lm_head.requires_grad_(False) + + def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: + """Project hidden states through the frozen vocabulary head in FP32. + + Args: + hidden_states: Tensor of shape [..., hidden], with arbitrary leading dimensions. + + Returns: + FP32 tensor of shape [..., vocab]. + """ + with torch.autocast(device_type=hidden_states.device.type, enabled=False): + return F.linear(hidden_states.float(), self.lm_head.weight.float()) + + def _backbone( + self, + noise_embeddings: torch.Tensor, + context_keys: Sequence[torch.Tensor], + key_indices: Sequence[torch.Tensor], + position_ids: torch.Tensor, + ) -> torch.Tensor: + """Run the draft layers on the block inputs. + + Args: + noise_embeddings: Tensor of shape [batch, draft_sequence, hidden]. + context_keys: One tensor of shape [batch, context_keys, head_dim] per layer. + key_indices: One integer tensor of shape [batch, draft_sequence, slots] per layer. + position_ids: Integer tensor of shape [batch, draft_sequence]. + + Returns: + The collapsed, not yet normalized output of shape [batch, draft_sequence, hidden]. + """ + hc_mult = self.dfly2_config.text_config.hc_mult + hidden_states = noise_embeddings.unsqueeze(2).expand(-1, -1, hc_mult, -1) + pre_mix = noise_embeddings.new_zeros(*noise_embeddings.shape[:2], hc_mult, dtype=torch.float32) + pre_mix[..., 0] = 1 + for layer, keys, indices in zip(self.layers, context_keys, key_indices): + hidden_states, pre_mix = layer(hidden_states, pre_mix, keys, indices, position_ids=position_ids) + return DeepseekV41HyperConnection.collapse(hidden_states, pre_mix) + + def forward( + self, + input_ids: torch.Tensor, + loss_mask: torch.Tensor, + context_keys: Sequence[torch.Tensor], + context_indices: Sequence[torch.Tensor], + target_last_hidden_states: torch.Tensor, + ) -> DSparkForwardOutput: + """Run DFly2 training for sampled anchors. + + Slot ``k`` of the block at anchor ``a`` predicts token ``a + k``; slot 0 holds the + anchor and is dropped from the outputs, so every output tensor covers the + ``block_size - 1`` drafted slots and its teacher is the target's distribution at + the token before the label. + + Args: + input_ids: Target-token tensor of shape [batch, sequence]. + loss_mask: Supervision tensor of shape [batch, sequence]. + context_keys: One tensor per draft layer of shape [batch, context_keys, + head_dim], as in ``DFly2TargetFeatures``. + context_indices: One integer tensor per draft layer of shape [batch, sequence, + slots], as in ``DFly2TargetFeatures``. + target_last_hidden_states: Frozen target tensor of shape [batch, sequence, + hidden], the input of the target's LM head. + + Returns: + Shared DSpark loss inputs. Draft and teacher logits have shape [batch, + num_anchors, block_size - 1, vocab]; token, mask, and confidence tensors have + shape [batch, num_anchors, block_size - 1]. + """ + batch, sequence = input_ids.shape + block_size = self.dfly2_config.block_size + if len(context_keys) != len(self.layers) or len(context_indices) != len(self.layers): + raise ValueError(f"DFly2 needs target features for {len(self.layers)} draft layers") + if target_last_hidden_states.shape[:2] != (batch, sequence): + raise ValueError("target_last_hidden_states must match input_ids [batch, sequence]") + anchor_positions, block_keep_mask = sample_anchor_positions( + seq_len=sequence, loss_mask=loss_mask, num_anchors=self.dfly2_config.num_anchors, device=input_ids.device + ) + num_blocks = anchor_positions.shape[1] + hidden = target_last_hidden_states.shape[-1] + target_last_hidden_states = target_last_hidden_states.detach() + + # Every slot's token: the anchor, then the labels a+1 .. a+block_size-1. + slot_indices = anchor_positions.unsqueeze(-1) + torch.arange(block_size, device=input_ids.device) + safe_slot_indices = torch.where( + block_keep_mask.unsqueeze(-1), slot_indices.clamp(max=sequence - 1), torch.zeros_like(slot_indices) + ) + slot_tokens = torch.gather(input_ids.unsqueeze(1).expand(-1, num_blocks, -1), 2, safe_slot_indices) + + noise_embeddings = create_noise_embed( + self.embed_tokens, + input_ids, + anchor_positions, + block_keep_mask, + mask_token_id=self.dfly2_config.mask_token_id, + block_size=block_size, + ).view(batch, num_blocks, block_size, hidden) + previous_rows = (anchor_positions - 1).clamp(min=0) + previous_hidden = torch.gather(target_last_hidden_states, 1, previous_rows.unsqueeze(-1).expand(-1, -1, hidden)) + fusion = self.mtp_fusion(noise_embeddings[:, :, 0], previous_hidden.to(noise_embeddings.dtype)) + fused_blocks = (block_keep_mask & (anchor_positions > 0)).unsqueeze(-1) + anchor_slot = noise_embeddings[:, :, :1] + torch.where(fused_blocks, fusion, 0).unsqueeze(2) + noise_embeddings = torch.cat((anchor_slot, noise_embeddings[:, :, 1:]), dim=2).flatten(1, 2) + + position_ids = create_position_ids(anchor_positions, block_size) + key_indices = [ + build_block_key_indices( + indices, + anchor_positions, + block_keep_mask, + num_context_keys=keys.shape[1], + block_size=block_size, + # The released draft attends bidirectionally within its block. + causal=False, + ) + for keys, indices in zip(context_keys, context_indices) + ] + normalized = self.final_norm(self._backbone(noise_embeddings, context_keys, key_indices, position_ids)) + + # Teacher forcing: each slot's previous token is the anchor for slots 0 and 1, then the label before it. + previous_tokens = torch.cat((slot_tokens[..., :1], slot_tokens[..., :-1]), dim=-1).flatten(1) + corrected = self.hidden_correction( + normalized, + self.embed_tokens(previous_tokens), + context_keys[-1], + context_key_indices(key_indices[-1], context_keys[-1].shape[1]), + position_ids=position_ids, + block_size=block_size, + ) + drafted = corrected.view(batch, num_blocks, block_size, hidden)[:, :, 1:] + + label_indices = slot_indices[..., 1:] + safe_label_indices = safe_slot_indices[..., 1:] + eval_mask = build_eval_mask( + seq_len=sequence, + loss_mask=loss_mask, + label_indices=label_indices, + safe_label_indices=safe_label_indices, + block_keep_mask=block_keep_mask, + ) + teacher_rows = (safe_label_indices - 1).clamp(min=0) + teacher_hidden = torch.gather( + target_last_hidden_states.unsqueeze(1).expand(-1, num_blocks, -1, -1), + 2, + teacher_rows.unsqueeze(-1).expand(-1, -1, -1, hidden), + ) + confidence_pred = None + if self.confidence_head is not None: + # The final-normalized states, as the V4.1 DSpark draft feeds its head: the raw residual + # stream of a trained draft is tens of units in RMS, which gives the head a loss and a + # gradient that dominate the clipped norm of the whole draft. + states = normalized.view(batch, num_blocks, block_size, hidden)[:, :, 1:] + if self.dfly2_config.confidence_head_stop_gradient: + states = states.detach() + confidence_pred = self.confidence_head(states) + return DSparkForwardOutput( + draft_logits=self.compute_logits(drafted), + target_ids=slot_tokens[..., 1:], + eval_mask=eval_mask, + block_keep_mask=block_keep_mask, + confidence_pred=confidence_pred, + aligned_target_logits=self.compute_logits(teacher_hidden), + ) + + +__all__ = ["DeepseekV41DFly2Config", "DeepseekV41DFly2Model", "default_dfly2_backend"] diff --git a/nemo_automodel/components/models/deepseek_v41/dfly2_target.py b/nemo_automodel/components/models/deepseek_v41/dfly2_target.py new file mode 100644 index 0000000000..c953e83548 --- /dev/null +++ b/nemo_automodel/components/models/deepseek_v41/dfly2_target.py @@ -0,0 +1,136 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""DFly2 target features of DeepSeek V4.1: the paired layers' keys and key lists. + +A ratio-1 CSA2 layer attends over ``[its FP8 sliding-window KV | the shared 1:1 compressed +KV]``: row ``r`` reads the window keys ``r - 127 .. r`` and the compressed rows its indexer +selected, offset past the window keys. The draft layer paired with it reads exactly those +keys, so this capture returns, per paired layer, that concatenated key tensor and every +row's key list in the same layout. + +The keys are taken during the frozen forward by a hook on each paired attention module, +while its parameters are still gathered under FSDP: the window keys are recomputed from +the layer's input with the layer's own projections (bitwise the values the layer used), +and the compressed KV and selection are read from the attention state it publishes. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence + +import torch +import torch.distributed as dist +import torch.nn as nn + +from nemo_automodel.components.models.deepseek_v41.attention import ( + DeepseekV41Attention, + DeepseekV41AttentionOutput, + DeepseekV41AttentionState, + _apply_rope, +) +from nemo_automodel.components.models.deepseek_v41.quantization import quantize_cache +from nemo_automodel.components.speculative.dfly2.common import DFly2TargetFeatures + + +def _window_key_indices(valid: torch.Tensor, window: int) -> torch.Tensor: + """List each row's sliding-window keys: the last ``window`` tokens up to and including the row. + + Args: + valid: Boolean tensor of shape [batch, sequence], false at right padding. + window: Window width. + + Returns: + Long tensor of shape [batch, sequence, min(window, sequence)] of token rows, ``-1`` + where the slot falls before the sequence start or on padding. + """ + batch, sequence = valid.shape + positions = torch.arange(sequence, device=valid.device) + slots = (positions - window + 1).clamp_min(0).unsqueeze(-1) + torch.arange( + min(window, sequence), device=valid.device + ) + visible = slots <= positions.unsqueeze(-1) + safe = slots.clamp_max(sequence - 1) + visible = visible.unsqueeze(0) & valid.gather(1, safe.flatten().expand(batch, -1)).view(batch, *slots.shape) + return torch.where(visible, slots.unsqueeze(0), -1) + + +def dfly2_target_features( + model: nn.Module, input_ids: torch.Tensor, *, attention_mask: torch.Tensor, layer_ids: Sequence[int] +) -> DFly2TargetFeatures: + """Run the frozen V4.1 target and capture the DFly2 features of the paired layers. + + Args: + model: ``DeepseekV41ForCausalLM`` target, text only, without context parallelism. + input_ids: Integer tensor of shape [batch, sequence]. + attention_mask: Binary right-padding tensor of shape [batch, sequence]. + layer_ids: Paired ratio-1 layers, in draft-layer order. + + Returns: + Features whose ``context_keys[i]`` has shape [batch, 2 * sequence, head_dim] (the + window KV, then the compressed KV) and ``context_indices[i]`` shape [batch, + sequence, window + index_topk] (window rows, then selected rows offset by + ``sequence``), plus the final normalized hidden state [batch, sequence, hidden]. + + Raises: + ValueError: A paired layer is not a ratio-1 layer. + """ + text_config = model.config.text_config + layers = model.model.layers + captured: dict[int, tuple[torch.Tensor, torch.Tensor, torch.Tensor]] = {} + last_hidden: list[torch.Tensor] = [] + + def _capture(layer_id: int) -> Callable[..., None]: + def _hook( + module: DeepseekV41Attention, + args: tuple[torch.Tensor, ...], + kwargs: dict[str, torch.Tensor | DeepseekV41AttentionState | dist.ProcessGroup | bool | None], + output: DeepseekV41AttentionOutput, + ) -> None: + """Record the keys of a layer whose input has shape [batch, sequence, hidden].""" + hidden_states = args[0] if args else kwargs["hidden_states"] + angles = module.rotary_emb(kwargs["position_ids"]) + window = quantize_cache( + _apply_rope(module.kv_norm(module.wkv(hidden_states)), angles), format="fp8", block_size=32 + ) + captured[layer_id] = (window, output.state.compressed_kv, output.state.topk_indices) + + return _hook + + handles = [] + for layer_id in layer_ids: + if text_config.compress_ratios[layer_id] != 1: + raise ValueError(f"DFly2 pairs ratio-1 target layers; layer {layer_id} is not one") + handles.append(layers[str(layer_id)].attn.register_forward_hook(_capture(layer_id), with_kwargs=True)) + handles.append(model.model.norm.register_forward_hook(lambda _module, _inputs, output: last_hidden.append(output))) + try: + model(input_ids, attention_mask=attention_mask, logits_to_keep=1) + finally: + for handle in handles: + handle.remove() + + sequence = input_ids.shape[1] + window_indices = _window_key_indices(attention_mask.bool(), text_config.sliding_window) + context_keys, context_indices = [], [] + for layer_id in layer_ids: + window, compressed, selected = captured[layer_id] + context_keys.append(torch.cat((window, compressed.to(window.dtype)), dim=1)) + picks = torch.where(selected >= 0, selected + sequence, -1) + context_indices.append(torch.cat((window_indices, picks), dim=-1).to(torch.int32)) + return DFly2TargetFeatures( + context_keys=tuple(context_keys), context_indices=tuple(context_indices), last_hidden_states=last_hidden[0] + ) + + +__all__ = ["dfly2_target_features"] diff --git a/nemo_automodel/components/models/deepseek_v41/model.py b/nemo_automodel/components/models/deepseek_v41/model.py index 474f47bf4b..52b4ce5fb6 100644 --- a/nemo_automodel/components/models/deepseek_v41/model.py +++ b/nemo_automodel/components/models/deepseek_v41/model.py @@ -39,11 +39,11 @@ from __future__ import annotations import math -from collections.abc import Callable +from collections.abc import Callable, Sequence from contextlib import AbstractContextManager from dataclasses import dataclass from functools import partial -from typing import Any +from typing import TYPE_CHECKING, Any import torch import torch.distributed as dist @@ -114,6 +114,9 @@ from nemo_automodel.components.moe.layers import MoE from nemo_automodel.shared.utils import dtype_from_str +if TYPE_CHECKING: + from nemo_automodel.components.speculative.dfly2.common import DFly2TargetFeatures + class DeepseekV41Block(nn.Module): """CSA2 and MoE sublayers with the single-pass mHC coefficient handoff.""" @@ -740,6 +743,23 @@ def get_dspark_target_feature_modules(self, layer_ids: list[int]) -> tuple[nn.Mo ) return tuple(self.model.layers[str(layer_id)].attn_hc for layer_id in layer_ids) + def dfly2_target_features( + self, input_ids: torch.Tensor, *, attention_mask: torch.Tensor, layer_ids: Sequence[int] + ) -> DFly2TargetFeatures: + """Run the frozen forward and return the keys and key lists of the layers paired with a DFly2 draft. + + Args: + input_ids: Integer tensor of shape [batch, sequence]. + attention_mask: Binary right-padding tensor of shape [batch, sequence]. + layer_ids: Paired ratio-1 layers, in draft-layer order. + + Returns: + Features documented by :func:`dfly2_target.dfly2_target_features`. + """ + from nemo_automodel.components.models.deepseek_v41.dfly2_target import dfly2_target_features + + return dfly2_target_features(self, input_ids, attention_mask=attention_mask, layer_ids=layer_ids) + def _nemo_prepare_model_owned_dtensors(self, fsdp_mesh: DeviceMesh) -> set[nn.Parameter]: """Register owner table DTensors before FSDP records ignored parameters. diff --git a/nemo_automodel/components/models/deepseek_v41/state_dict_adapter.py b/nemo_automodel/components/models/deepseek_v41/state_dict_adapter.py index 586d01ed70..9e07e83653 100644 --- a/nemo_automodel/components/models/deepseek_v41/state_dict_adapter.py +++ b/nemo_automodel/components/models/deepseek_v41/state_dict_adapter.py @@ -679,6 +679,13 @@ class DeepseekV41DSparkStateDictAdapter(MoESplitExpertsStateDictMixin, StateDict """Convert the released ``mtp.*`` DSpark weights for training and export.""" _supports_low_memory_dcp_load = False + # Native name of the draft's layer list, and the released-name patterns that differ per draft layout. + _native_layers = "mtp" + _expert_fqn_pattern = _DSPARK_EXPERT_PATTERN + _released_expert_pattern = re.compile(r"mtp\.\d+\.ffn\.experts\.(\d+)\.") + _quantized_released_pattern = re.compile( + r"mtp\.\d+\.(?:attn\.(?:wq_a|wq_b|wkv|wo_a|wo_b)|main_proj|ffn\.(?:shared_experts|experts\.\d+)\.w[123])\.weight" + ) def __init__( self, @@ -693,6 +700,22 @@ def __init__( self.dtype = dtype self._uses_model_prefix = False + def _to_native_key(self, key: str) -> str: + """Map one released draft tensor name to the native draft namespace.""" + return _dspark_native_key(key) + + def _to_released_key(self, key: str) -> str: + """Map one native draft parameter name to the released checkpoint namespace.""" + return _dspark_released_key(key) + + def _to_layer_namespace(self, key: str) -> str: + """Rename the native layer list to ``layers.``, the namespace of the split-expert helpers.""" + return re.sub(rf"^{self._native_layers}\.(\d+)\.", r"layers.\1.", key) + + def _from_layer_namespace(self, key: str) -> str: + """Undo :meth:`_to_layer_namespace`.""" + return re.sub(r"^layers\.(\d+)\.", rf"{self._native_layers}.\1.", key) + @property def _expert_path_segment(self) -> str: return "ffn.experts" @@ -700,7 +723,7 @@ def _expert_path_segment(self) -> str: @property def view_loaded_native_keys(self) -> set[str]: """Return native DSpark keys populated through checkpoint views.""" - return {re.sub(r"^layers\.(\d+)\.", r"mtp.\1.", key) for key in super().view_loaded_native_keys} + return {self._from_layer_namespace(key) for key in super().view_loaded_native_keys} def is_draft_checkpoint_key(self, key: str) -> bool: """Return whether a tensor in a released checkpoint belongs to the draft.""" @@ -710,16 +733,16 @@ def get_hf_state_dict_keys(self, state_dict: dict[str, Any]) -> list[str]: """Return released names for the draft's native state-dict keys.""" keys: list[str] = [] for fqn in state_dict: - expert = _DSPARK_EXPERT_PATTERN.fullmatch(fqn) + expert = self._expert_fqn_pattern.fullmatch(fqn) if expert: - projections = (1, 3) if expert[2] == "gate_and_up_projs" else (2,) + projections = ("gate_proj", "up_proj") if expert[2] == "gate_and_up_projs" else ("down_proj",) keys.extend( - f"mtp.{expert[1]}.ffn.experts.{index}.w{projection}.weight" + self._to_released_key(f"{self._native_layers}.{expert[1]}.ffn.experts.{index}.{projection}.weight") for index in range(self.moe_config.n_routed_experts) for projection in projections ) elif "_extra_state" not in fqn: - keys.append(_dspark_released_key(fqn)) + keys.append(self._to_released_key(fqn)) return keys def from_hf( @@ -743,7 +766,7 @@ def from_hf( 2 * expert_hidden] and [experts, expert_hidden, hidden]. """ for key in list(hf_state_dict): - expert = re.match(r"mtp\.\d+\.ffn\.experts\.(\d+)\.", key) + expert = self._released_expert_pattern.match(key) nonlocal_expert = expert is not None and not should_load_expert_for_rank( int(expert[1]), device_mesh, self.moe_config.n_routed_experts ) @@ -757,17 +780,16 @@ def from_hf( value = hf_state_dict.pop(key) if key.endswith(".scale"): raise ValueError(f"Checkpoint scale {key} has no matching weight") - native_key = _dspark_native_key(key) + native_key = self._to_native_key(key) if ".ffn.experts." in native_key: - pseudo_key = re.sub(r"^mtp\.(\d+)\.", r"layers.\1.", native_key) - expert_state[pseudo_key] = value + expert_state[self._to_layer_namespace(native_key)] = value else: if native_key in converted: raise ValueError(f"Multiple checkpoint tensors map to {native_key}") converted[native_key] = value merged = self._from_hf_w_merged_experts(expert_state, device_mesh) - converted.update({re.sub(r"^layers\.(\d+)\.", r"mtp.\1.", key): value for key, value in merged.items()}) + converted.update({self._from_layer_namespace(key): value for key, value in merged.items()}) return converted def _dequantize(self, state_dict: dict[str, Any]) -> None: @@ -816,34 +838,26 @@ def convert_single_tensor_to_hf(self, fqn: str, tensor: Any, **kwargs: Any) -> l "Quantization targets are for checkpoint loading only; export trained weights without quantization" ) - expert = _DSPARK_EXPERT_PATTERN.fullmatch(fqn) + expert = self._expert_fqn_pattern.fullmatch(fqn) if expert: - pseudo_fqn = re.sub(r"^mtp\.(\d+)\.", r"layers.\1.", fqn) result = self._convert_single_merged_expert_to_hf_split_experts( - pseudo_fqn, + self._to_layer_namespace(fqn), tensor, for_checkpoint_load=kwargs.get("for_checkpoint_load", False), quantization=quantization, ) if result is None: raise RuntimeError(f"Could not convert DSpark expert tensor {fqn}") - released = [ - (_dspark_released_key(re.sub(r"^layers\.(\d+)\.", r"mtp.\1.", key)), value) for key, value in result - ] + released = [(self._to_released_key(self._from_layer_namespace(key)), value) for key, value in result] else: - released = [(_dspark_released_key(fqn), tensor)] + released = [(self._to_released_key(fqn), tensor)] exclude = kwargs.get("exclude_key_regex") converted: list[tuple[str, Any]] = [] for key, value in released: if exclude and re.match(exclude, key): continue - quantized = re.fullmatch( - r"mtp\.\d+\.(?:attn\.(?:wq_a|wq_b|wkv|wo_a|wo_b)" - r"|main_proj|ffn\.(?:shared_experts|experts\.\d+)\.w[123])\.weight", - key, - ) - if quantization and quantized: + if quantization and self._quantized_released_pattern.fullmatch(key): converted.extend(DeepseekV41StateDictAdapter._quantized_load_targets(key, value)) else: converted.append((key, value)) @@ -852,7 +866,48 @@ def convert_single_tensor_to_hf(self, fqn: str, tensor: Any, **kwargs: Any) -> l def forced_hf_dtype_mapping(self, state_dict: dict[str, Any]) -> dict[str, str]: """Return released draft keys whose trained values must remain FP32.""" return { - _dspark_released_key(key): "float32" + self._to_released_key(key): "float32" for key, value in state_dict.items() if isinstance(value, torch.Tensor) and value.dtype == torch.float32 } + + +# FP32 holders of the DFly2 attentive correction, stored as plain tensors in the release. +_DFLY2_CORRECTION_HOLDER = re.compile( + r"(\.attention\.(?:attn_sink|block_sink|block_rel_bias|block_gate_bias))\.weight$" +) + + +class DeepseekV41DFly2StateDictAdapter(DeepseekV41DSparkStateDictAdapter): + """Convert the released DFly2 draft for training and export. + + The release names every tensor under ``model.``: the draft layers as the target's own + layers (``model.layers.{i}.attn.wq_a.weight``, ``hc_attn_fn``, split ``ffn.experts.{e}.w1`` + in FP4) and the heads by their module path (``model.mtp_fusion.gate``, + ``model.hidden_correction.attention.block_sink``). Native names drop the prefix and use + the target's native layer names. + """ + + _native_layers = "layers" + _expert_fqn_pattern = re.compile(r"^layers\.(\d+)\.ffn\.experts\.(gate_and_up_projs|down_projs)$") + _released_expert_pattern = re.compile(r"model\.layers\.\d+\.ffn\.experts\.(\d+)\.") + # Only the routed experts are quantized in the release. + _quantized_released_pattern = re.compile(r"model\.layers\.\d+\.ffn\.experts\.\d+\.w[123]\.weight") + + def is_draft_checkpoint_key(self, key: str) -> bool: + """Return whether a tensor in a released checkpoint belongs to the draft.""" + return key.startswith("model.") + + def _to_native_key(self, key: str) -> str: + """Map one released DFly2 tensor name to the native draft namespace.""" + key = key.removeprefix("model.") + if key.startswith("layers."): + return _native_key(key).removeprefix("model.") + holder = key + ".weight" + return holder if _DFLY2_CORRECTION_HOLDER.search(holder) else key + + def _to_released_key(self, key: str) -> str: + """Map one native DFly2 parameter name to the released checkpoint namespace.""" + if key.startswith("layers."): + return "model." + _released_key(key) + return "model." + _DFLY2_CORRECTION_HOLDER.sub(r"\1", key) diff --git a/nemo_automodel/components/speculative/dfly2/__init__.py b/nemo_automodel/components/speculative/dfly2/__init__.py new file mode 100644 index 0000000000..44cf2595dd --- /dev/null +++ b/nemo_automodel/components/speculative/dfly2/__init__.py @@ -0,0 +1,38 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""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. +""" + +from nemo_automodel.components.speculative.dfly2.common import DFly2TargetFeatures, build_block_key_indices +from nemo_automodel.components.speculative.dfly2.core import DFly2TrainerModule +from nemo_automodel.components.speculative.dfly2.target import ( + DFly2TargetFeatureProvider, + DFly2TargetModel, + ModelOwnedDFly2Provider, +) + +__all__ = [ + "DFly2TargetFeatureProvider", + "DFly2TargetFeatures", + "DFly2TargetModel", + "DFly2TrainerModule", + "ModelOwnedDFly2Provider", + "build_block_key_indices", +] diff --git a/nemo_automodel/components/speculative/dfly2/common.py b/nemo_automodel/components/speculative/dfly2/common.py new file mode 100644 index 0000000000..fc626ff24a --- /dev/null +++ b/nemo_automodel/components/speculative/dfly2/common.py @@ -0,0 +1,162 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Code provenance: the draft-key part of ``build_block_key_indices`` is adapted from +# Tencent/AngelSpec, https://github.com/Tencent/AngelSpec at revision e02ea36e65d44e6e165c4ba73c139d500e12f2d9, +# file angelspec/models/dflash.py (``_create_dflash_sparse_kv_indices``), which carries this notice: +# +# Copyright (c) 2026 LightSeek Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Target features and key lists shared by every DFly2 draft. + +A DFly2 draft layer owns no context projection. It is paired with one sparse-attention +layer of the target and reads that layer's own keys (KV sharing) at the positions that +layer attends from the row before the anchor (index sharing). The target therefore hands +the draft, per paired layer, the key tensor it attended over and the key list of every +row; the draft keeps the row before each anchor and appends its own block. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch +import torch.nn.functional as F + +# Key lists are padded to a multiple of this width, matching the sparse attention kernels. +KEY_LIST_ALIGNMENT = 64 + + +@dataclass(frozen=True) +class DFly2TargetFeatures: + """Frozen target state one DFly2 training step reads. + + Attributes: + context_keys: 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). + context_indices: 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. + last_hidden_states: Tensor of shape [batch, sequence, hidden], the target's final + normalized hidden state (the input of its LM head). + """ + + context_keys: tuple[torch.Tensor, ...] + context_indices: tuple[torch.Tensor, ...] + last_hidden_states: torch.Tensor + + def __post_init__(self) -> None: + if len(self.context_keys) != len(self.context_indices): + raise ValueError("DFly2 target features need one key tensor per key-list tensor") + batch, sequence = self.last_hidden_states.shape[:2] + for keys, indices in zip(self.context_keys, self.context_indices): + if keys.shape[0] != batch or indices.shape[:2] != (batch, sequence): + raise ValueError("DFly2 context keys and key lists must match last_hidden_states [batch, sequence]") + + +def 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. + + Args: + context_indices: Integer tensor of shape [batch, sequence, slots] with ``-1`` + unused, as in :class:`DFly2TargetFeatures`. + anchor_positions: Integer tensor of shape [batch, num_anchors]. + block_keep_mask: Boolean tensor of shape [batch, num_anchors]. + num_context_keys: Number of context rows preceding the draft keys. + block_size: Draft slots per block, the anchor slot included. + causal: Whether a draft query sees only the earlier slots of its block. + + Returns: + Int32 tensor of shape [batch, num_anchors * block_size, padded_slots], the context + slots followed by ``block_size`` draft slots, ``-1`` padded to a multiple of + :data:`KEY_LIST_ALIGNMENT`. + """ + batch, num_anchors = anchor_positions.shape + device = anchor_positions.device + rows = (anchor_positions - 1).clamp(min=0) + context = torch.gather( + context_indices, 1, rows.unsqueeze(-1).expand(-1, -1, context_indices.shape[-1]).to(torch.long) + ) + has_context = block_keep_mask & (anchor_positions > 0) + context = torch.where(has_context.unsqueeze(-1), context, -1).repeat_interleave(block_size, dim=1) + + # Block j's draft keys are rows num_context_keys + j * block_size + (0 .. block_size - 1); + # each of its block_size queries lists all of them, or its prefix when causal. + block_rows = num_context_keys + torch.arange(num_anchors * block_size, device=device).view(num_anchors, block_size) + own_block = block_rows.unsqueeze(1).expand(-1, block_size, -1) + allowed = block_keep_mask.view(batch, num_anchors, 1, 1).expand(-1, -1, block_size, block_size) + if causal: + allowed = allowed & torch.ones(block_size, block_size, dtype=torch.bool, device=device).tril() + draft = torch.where(allowed, own_block, -1).flatten(1, 2) + + indices = torch.cat((context.to(torch.int32), draft.to(torch.int32)), dim=-1) + return F.pad(indices, (0, -indices.shape[-1] % KEY_LIST_ALIGNMENT), value=-1) + + +def context_key_indices(key_indices: torch.Tensor, num_context_keys: int) -> torch.Tensor: + """Keep only the context slots of draft key lists, masking the block's own keys. + + Args: + key_indices: Integer tensor of shape [batch, queries, slots] from + :func:`build_block_key_indices`. + num_context_keys: Number of context rows preceding the draft keys. + + Returns: + Tensor with the shape and dtype of ``key_indices`` where every draft-key slot is ``-1``. + """ + return torch.where(key_indices < num_context_keys, key_indices, -1) + + +__all__ = [ + "DFly2TargetFeatures", + "KEY_LIST_ALIGNMENT", + "build_block_key_indices", + "context_key_indices", +] diff --git a/nemo_automodel/components/speculative/dfly2/core.py b/nemo_automodel/components/speculative/dfly2/core.py new file mode 100644 index 0000000000..aededc7f3a --- /dev/null +++ b/nemo_automodel/components/speculative/dfly2/core.py @@ -0,0 +1,107 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""DFly2 online training wrapper. + +Like DSpark's, the draft is self-contained (anchors, key lists, backbone, corrections), so +this wrapper only calls it with the frozen target features and computes the DFly2 +objective. It reports :class:`DSparkStepMetrics` so the DSpark recipe's metric window, +evaluation and logging apply unchanged. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from nemo_automodel.components.speculative.dfly2.loss import compute_dfly2_loss +from nemo_automodel.components.speculative.dspark.core import DSparkStepMetrics + + +class DFly2TrainerModule(nn.Module): + """DFly2 online training wrapper computing the D-PACE-weighted LK objective.""" + + def __init__( + self, + draft_model: nn.Module, + *, + dpace_alpha: float = 0.5, + lk_eta: float = 3.0, + confidence_head_alpha: float = 0.0, + ) -> None: + super().__init__() + if not 0.0 <= dpace_alpha <= 1.0: + raise ValueError(f"dpace_alpha must be in [0, 1], got {dpace_alpha}") + self.draft_model = draft_model + self.dpace_alpha = float(dpace_alpha) + self.lk_eta = float(lk_eta) + self.confidence_head_alpha = float(confidence_head_alpha) + + def forward( + self, + input_ids: torch.Tensor, + loss_mask: torch.Tensor, + context_keys: Sequence[torch.Tensor], + context_indices: Sequence[torch.Tensor], + target_last_hidden_states: torch.Tensor, + ) -> DSparkStepMetrics: + """Run the draft on the target features and compute the DFly2 loss. + + Args: + input_ids: Target-token tensor of shape [batch, sequence]. + loss_mask: Supervision tensor of shape [batch, sequence]. + context_keys: One tensor per draft layer of shape [batch, context_keys, + key_dim], as in :class:`DFly2TargetFeatures`. + context_indices: One integer tensor per draft layer of shape [batch, + sequence, slots], as in :class:`DFly2TargetFeatures`. + target_last_hidden_states: Tensor of shape [batch, sequence, hidden]. + + Returns: + Step metrics. The per-position acceptance sums have ``block_size`` entries, + entry ``k`` for the ``k``-th drafted token; the anchor slot is not drafted, + so the last entry stays zero and is not logged. + """ + outputs = self.draft_model( + input_ids=input_ids, + loss_mask=loss_mask, + context_keys=context_keys, + context_indices=context_indices, + target_last_hidden_states=target_last_hidden_states, + ) + loss, terms = compute_dfly2_loss( + outputs=outputs, + dpace_alpha=self.dpace_alpha, + lk_eta=self.lk_eta, + confidence_head_alpha=self.confidence_head_alpha, + ) + return DSparkStepMetrics( + loss=loss, + ce_loss=terms["ce_loss"], + l1_loss=terms["l1_loss"], + confidence_loss=terms["confidence_loss"], + accept_rate_per_pos_num=F.pad(terms["accept_rate_per_pos_num"], (0, 1)), + accept_rate_per_pos_den=F.pad(terms["accept_rate_per_pos_den"], (0, 1)), + tau_num=terms["tau_num"], + tau_den=terms["tau_den"], + confidence_abs_error_num=terms["confidence_abs_error_num"], + confidence_bias_num=terms["confidence_bias_num"], + confidence_cumprod_bias_num=terms["confidence_cumprod_bias_num"], + confidence_diag_den=terms["confidence_diag_den"], + ) + + +__all__ = ["DFly2TrainerModule"] diff --git a/nemo_automodel/components/speculative/dfly2/loss.py b/nemo_automodel/components/speculative/dfly2/loss.py new file mode 100644 index 0000000000..6abb62195a --- /dev/null +++ b/nemo_automodel/components/speculative/dfly2/loss.py @@ -0,0 +1,210 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""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). +""" + +from __future__ import annotations + +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch.utils.checkpoint import checkpoint + +from nemo_automodel.components.loss.dllm_loss import dpace_position_weights +from nemo_automodel.components.speculative.dspark.common import DSparkForwardOutput +from nemo_automodel.components.speculative.dspark.loss import _collect_acceptance_diagnostics + +_PROBABILITY_CHUNK_TOKENS = 128 + + +def _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. + + Args: + draft_logits: Tensor of shape [tokens, vocab]. + target_logits: Tensor of shape [tokens, vocab]. + + Returns: + ``(tv, kl)``, each of shape [tokens]. + """ + draft_log_probs = torch.log_softmax(draft_logits.float(), dim=-1) + target_log_probs = torch.log_softmax(target_logits.float(), dim=-1) + target_probs = target_log_probs.exp() + tv = 0.5 * (target_probs - draft_log_probs.exp()).abs().sum(dim=-1) + kl = (target_probs * (target_log_probs - draft_log_probs)).sum(dim=-1) + return tv, kl + + +def _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. + + Args: + draft_logits: Tensor of shape [..., vocab]. + target_logits: Tensor of shape [..., vocab], detached. + chunk_size: Slots per chunk. + + Returns: + ``(tv, kl)``, each of shape [...]. + """ + output_shape = draft_logits.shape[:-1] + vocab_size = draft_logits.shape[-1] + flat_draft = draft_logits.reshape(-1, vocab_size) + flat_target = target_logits.reshape(-1, vocab_size) + tvs, kls = [], [] + for start in range(0, flat_draft.shape[0], chunk_size): + draft_chunk = flat_draft[start : start + chunk_size] + target_chunk = flat_target[start : start + chunk_size] + if torch.is_grad_enabled() and draft_chunk.requires_grad: + tv, kl = checkpoint( + _distance_chunk, draft_chunk, target_chunk, use_reentrant=False, preserve_rng_state=False + ) + else: + tv, kl = _distance_chunk(draft_chunk, target_chunk) + tvs.append(tv) + kls.append(kl) + return torch.cat(tvs).reshape(output_shape), torch.cat(kls).reshape(output_shape) + + +@torch.no_grad() +def _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. + + Args: + draft_logits: Tensor of shape [..., vocab]. + target_ids: Integer tensor of shape [...]. + chunk_size: Slots per chunk. + + Returns: + Tensor of shape [...]. + """ + flat_logits = draft_logits.reshape(-1, draft_logits.shape[-1]) + flat_targets = target_ids.reshape(-1) + losses = [ + F.cross_entropy( + flat_logits[start : start + chunk_size].float(), flat_targets[start : start + chunk_size], reduction="none" + ) + for start in range(0, flat_logits.shape[0], chunk_size) + ] + return torch.cat(losses).view_as(target_ids) + + +def compute_dfly2_loss( + *, + outputs: 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. + + Args: + outputs: 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: D-PACE smoothing in ``[0, 1]``. + lk_eta: Sharpness of the LK mixing weight; larger values switch to TV sooner. + confidence_head_alpha: Weight of the confidence loss; ignored without a head. + + Returns: + The backward loss (scaled by the data-parallel world size, see the module + docstring) and detached terms: ``loss``, ``ce_loss`` (the corpus cross entropy, + logged only), ``l1_loss`` (the TV term), ``lk_loss``, ``confidence_loss``, and the + unreduced acceptance-diagnostic sums of the DSpark objective. + + Raises: + ValueError: ``aligned_target_logits`` is missing. + """ + if outputs.aligned_target_logits is None: + raise ValueError("DFly2 distills from the target: aligned_target_logits is required") + draft_logits = outputs.draft_logits + target_logits = outputs.aligned_target_logits.detach() + eval_mask = outputs.eval_mask + mask = eval_mask.to(torch.float32) + + token_ce = _token_cross_entropy(draft_logits, outputs.target_ids) + weights = dpace_position_weights(token_ce, mask, eval_mask, dpace_alpha=dpace_alpha) * mask + tv, kl = _compute_distances(draft_logits, target_logits) + mixing = torch.exp(-float(lk_eta) * (1.0 - tv).detach()) + lk = mixing * kl + (1.0 - mixing) * tv + accept_rate = (1.0 - tv).detach().clamp(0.0, 1.0) + + has_confidence = outputs.confidence_pred is not None + confidence = mask.new_zeros(()) + if has_confidence: + errors = F.binary_cross_entropy_with_logits(outputs.confidence_pred.float(), accept_rate, reduction="none") + confidence = (errors * weights).sum() + + local_denominator = weights.sum() + global_denominator = local_denominator.detach().clone() + world_size = dist.get_world_size() if dist.is_initialized() else 1 + if world_size > 1: + dist.all_reduce(global_denominator, op=dist.ReduceOp.SUM) + numerator = (lk * weights).sum() + float(confidence_head_alpha) * confidence + backward_loss = numerator / (global_denominator + 1e-6) * world_size + + local = 1.0 / (local_denominator.detach() + 1e-6) + terms = { + "loss": numerator.detach() * local, + "ce_loss": (token_ce * weights).sum().detach() * local, + "l1_loss": (tv * weights).sum().detach() * local, + "lk_loss": (lk * weights).sum().detach() * local, + "confidence_loss": confidence.detach() * local, + } + with torch.no_grad(): + diagnostics = _collect_acceptance_diagnostics( + outputs=outputs, accept_rate_3d=accept_rate, loss_weight_mask=weights, has_confidence=has_confidence + ) + terms["accept_rate_per_pos_num"] = diagnostics["accept_rate_pos_num"] + terms["accept_rate_per_pos_den"] = diagnostics["accept_rate_pos_den"] + for key in ( + "tau_num", + "tau_den", + "confidence_abs_error_num", + "confidence_bias_num", + "confidence_cumprod_bias_num", + "confidence_diag_den", + ): + terms[key] = diagnostics[key] + return backward_loss, terms + + +__all__ = ["compute_dfly2_loss"] diff --git a/nemo_automodel/components/speculative/dfly2/target.py b/nemo_automodel/components/speculative/dfly2/target.py new file mode 100644 index 0000000000..fea3f10bc9 --- /dev/null +++ b/nemo_automodel/components/speculative/dfly2/target.py @@ -0,0 +1,128 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Model-owned contracts and the frozen-target wrapper for DFly2 training. + +DFly2 reads the target's own attention state, whose layout is architecture specific, so +the target model produces it (:class:`DFly2TargetFeatureProvider`) and the target config +builds the matching draft (:class:`ModelOwnedDFly2Provider`). This module only names those +contracts and runs the frozen forward. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Protocol, runtime_checkable + +import torch +import torch.nn as nn + +from nemo_automodel.components.speculative.dfly2.common import DFly2TargetFeatures + + +class _DFly2DraftOptions(Protocol): + """Recipe options consumed by model-owned DFly2 draft constructors.""" + + target_layer_ids: list[int] + block_size: int + num_anchors: int + mask_token_id: int + enable_confidence_head: bool + confidence_head_stop_gradient: bool + attn_backend: str + + +@runtime_checkable +class ModelOwnedDFly2Provider(Protocol): + """Target config that owns construction of its architecture-specific DFly2 draft.""" + + def build_dfly2_draft(self, options: _DFly2DraftOptions) -> nn.Module: + """Build a draft from the recipe's declarative options.""" + + +@runtime_checkable +class DFly2TargetFeatureProvider(Protocol): + """Target model that exposes the attention state its paired DFly2 draft layers read.""" + + def dfly2_target_features( + self, input_ids: torch.Tensor, *, attention_mask: torch.Tensor, layer_ids: Sequence[int] + ) -> DFly2TargetFeatures: + """Run the frozen forward and return the paired layers' keys and key lists. + + Args: + input_ids: Integer tensor of shape [batch, sequence]. + attention_mask: Binary right-padding tensor of shape [batch, sequence]. + layer_ids: Target layers paired with the draft layers, in draft-layer order. + """ + + +@dataclass +class DFly2TargetBatch: + """Target features and the batch tensors the DFly2 trainer reads. + + Attributes: + features: Frozen target state, documented by :class:`DFly2TargetFeatures`. + input_ids: Integer tensor of shape [batch, sequence]. + loss_mask: Tensor of shape [batch, sequence] selecting supervised tokens. + """ + + features: DFly2TargetFeatures + input_ids: torch.Tensor + loss_mask: torch.Tensor + + +class DFly2TargetModel: + """Run a frozen target that implements :class:`DFly2TargetFeatureProvider`.""" + + def __init__(self, model: nn.Module, target_layer_ids: Sequence[int]) -> None: + if not isinstance(model, DFly2TargetFeatureProvider): + raise TypeError(f"{type(model).__name__} does not provide DFly2 target features") + self.model = model.eval() + self.target_layer_ids = [int(layer_id) for layer_id in target_layer_ids] + + def get_input_embeddings(self) -> nn.Module: + """Return the target's input embedding.""" + return self.model.get_input_embeddings() + + def get_output_embeddings(self) -> nn.Module: + """Return the target's LM head.""" + return self.model.get_output_embeddings() + + @torch.no_grad() + def generate_batch( + self, input_ids: torch.Tensor, attention_mask: torch.Tensor, loss_mask: torch.Tensor + ) -> DFly2TargetBatch: + """Run the target once and collect the DFly2 features. + + Args: + input_ids: Integer tensor of shape [batch, sequence]. + attention_mask: Binary right-padding tensor of shape [batch, sequence]. + loss_mask: Tensor of shape [batch, sequence] selecting supervised tokens. + + Returns: + The batch with the features of :meth:`DFly2TargetFeatureProvider.dfly2_target_features`. + """ + features = self.model.dfly2_target_features( + input_ids, attention_mask=attention_mask, layer_ids=self.target_layer_ids + ) + return DFly2TargetBatch(features=features, input_ids=input_ids, loss_mask=loss_mask) + + +__all__ = [ + "DFly2TargetBatch", + "DFly2TargetFeatureProvider", + "DFly2TargetModel", + "ModelOwnedDFly2Provider", +] diff --git a/nemo_automodel/recipes/speculative_decoding/train_dfly2.py b/nemo_automodel/recipes/speculative_decoding/train_dfly2.py new file mode 100644 index 0000000000..8c4d9748b0 --- /dev/null +++ b/nemo_automodel/recipes/speculative_decoding/train_dfly2.py @@ -0,0 +1,190 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""DFly2 draft-model training recipe (DeepSeek V4.1 targets). + +DFly2 (arXiv:2611.34776) is a block-parallel drafter for sparse-attention targets. Each +draft layer is paired with one target sparse-attention layer and reads that layer's own +keys at the positions it attends from the row before the anchor, so the served drafter +shares the target's KV cache and indexer instead of keeping its own. See +``nemo_automodel.components.speculative.dfly2``. + +This recipe reuses every piece of the DSpark recipe -- the frozen EP/FSDP target, anchor +sampling, gradient accumulation with a trailing-window flush, metrics, and checkpointing +-- and swaps in the model-owned DFly2 draft, the target capture of the paired layers' +keys and key lists, and the D-PACE-weighted LK objective. ``target_layer_ids`` names the +paired target layers, one per draft layer. +""" + +from __future__ import annotations + +import json +import logging +from pathlib import Path + +import torch + +from nemo_automodel.components.config._arg_parser import parse_args_and_load_config +from nemo_automodel.components.config.loader import ConfigNode +from nemo_automodel.components.speculative.dfly2 import DFly2TargetModel, DFly2TrainerModule, ModelOwnedDFly2Provider +from nemo_automodel.components.speculative.dspark.core import DSparkStepMetrics +from nemo_automodel.components.speculative.dspark.registry import ModelOwnedDSparkProvider +from nemo_automodel.components.speculative.dspark.target import _DSparkPackedForward +from nemo_automodel.recipes.speculative_decoding.train_dspark import TrainDSparkRecipe, _DraftArgs + +logger = logging.getLogger(__name__) + + +def check_dfly2_checkpoint_settings( + path: str, *, target_layer_ids: list[int], block_size: int, mask_token_id: int +) -> None: + """Refuse warm-start weights whose recorded DFly2 settings differ from this run's. + + The paired target layers, the block size and the mask token own no tensors, so a draft + trained with others loads cleanly and then reads the wrong keys. A released draft and an + export of this recipe record them in ``config.json`` under ``dfly_config``. + + Args: + path: The configured ``draft_weights_path``, a directory or a ``.safetensors`` file. + target_layer_ids: Paired target layers of this run, in draft-layer order. + block_size: Draft slots per block of this run. + mask_token_id: Mask token of this run. + + Raises: + ValueError: A recorded setting differs from this run's. + """ + root = Path(path) + directory = root if root.is_dir() else root.parent + # A consolidated export holds config.json; a step checkpoint's model/ keeps it in .hf_metadata/. + candidates = (directory / "config.json", directory / ".hf_metadata" / "config.json") + config_path = next((candidate for candidate in candidates if candidate.is_file()), None) + if config_path is None: + return + recorded = json.loads(config_path.read_text()).get("dfly_config") + if not recorded: + return + expected = { + "target_kv_layers": [int(layer_id) for layer_id in target_layer_ids], + "block_size": int(block_size), + "mask_token_id": int(mask_token_id), + } + mismatched = { + name: {"checkpoint": recorded[name], "this run": value} + for name, value in expected.items() + if name in recorded and recorded[name] != value + } + if mismatched: + raise ValueError(f"draft_weights_path={path!r} was trained with other DFly2 settings: {mismatched}.") + + +class TrainDFly2Recipe(TrainDSparkRecipe): + """Recipe for DFly2 draft-model training on a colocated sparse-attention target.""" + + # The released draft has no confidence head, so a run that does not ask for one can warm-start from it. + default_confidence_head_alpha = 0.0 + + def setup(self) -> None: + """Reject the DSpark options DFly2 does not support, then build everything via the DSpark recipe.""" + recipe_cfg = self.cfg.recipe_args + unsupported = { + "cached_target_path": recipe_cfg.get("cached_target_path", None) is not None, + "target_model_backend=remote": str(recipe_cfg.get("target_model_backend", "colocated")) != "colocated", + "packed_sequence_size": int(recipe_cfg.get("packed_sequence_size", 0) or 0) > 0, + "multimodal": bool(recipe_cfg.get("multimodal", False)), + } + rejected = [name for name, requested in unsupported.items() if requested] + if rejected: + # The draft reads the target's attention state, which only a colocated + # text-only forward on unpacked rows produces here. + raise NotImplementedError(f"DFly2 trains against a colocated, unpacked text target; got {rejected}.") + super().setup() + + def _build_target_wrapper( + self, target_layer_ids: list[int], target_packed_forward: _DSparkPackedForward | None + ) -> DFly2TargetModel: + """Capture the paired layers' keys and key lists instead of hidden states.""" + del target_packed_forward # packing is rejected in setup + return DFly2TargetModel(self.target_model, target_layer_ids) + + def _build_model_owned_draft(self, target_config: ModelOwnedDSparkProvider, margs: _DraftArgs) -> torch.nn.Module: + """Build the target package's DFly2 draft and start its layers from their paired target layers.""" + if not isinstance(target_config, ModelOwnedDFly2Provider): + raise ValueError(f"{type(target_config).__name__} does not provide a DFly2 draft") + recipe_cfg = self.cfg.recipe_args + options = _DraftArgs( + target_layer_ids=margs.target_layer_ids, + block_size=margs.block_size, + num_anchors=margs.num_anchors, + mask_token_id=margs.mask_token_id, + enable_confidence_head=float(margs.confidence_head_alpha) > 0.0, + confidence_head_stop_gradient=bool(recipe_cfg.get("confidence_head_stop_gradient", True)), + # Long rows need the sparse kernel ("tilelang" or "cudnn"); "sdpa" builds a dense mask. + attn_backend=str(recipe_cfg.get("draft_attn_backend", "sdpa")), + ) + draft_weights_path = recipe_cfg.get("draft_weights_path", None) + if draft_weights_path: + check_dfly2_checkpoint_settings( + str(draft_weights_path), + target_layer_ids=list(margs.target_layer_ids), + block_size=int(margs.block_size), + mask_token_id=int(margs.mask_token_id), + ) + draft_model = target_config.build_dfly2_draft(options) + # Collective over the sharded target: every rank builds the draft and gathers the same tensors. + draft_model.initialize_from_target(self.target_model) + return draft_model + + def _build_trainer_module(self, recipe_cfg: ConfigNode, confidence_head_alpha: float) -> torch.nn.Module: + """Build the DFly2 trainer wrapper (D-PACE-weighted LK plus confidence).""" + return DFly2TrainerModule( + self.draft_model, + dpace_alpha=float(recipe_cfg.get("dpace_alpha", 0.5)), + lk_eta=float(recipe_cfg.get("lk_eta", 3.0)), + confidence_head_alpha=confidence_head_alpha, + ) + + @staticmethod + def _draft_fsdp_units(draft_model: torch.nn.Module) -> list[torch.nn.Module]: + """Shard the heads by dtype too: the corrections hold FP32 sinks and biases, the confidence head is FP32.""" + heads = [draft_model.mtp_fusion, draft_model.hidden_correction] + if draft_model.confidence_head is not None: + heads.append(draft_model.confidence_head) + return [*draft_model.layers, *heads] + + def _forward_batch(self, batch: dict[str, torch.Tensor]) -> DSparkStepMetrics: + """Run the frozen target once and train the draft on its paired layers' keys.""" + batch = {k: v.to(self.device, non_blocking=True) for k, v in batch.items()} + target_batch = self.target_wrapper.generate_batch( + input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], loss_mask=batch["loss_mask"] + ) + features = target_batch.features + return self.trainer_module( + input_ids=target_batch.input_ids, + loss_mask=target_batch.loss_mask, + context_keys=features.context_keys, + context_indices=features.context_indices, + target_last_hidden_states=features.last_hidden_states, + ) + + +def main(config_path: str | None = None) -> None: + """Entrypoint for ``TrainDFly2Recipe``.""" + cfg = parse_args_and_load_config(config_path) + trainer = TrainDFly2Recipe(cfg) + trainer.setup() + trainer.run_train_validation_loop() + + +if __name__ == "__main__": + main() diff --git a/nemo_automodel/recipes/speculative_decoding/train_dspark.py b/nemo_automodel/recipes/speculative_decoding/train_dspark.py index 0eea180769..f86258aed7 100644 --- a/nemo_automodel/recipes/speculative_decoding/train_dspark.py +++ b/nemo_automodel/recipes/speculative_decoding/train_dspark.py @@ -38,6 +38,7 @@ from nemo_automodel._transformers import NeMoAutoModelForCausalLM, NeMoAutoModelForImageTextToText from nemo_automodel._transformers.auto_tokenizer import NeMoAutoTokenizer from nemo_automodel.components.config._arg_parser import parse_args_and_load_config +from nemo_automodel.components.config.loader import ConfigNode from nemo_automodel.components.datasets.llm.dspark_cache import ( DTYPE_MAP, build_cached_dspark_dataloader, @@ -80,7 +81,7 @@ resolve_dspark_draft_spec, ) from nemo_automodel.components.speculative.dspark.remote import DSparkTargetInfo, RemoteDSparkTargetModel -from nemo_automodel.components.speculative.dspark.target import HFDSparkTargetModel +from nemo_automodel.components.speculative.dspark.target import HFDSparkTargetModel, _DSparkPackedForward from nemo_automodel.components.speculative.dspark.target_utils import ( DEEPSEEK_V4_MODEL_TYPE as _DEEPSEEK_V4_MODEL_TYPE, ) @@ -431,6 +432,8 @@ class TrainDSparkRecipe(SpecDecodeRecipeBase): # A freshly-initialized DSpark draft (random attention layers, Markov head, # confidence head) spikes when it reaches near-peak LR within a few steps. min_warmup_steps = 20 + # Weight of the confidence loss when recipe_args.confidence_head_alpha is not set. + default_confidence_head_alpha = 1.0 def __init__(self, cfg): self.cfg = cfg @@ -854,12 +857,7 @@ def setup(self): if self.dist_env.is_main: logger.info("DSpark REMOTE target: %d server(s) at %s.", len(remote_urls), remote_urls) elif self.target_model is not None: - self.target_wrapper = HFDSparkTargetModel( - self.target_model, - target_layer_ids=target_layer_ids, - cp_mesh=self.cp_mesh, - packed_forward=target_packed_forward, - ) + self.target_wrapper = self._build_target_wrapper(target_layer_ids, target_packed_forward) else: self.target_wrapper = None @@ -996,7 +994,7 @@ def setup(self): and attention_backend != "flex_attention" ): raise ValueError(f"DSpark training requires attention_backend='flex_attention', got {attention_backend!r}.") - confidence_head_alpha = float(recipe_cfg.get("confidence_head_alpha", 1.0)) + confidence_head_alpha = self._resolve_confidence_head_alpha(recipe_cfg) markov_rank = int(recipe_cfg.get("markov_rank", 256)) draft_model = None @@ -1013,7 +1011,7 @@ def setup(self): confidence_head_with_markov=bool(recipe_cfg.get("confidence_head_with_markov", True)), confidence_head_stop_gradient=bool(recipe_cfg.get("confidence_head_stop_gradient", False)), ) - draft_model = target_config.build_dspark_draft(margs) + draft_model = self._build_model_owned_draft(target_config, margs) elif is_deepseek_v4_target or is_glm_5_2_target or is_gemma4_target or is_kimi_k3_target: # Gemma4, DeepSeek V4, GLM-5.2, and Kimi K3 drafts share one typed # draft-config builder that takes the same DSpark model-args bundle. @@ -1111,13 +1109,7 @@ def setup(self): # the separately constructed trainable draft must be wrapped explicitly. apply_draft_activation_checkpointing(self.draft_model, activation_checkpointing) - trainer_module = DSparkTrainerModule( - self.draft_model, - loss_decay_gamma=recipe_cfg.get("loss_decay_gamma", None), - ce_loss_alpha=float(recipe_cfg.get("ce_loss_alpha", 0.1)), - l1_loss_alpha=float(recipe_cfg.get("l1_loss_alpha", 0.9)), - confidence_head_alpha=confidence_head_alpha, - ).to(self.device) + trainer_module = self._build_trainer_module(recipe_cfg, confidence_head_alpha).to(self.device) # Multi-GPU strategy: FSDP2 (default) shards the draft per block, or DDP. self.parallel_strategy = "ddp" if self.dist_env.world_size > 1: @@ -1138,9 +1130,9 @@ def setup(self): fp32_compute_module_names = tuple( getattr(trainer_module.draft_model, "_keep_in_fp32_modules_strict", ()) ) - for layer in trainer_module.draft_model.layers: + for unit in self._draft_fsdp_units(trainer_module.draft_model): fully_shard_by_dtype( - layer, + unit, mesh=draft_mesh, mp_policy=mp_policy, offload_policy=None, @@ -1201,6 +1193,40 @@ def setup(self): self.trackio_logger = trackio_cfg.build(run_config=self.cfg.to_yaml_dict(use_orig_values=True)) logger.info("Trackio experiment tracking enabled") + def _resolve_confidence_head_alpha(self, recipe_cfg: ConfigNode) -> float: + """Return ``recipe_args.confidence_head_alpha``, or this recipe's default when it is not set.""" + return float(recipe_cfg.get("confidence_head_alpha", self.default_confidence_head_alpha)) + + def _build_target_wrapper( + self, target_layer_ids: list[int], target_packed_forward: _DSparkPackedForward | None + ) -> HFDSparkTargetModel: + """Wrap the loaded frozen target for online feature capture.""" + return HFDSparkTargetModel( + self.target_model, + target_layer_ids=target_layer_ids, + cp_mesh=self.cp_mesh, + packed_forward=target_packed_forward, + ) + + def _build_model_owned_draft(self, target_config: ModelOwnedDSparkProvider, margs: _DraftArgs) -> torch.nn.Module: + """Build the draft owned by the target's model package.""" + return target_config.build_dspark_draft(margs) + + def _build_trainer_module(self, recipe_cfg: ConfigNode, confidence_head_alpha: float) -> torch.nn.Module: + """Build the training wrapper that runs the draft and computes its objective.""" + return DSparkTrainerModule( + self.draft_model, + loss_decay_gamma=recipe_cfg.get("loss_decay_gamma", None), + ce_loss_alpha=float(recipe_cfg.get("ce_loss_alpha", 0.1)), + l1_loss_alpha=float(recipe_cfg.get("l1_loss_alpha", 0.9)), + confidence_head_alpha=confidence_head_alpha, + ) + + @staticmethod + def _draft_fsdp_units(draft_model: torch.nn.Module) -> list[torch.nn.Module]: + """Return the draft modules that each get their own dtype-uniform FSDP2 units.""" + return list(draft_model.layers) + @staticmethod def _resolve_mask_token_id(recipe_cfg, vocab_size: int) -> int: """Resolve and validate the MASK token id filling non-anchor block positions. diff --git a/tests/unit_tests/models/deepseek_v41/test_dfly2.py b/tests/unit_tests/models/deepseek_v41/test_dfly2.py new file mode 100644 index 0000000000..200aba901e --- /dev/null +++ b/tests/unit_tests/models/deepseek_v41/test_dfly2.py @@ -0,0 +1,770 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch +from safetensors.torch import save_file + +from nemo_automodel.components.models.common import BackendConfig +from nemo_automodel.components.models.common.utils import cast_model_to_dtype +from nemo_automodel.components.models.deepseek_v41.config import ( + DeepseekV41Config, + DeepseekV41TextConfig, + DeepseekV41VisionConfig, +) +from nemo_automodel.components.models.deepseek_v41.dfly2 import DeepseekV41DFly2Config, DeepseekV41DFly2Model +from nemo_automodel.components.models.deepseek_v41.model import DeepseekV41ForCausalLM +from nemo_automodel.components.speculative.dfly2 import DFly2TargetModel +from nemo_automodel.recipes.speculative_decoding._dspark_warm_start import load_dspark_draft_weights + +pytestmark = [pytest.mark.timeout(70), pytest.mark.cpu_only] + +# Layers 4 and 5 are ratio-1 layers: 4 publishes the shared 1:1 compressed KV, both select keys. +_PAIRED_LAYERS = (4, 5) + + +def _text_config(**overrides) -> DeepseekV41TextConfig: + values = dict( + vocab_size=64, + hidden_size=16, + moe_intermediate_size=16, + num_hidden_layers=6, + num_attention_heads=2, + head_dim=8, + qk_rope_head_dim=4, + q_lora_rank=8, + o_lora_rank=8, + o_groups=1, + n_routed_experts=4, + num_experts_per_tok=2, + # Two trailing schedule slots for the draft layers, without compressor or indexer. + compress_ratios=[0, 0, 2, 2, 1, 1, 0, 0], + kv_source_layer_ids=[2, 4], + index_source_layer_ids=[2, 4, 5], + index_n_heads=2, + index_head_dim=8, + index_topk=2, + candidate_source_layer_id=4, + candidate_topk_blocks=2, + candidate_block_size=2, + sliding_window=4, + engram_layer_ids=[], + engram_num_embeddings=[], + num_nextn_predict_layers=0, + dspark_block_size=0, + dspark_noise_token_id=0, + dtype="float32", + ) + values.update(overrides) + return DeepseekV41TextConfig(**values) + + +def _backend() -> BackendConfig: + return BackendConfig(attn="eager", linear="torch", rms_norm="torch_fp32", experts="torch", dispatcher="torch") + + +def _target() -> DeepseekV41ForCausalLM: + torch.manual_seed(3) + config = DeepseekV41Config(vision_config=DeepseekV41VisionConfig(num_hidden_layers=0), text_config=_text_config()) + with torch.device("meta"): + model = DeepseekV41ForCausalLM(config, backend=_backend()) + model.to_empty(device="cpu") + model.initialize_weights(torch.device("cpu"), dtype=torch.float32) + return model.eval() + + +def _draft(**overrides) -> DeepseekV41DFly2Model: + torch.manual_seed(5) + values = dict( + text_config=_text_config(), + target_layer_ids=_PAIRED_LAYERS, + block_size=3, + num_anchors=4, + mask_token_id=63, + n_routed_experts=4, + num_experts_per_tok=2, + ) + values.update(overrides) + return DeepseekV41DFly2Config(**values).build(_backend()) + + +def _attach_heads(draft: DeepseekV41DFly2Model) -> None: + draft.initialize_embeddings_and_head(embed_tokens=torch.nn.Embedding(64, 16), lm_head=torch.nn.Linear(16, 64)) + + +def _randomize(*modules: torch.nn.Module) -> None: + """Give modules values a fresh draft does not have (fresh norms are ones, sinks and mHC mixes match).""" + with torch.no_grad(): + for module in modules: + for parameter in module.parameters(): + parameter.normal_(std=0.5) + + +def _assert_copied(pairs: dict[str, tuple[torch.nn.Module, torch.nn.Module]]) -> None: + for name, (copy, source) in pairs.items(): + theirs = source.state_dict() + for key, value in copy.state_dict().items(): + torch.testing.assert_close(value, theirs[key], rtol=0, atol=0, msg=f"{name}.{key}") + + +def _draft_features(batch: int, sequence: int) -> tuple: + """Random draft inputs: token ids, keys and key lists per paired layer, and last hidden states.""" + generator = torch.Generator().manual_seed(23) + input_ids = torch.randint(0, 60, (batch, sequence), generator=generator) + context_keys = tuple(torch.randn(batch, 2 * sequence, 8, generator=generator) for _ in _PAIRED_LAYERS) + context_indices = tuple( + torch.randint(-1, 2 * sequence, (batch, sequence, 4), generator=generator).int() for _ in _PAIRED_LAYERS + ) + return input_ids, context_keys, context_indices, torch.randn(batch, sequence, 16, generator=generator) + + +def test_capture_reproduces_each_paired_target_attention() -> None: + """A draft attention started from its paired layer reproduces that layer from the captured keys alone. + + Fed the target layer's own input and the captured key list of every row (without any + draft key), the draft attention must give exactly the target layer's attention output: + this pins the window keys, the shared compressed keys, and the index offsets together. + """ + target = _target() + draft = _draft() + draft.initialize_from_target(target) + input_ids = torch.randint(0, 64, (2, 12)) + attention_mask = torch.ones(2, 12, dtype=torch.long) + attention_mask[1, 10:] = 0 + seen = {} + + def _record(layer_id): + def _hook(_module, args, kwargs, output): + seen[layer_id] = (args[0], output.hidden_states) + + return _hook + + handles = [ + target.model.layers[str(layer_id)].attn.register_forward_hook(_record(layer_id), with_kwargs=True) + for layer_id in _PAIRED_LAYERS + ] + try: + batch = DFly2TargetModel(target, _PAIRED_LAYERS).generate_batch(input_ids, attention_mask, attention_mask) + finally: + for handle in handles: + handle.remove() + + features = batch.features + positions = torch.arange(12).expand(2, -1) + for index, layer_id in enumerate(_PAIRED_LAYERS): + layer_input, expected = seen[layer_id] + keys, indices = features.context_keys[index], features.context_indices[index] + assert keys.shape == (2, 24, 8) and indices.shape == (2, 12, 4 + 2) + assert int(indices.max()) < 24 + attended = draft.layers[index].attn(layer_input, keys, indices, position_ids=positions) + valid = attention_mask.bool() + torch.testing.assert_close(attended[valid], expected[valid], rtol=1e-5, atol=1e-5) + assert features.last_hidden_states.shape == (2, 12, 16) + + +def test_window_rows_end_at_the_row_and_skip_padding() -> None: + target = _target() + attention_mask = torch.ones(1, 6, dtype=torch.long) + attention_mask[0, 5] = 0 + features = target.dfly2_target_features(torch.randint(0, 64, (1, 6)), attention_mask=attention_mask, layer_ids=[4]) + window = features.context_indices[0][0, :, :4] + assert window[0].tolist() == [0, -1, -1, -1] + assert window[4].tolist() == [1, 2, 3, 4] + # The padded token is never a window key, and selected keys index the global copy. + assert (window != 5).all() + picks = features.context_indices[0][0, :, 4:] + assert ((picks == -1) | (picks >= 6)).all() + + +def test_only_ratio_one_layers_can_be_paired() -> None: + with pytest.raises(ValueError, match="ratio-1"): + _draft(target_layer_ids=(2, 5)) + with pytest.raises(ValueError, match="ratio-1"): + _target().dfly2_target_features( + torch.zeros(1, 4, dtype=torch.long), attention_mask=torch.ones(1, 4), layer_ids=[3] + ) + + +def test_fresh_draft_starts_as_its_backbone_and_trains_every_head() -> None: + torch.manual_seed(11) + draft = _draft() + _attach_heads(draft) + hidden = torch.randn(1, 6, 16) + previous = torch.randn(1, 6, 16) + keys = torch.randn(1, 10, 8) + indices = torch.randint(0, 10, (1, 6, 3), dtype=torch.int32) + corrected = draft.hidden_correction( + hidden, previous, keys, indices, position_ids=torch.arange(6).view(1, -1), block_size=3 + ) + torch.testing.assert_close(corrected, hidden, rtol=0, atol=0) + assert draft.mtp_fusion(torch.randn(1, 2, 16), torch.randn(1, 2, 16)).abs().max() == 0 + + input_ids, context_keys, context_indices, last_hidden = _draft_features(1, 10) + outputs = draft(input_ids, torch.ones(1, 10), context_keys, context_indices, last_hidden) + assert outputs.draft_logits.shape == (1, 4, 2, 64) + assert outputs.aligned_target_logits.shape == (1, 4, 2, 64) + outputs.draft_logits.square().mean().backward() + # Zero-initialized outputs receive gradient at the first step, so every head can open. + assert draft.mtp_fusion.gate.grad.abs().sum() > 0 + assert draft.hidden_correction.down_proj.weight.grad.abs().sum() > 0 + assert draft.hidden_correction.attention.wo_b.weight.grad.abs().sum() > 0 + assert draft.layers[0].ffn.experts.gate_and_up_projs.grad is not None + assert draft.embed_tokens.weight.grad is None and draft.lm_head.weight.grad is None + + +def test_drafted_slots_label_the_tokens_after_the_anchor() -> None: + torch.manual_seed(2) + draft = _draft(num_anchors=1) + _attach_heads(draft) + input_ids = torch.arange(10, 20).view(1, -1) + loss_mask = torch.zeros(1, 10) + loss_mask[0, 6:8] = 1 + last_hidden = torch.randn(1, 10, 16) + context = [torch.randn(1, 20, 8) for _ in _PAIRED_LAYERS] + indices = [torch.full((1, 10, 2), -1, dtype=torch.int32) for _ in _PAIRED_LAYERS] + outputs = draft(input_ids, loss_mask, context, indices, last_hidden) + # The only eligible anchor is 6 (its first label, 7, is supervised): slots predict 7 and 8, + # and the second is dropped because token 8 is not supervised. + assert outputs.target_ids.tolist() == [[[17, 18]]] + assert outputs.eval_mask.tolist() == [[[True, False]]] + # Each teacher is the target's distribution at the token before its label. + torch.testing.assert_close(outputs.aligned_target_logits[0, 0], draft.compute_logits(last_hidden[0, 6:8])) + + +def test_confidence_head_reads_detached_draft_states() -> None: + draft = _draft(enable_confidence_head=True, confidence_head_stop_gradient=True) + _attach_heads(draft) + normalized = [] + draft.final_norm.register_forward_hook(lambda module, args, output: normalized.append(output)) + input_ids, context_keys, context_indices, last_hidden = _draft_features(1, 10) + outputs = draft(input_ids, torch.ones(1, 10), context_keys, context_indices, last_hidden) + assert outputs.confidence_pred.shape == (1, 4, 2) and outputs.confidence_pred.dtype == torch.float32 + # The head reads the final-normalized states. + expected = draft.confidence_head(normalized[0].view(1, 4, 3, 16)[:, :, 1:]) + torch.testing.assert_close(outputs.confidence_pred, expected, rtol=0, atol=0) + outputs.confidence_pred.sum().backward() + assert draft.confidence_head.confidence_proj.weight.grad is not None + assert all(parameter.grad is None for parameter in draft.layers.parameters()) + + +def test_released_checkpoint_roundtrip() -> None: + draft = _draft() + expected = {key: value.detach().clone() for key, value in draft.state_dict().items()} + released = draft.state_dict_adapter.to_hf(draft.state_dict()) + # Names of the released AngelSlim/DS-V4.1-Flash-DFly2-B6 layout. + for key in ( + "model.layers.0.attn.wq_a.weight", + "model.layers.0.attn.attn_sink", + "model.layers.0.attn_norm.weight", + "model.layers.1.ffn_norm.weight", + "model.layers.0.hc_attn_fn", + "model.layers.1.hc_ffn_scale", + "model.layers.0.ffn.gate.bias", + "model.layers.0.ffn.gate.bias_vl", + "model.layers.0.ffn.shared_experts.w1.weight", + "model.layers.0.ffn.experts.3.w2.weight", + "model.final_norm.weight", + "model.mtp_fusion.eh_proj.weight", + "model.mtp_fusion.gate", + "model.hidden_correction.down_proj.weight", + "model.hidden_correction.attention.q_in.weight", + "model.hidden_correction.attention.attn_sink", + "model.hidden_correction.attention.block_rel_bias", + "model.hidden_correction.attention.block_gate.weight", + ): + assert key in released, key + assert set(released) == set(draft.state_dict_adapter.get_hf_state_dict_keys(draft.state_dict())) + + restored = draft.state_dict_adapter.from_hf(released) + assert restored.keys() == expected.keys() + for key, value in expected.items(): + torch.testing.assert_close(restored[key], value, rtol=0, atol=0) + + +def test_warm_start_reads_the_released_layout(tmp_path: Path) -> None: + source = _draft() + with torch.no_grad(): + source.mtp_fusion.gate.fill_(0.5) + source.hidden_correction.attention.block_sink.weight.fill_(-1.0) + # A router bias that BF16 cannot hold. + source.layers[0].ffn.gate.e_score_correction_bias.copy_(torch.arange(4) / 7 + 0.1) + router_bias = source.layers[0].ffn.gate.e_score_correction_bias.clone() + assert not torch.equal(router_bias.to(torch.bfloat16).float(), router_bias) + # Both drafts go through the recipe's BF16 cast. + cast_model_to_dtype(source, torch.bfloat16) + released = source.state_dict_adapter.to_hf(source.state_dict()) + # The release ships neither the shared embedding nor the head. + released = { + key: value.contiguous() + for key, value in released.items() + if key not in ("model.embed_tokens.weight", "model.lm_head.weight") + } + save_file(released, str(tmp_path / "model.safetensors")) + + draft = _draft() + cast_model_to_dtype(draft, torch.bfloat16) + _attach_heads(draft) + load_dspark_draft_weights( + draft, str(tmp_path), keep_target_embeddings=True, target_layer_ids=list(_PAIRED_LAYERS), mask_token_id=63 + ) + torch.testing.assert_close(draft.layers[0].ffn.gate.e_score_correction_bias, router_bias, rtol=0, atol=0) + exported = draft.state_dict_adapter.to_hf(draft.state_dict()) + torch.testing.assert_close(exported["model.layers.0.ffn.gate.bias"], router_bias, rtol=0, atol=0) + torch.testing.assert_close(draft.mtp_fusion.gate, source.mtp_fusion.gate) + torch.testing.assert_close( + draft.hidden_correction.attention.block_sink.weight, source.hidden_correction.attention.block_sink.weight + ) + torch.testing.assert_close( + draft.layers[1].ffn.experts.down_projs, source.layers[1].ffn.experts.down_projs, rtol=0, atol=0 + ) + + +def test_exported_config_carries_the_dfly2_settings() -> None: + draft = _draft() + exported = json.loads(draft.config.to_json_string(use_diff=False)) + assert exported["architectures"] == ["DeepseekV41DFly2Model"] + assert exported["dfly_config"]["block_size"] == 3 + assert exported["dfly_config"]["target_kv_layers"] == list(_PAIRED_LAYERS) + assert exported["dfly_config"]["mask_token_id"] == 63 + + +def test_draft_does_not_inherit_the_targets_sparse_backward() -> None: + config = DeepseekV41Config( + vision_config=DeepseekV41VisionConfig(num_hidden_layers=0), + text_config=_text_config(sparse_attention_backward="deterministic"), + ) + options = SimpleNamespace( + target_layer_ids=[4, 5], + block_size=3, + num_anchors=2, + mask_token_id=63, + enable_confidence_head=False, + confidence_head_stop_gradient=True, + attn_backend="eager", + ) + # The target's TileLang-only deterministic backward would reject the eager draft. + draft = config.build_dfly2_draft(options) + assert config.text_config.sparse_attention_backward == "deterministic" + assert draft.dfly2_config.text_config.sparse_attention_backward == "atomic" + + +def _fsdp_trainer(): + from nemo_automodel.components.speculative.dfly2 import DFly2TrainerModule + + # Every valid anchor is taken (num_anchors exceeds the candidates), so the blocks do not + # depend on how the global batch is split across ranks. + draft = _draft(num_anchors=16, enable_confidence_head=True, confidence_head_stop_gradient=False) + torch.manual_seed(29) + _attach_heads(draft) + with torch.no_grad(): + # Open every zero-initialized head so all parameters carry gradient. + draft.mtp_fusion.gate.fill_(0.5) + draft.hidden_correction.down_proj.weight.normal_(std=0.1) + draft.hidden_correction.attention.wo_b.weight.normal_(std=0.1) + draft.hidden_correction.attention.block_gate_bias.weight.fill_(0.3) + return DFly2TrainerModule(draft, confidence_head_alpha=1.0) + + +def _init_gloo(rank: int, rendezvous: str) -> None: + from datetime import timedelta + + import torch.distributed as dist + + dist.init_process_group( + "gloo", init_method=f"file://{rendezvous}", rank=rank, world_size=2, timeout=timedelta(seconds=90) + ) + + +def _shard_like_the_recipe(trainer: torch.nn.Module, param_dtype: torch.dtype) -> None: + """Dtype-uniform FSDP2 units for the draft units, then the root, over two CPU ranks.""" + from torch.distributed.device_mesh import init_device_mesh + from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard + + from nemo_automodel.components.distributed.parallelizer_utils import fully_shard_by_dtype + from nemo_automodel.recipes.speculative_decoding.train_dfly2 import TrainDFly2Recipe + + mesh = init_device_mesh("cpu", (2,), mesh_dim_names=("dp",)) + policy = MixedPrecisionPolicy(param_dtype=param_dtype, reduce_dtype=torch.float32, cast_forward_inputs=False) + for unit in TrainDFly2Recipe._draft_fsdp_units(trainer.draft_model): + fully_shard_by_dtype( + unit, + mesh=mesh, + mp_policy=policy, + offload_policy=None, + fp32_compute_module_names=tuple(trainer.draft_model._keep_in_fp32_modules_strict), + ) + fully_shard(trainer, mesh=mesh, mp_policy=policy) + + +def _fsdp_training_worker(rank: int, rendezvous: str, reference_path: str, compute_dtype: str) -> None: + import torch.distributed as dist + from torch.distributed.tensor import DTensor + + _init_gloo(rank, rendezvous) + try: + trainer = _fsdp_trainer() + param_dtype = getattr(torch, compute_dtype) + _shard_like_the_recipe(trainer, param_dtype) + + input_ids, keys, indices, last_hidden = _draft_features(2, 10) + local = slice(rank, rank + 1) + loss_mask = torch.ones(2, 10) + loss_mask[0, 7:] = 0 # an uneven split of supervised slots across the ranks + metrics = trainer( + input_ids=input_ids[local], + loss_mask=loss_mask[local], + context_keys=tuple(key[local] for key in keys), + context_indices=tuple(index[local] for index in indices), + target_last_hidden_states=last_hidden[local], + ) + metrics.loss.backward() + reference = torch.load(reference_path) + grads = {} + for name, parameter in trainer.named_parameters(): + if name not in reference: + assert parameter.grad is None, name + continue + grads[name] = parameter.grad.full_tensor() if isinstance(parameter.grad, DTensor) else parameter.grad + if param_dtype == torch.float32: + for name, grad in grads.items(): + torch.testing.assert_close(grad, reference[name], rtol=1e-4, atol=1e-6, msg=name) + else: + # The recipe's BF16 policy: the FP32 heads must still run (a BF16 weight against their + # FP32 inputs fails), compute in FP32, and the draft's gradient must stay close overall. + assert all(torch.isfinite(grad).all() for grad in grads.values()) + head = "draft_model.confidence_head.confidence_proj.weight" + torch.testing.assert_close(grads[head], reference[head], rtol=0.05, atol=1e-5) + flat = torch.cat([grad.flatten() for grad in grads.values()]) + expected = torch.cat([reference[name].flatten() for name in grads]) + assert (flat - expected).norm() <= 0.05 * expected.norm() + # Per tensor too, except the last layer's FFN mix, whose reference gradient is near zero. + last_mix = f"draft_model.layers.{len(_PAIRED_LAYERS) - 1}.ffn_hc." + for name, grad in grads.items(): + if not name.startswith(last_mix): + assert (grad - reference[name]).norm() <= 0.1 * reference[name].norm() + 1e-8, name + finally: + dist.destroy_process_group() + + +@pytest.mark.runtime_budget( + 20, hard_timeout=70, reason="Two-process gloo FSDP2 forward and backward of the draft against one process." +) +@pytest.mark.parametrize("compute_dtype", ["float32", "bfloat16"]) +def test_fsdp_gradient_matches_the_single_process_global_batch( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, compute_dtype: str +) -> None: + """Sharded like the recipe over two ranks, the draft's gradient equals the one-process gradient. + + The objective divides by the weight sum of all ranks and scales by the world size, so + FSDP's gradient average reproduces the global weighted mean even though the ranks hold + different numbers of supervised slots. + """ + import torch.multiprocessing as mp + + trainer = _fsdp_trainer() + input_ids, keys, indices, last_hidden = _draft_features(2, 10) + loss_mask = torch.ones(2, 10) + loss_mask[0, 7:] = 0 + metrics = trainer( + input_ids=input_ids, + loss_mask=loss_mask, + context_keys=keys, + context_indices=indices, + target_last_hidden_states=last_hidden, + ) + metrics.loss.backward() + reference = {name: parameter.grad for name, parameter in trainer.named_parameters() if parameter.grad is not None} + assert "draft_model.confidence_head.confidence_proj.weight" in reference + assert "draft_model.mtp_fusion.gate" in reference + torch.save(reference, tmp_path / "reference.pt") + # Other unit-test modules disable compilation during collection; the spawned workers need the + # fullgraph MoE activation compiled. + monkeypatch.setenv("TORCH_COMPILE_DISABLE", "0") + mp.spawn( + _fsdp_training_worker, + args=(str(tmp_path / "rendezvous"), str(tmp_path / "reference.pt"), compute_dtype), + nprocs=2, + join=True, + ) + + +def test_each_drafted_slot_reads_only_what_exists_when_its_block_is_drafted() -> None: + """Perturb one input row at a time; slot ``k`` of the block at anchor ``a`` may move only for + + * tokens up to row ``a + k - 1`` (the anchor, then the teacher-forced previous tokens), + * the target's last hidden state at row ``a - 1`` (the MTP fusion), + * keys listed by row ``a - 1``'s key list of the same paired layer, and that list itself. + + A label leak, a fusion or key list read from row ``a``, or a draft layer reading another + paired layer's keys each moves a slot that must not move. + """ + torch.manual_seed(7) + sequence, block_size = 10, 3 + # Every candidate anchor is taken, so block j sits at anchor j. + draft = _draft(num_anchors=sequence, block_size=block_size) + _attach_heads(draft) + with torch.no_grad(): + # Open the zero-initialized heads so every path carries signal. + draft.mtp_fusion.gate.fill_(1.0) + draft.hidden_correction.down_proj.weight.normal_(std=0.2) + attention = draft.hidden_correction.attention + # Full projections: the embedding half of q_in / kv_in and the gate start at zero. + for linear in (attention.wo_b, attention.q_in, attention.kv_in, attention.block_gate): + linear.weight.normal_(std=0.2) + attention.block_gate_bias.weight.fill_(0.5) + generator = torch.Generator().manual_seed(11) + input_ids = torch.randint(0, 60, (1, sequence), generator=generator) + last_hidden = torch.randn(1, sequence, 16, generator=generator) + keys = [torch.randn(1, sequence, 8, generator=generator) for _ in _PAIRED_LAYERS] + # Causal key lists that differ between the two paired layers: row r lists keys at or before r. + lists = [] + for _ in _PAIRED_LAYERS: + rows = [torch.randperm(r + 1, generator=generator)[:3] for r in range(sequence)] + lists.append(torch.stack([torch.nn.functional.pad(row, (0, 3 - len(row)), value=-1) for row in rows])[None]) + loss_mask = torch.ones(1, sequence) + + def logits(ids=input_ids, hidden=last_hidden, context=keys, indices=lists): + with torch.no_grad(): + return draft(ids, loss_mask, context, [index.int() for index in indices], hidden).draft_logits[0] + + base = logits() + anchors = range(sequence - 1) + violations = [] + + def check(name, changed, allowed): + moved = (changed - base).abs().amax(-1) > 1e-6 # [blocks, drafted] + for anchor in anchors: + for drafted in range(block_size - 1): + if moved[anchor, drafted] and not allowed(anchor, drafted + 1): + violations.append((name, anchor, drafted + 1)) + + missing = [] + + def require(name, changed, required): + moved = (changed - base).abs().amax(-1) > 1e-6 + for anchor in anchors: + for drafted in range(block_size - 1): + if required(anchor, drafted + 1) and not moved[anchor, drafted]: + missing.append((name, anchor, drafted + 1)) + + for row in range(sequence): + ids = input_ids.clone() + ids[0, row] = (ids[0, row] + 1) % 60 + changed = logits(ids=ids) + check(f"token {row}", changed, lambda a, k, r=row: r <= a + k - 1) + # The token before slot k's label is that slot's teacher-forced previous token. + require(f"token {row}", changed, lambda a, k, r=row: r == a + k - 1) + hidden = last_hidden.clone() + hidden[0, row] += 1.0 + changed = logits(hidden=hidden) + check(f"last hidden {row}", changed, lambda a, k, r=row: r == a - 1) + require(f"last hidden {row}", changed, lambda a, k, r=row: r == a - 1) + for layer in range(len(_PAIRED_LAYERS)): + context = [key.clone() for key in keys] + context[layer][0, row] += 1.0 + listed = lambda a, k, r=row, i=layer: a >= 1 and bool((lists[i][0, a - 1] == r).any()) # noqa: E731 + check(f"layer {layer} key {row}", logits(context=context), listed) + indices = [index.clone() for index in lists] + indices[layer][0, row] = torch.roll(indices[layer][0, row], 1) + indices[layer][0, row, 0] = -1 + check(f"layer {layer} key list {row}", logits(indices=indices), lambda a, k, r=row: r == a - 1) + assert violations == [] + assert missing == [] + + +def test_unused_slots_never_read_key_zero() -> None: + from nemo_automodel.components.models.deepseek_v41.dfly2 import _listed_latent_attention + + torch.manual_seed(1) + query = torch.randn(1, 2, 2, 8) + kv = torch.randn(1, 5, 8) + # Neither row lists key 0; the second lists nothing at all. + indices = torch.tensor([[[3, -1, 1, -1], [-1, -1, -1, -1]]], dtype=torch.int32) + sinks = torch.zeros(2) + for backend in ("eager", "sdpa"): + out = _listed_latent_attention(query, kv, indices, sinks, 8**-0.5, backend=backend) + changed = kv.clone() + changed[0, 0] += 5.0 + torch.testing.assert_close( + _listed_latent_attention(query, changed, indices, sinks, 8**-0.5, backend=backend), out + ) + assert out[0, 1].abs().max() == 0 + + +def test_each_draft_layer_reads_its_own_paired_layer() -> None: + """With draft layer 1's attention and the correction silenced, only layer 0's keys may matter.""" + torch.manual_seed(3) + sequence = 8 + draft = _draft(num_anchors=sequence) + _attach_heads(draft) + with torch.no_grad(): + draft.layers[1].attn.wo_b.weight.zero_() + draft.hidden_correction.attention.wo_b.weight.zero_() + input_ids = torch.randint(0, 60, (1, sequence)) + keys = [torch.randn(1, sequence, 8) for _ in _PAIRED_LAYERS] + indices = [torch.arange(sequence).view(1, -1, 1).expand(-1, -1, 2).clone().int() for _ in _PAIRED_LAYERS] + last_hidden = torch.randn(1, sequence, 16) + + def logits(context): + with torch.no_grad(): + return draft(input_ids, torch.ones(1, sequence), context, indices, last_hidden).draft_logits + + base = logits(keys) + torch.testing.assert_close(logits([keys[0], keys[1] + 1.0]), base, rtol=0, atol=0) + assert not torch.allclose(logits([keys[0] + 1.0, keys[1]]), base) + + +def _consolidated_save_worker(rank: int, root: str) -> None: + import torch.distributed as dist + + from nemo_automodel.components.checkpoint.checkpointing import Checkpointer, CheckpointingConfig + from nemo_automodel.components.speculative.dfly2 import DFly2TrainerModule + + _init_gloo(rank, f"{root}/rendezvous") + try: + draft = _draft(enable_confidence_head=True) + torch.manual_seed(13) + _attach_heads(draft) + expected = {key: value.detach().clone() for key, value in draft.state_dict().items()} + trainer = DFly2TrainerModule(draft) + _shard_like_the_recipe(trainer, torch.bfloat16) + # As the recipe builds it: native draft keys, no reference checkpoint. + checkpointer = Checkpointer( + CheckpointingConfig( + checkpoint_dir=f"{root}/checkpoints", + model_save_format="safetensors", + save_consolidated=True, + model_cache_dir=f"{root}/cache", + model_repo_id="test/dfly2", + model_state_dict_keys=list(expected), + ), + dp_rank=rank, + tp_rank=0, + pp_rank=0, + ) + try: + checkpointer.save_model(draft, f"{root}/saved") + finally: + checkpointer.close() + dist.barrier() + if rank == 0: + restored = _draft(enable_confidence_head=True) + restored.initialize_embeddings_and_head( + embed_tokens=torch.nn.Embedding(64, 16), lm_head=torch.nn.Linear(16, 64) + ) + load_dspark_draft_weights( + restored, + f"{root}/saved/model/consolidated", + keep_target_embeddings=True, + target_layer_ids=list(_PAIRED_LAYERS), + mask_token_id=63, + ) + for key, value in restored.state_dict().items(): + if key not in ("embed_tokens.weight", "lm_head.weight"): + torch.testing.assert_close(value, expected[key], rtol=0, atol=0, msg=key) + finally: + dist.destroy_process_group() + + +@pytest.mark.runtime_budget( + 20, hard_timeout=70, reason="Two-process gloo FSDP2 consolidated save of the draft, then a warm start from it." +) +def test_consolidated_save_of_a_sharded_draft_holds_every_expert(tmp_path: Path) -> None: + """Each rank exports only the experts of its FSDP shard; the consolidated draft must still hold all of them.""" + import torch.multiprocessing as mp + + mp.spawn(_consolidated_save_worker, args=(str(tmp_path),), nprocs=2, join=True) + + +def test_attentive_correction_starts_from_the_last_layer_closed() -> None: + draft = _draft() + source = draft.layers[-1].attn + correction = draft.hidden_correction.attention + _randomize(source.q_norm, source.wq_b, source.kv_norm, source.wo_a, source.sinks_param) + with torch.no_grad(): + draft.initialize_attentive_correction() + _assert_copied( + { + "q_norm": (correction.q_norm, source.q_norm), + "wq_b": (correction.wq_b, source.wq_b), + "kv_norm": (correction.kv_norm, source.kv_norm), + "wo_a": (correction.wo_a, source.wo_a), + } + ) + # The hidden columns of the query and key inputs take the layer's projections; the + # previous-embedding columns start at zero, and so does the output. + torch.testing.assert_close(correction.q_in.weight[:, :16], source.wq_a.weight, rtol=0, atol=0) + torch.testing.assert_close(correction.kv_in.weight[:, :16], source.wkv.weight, rtol=0, atol=0) + assert correction.q_in.weight[:, 16:].abs().max() == 0 and correction.kv_in.weight[:, 16:].abs().max() == 0 + torch.testing.assert_close(correction.attn_sink.weight, source.sinks_param.weight, rtol=0, atol=0) + torch.testing.assert_close(correction.block_sink.weight, source.sinks_param.weight, rtol=0, atol=0) + assert correction.wo_b.weight.abs().max() == 0 and correction.block_gate_bias.weight.abs().max() == 0 + + +def test_recipe_starts_each_draft_layer_from_its_paired_target_layer() -> None: + """Eq. (9): attention (sinks included), norms, mHC mixes and the shared expert of draft layer i + equal the tensors of paired target layer i after the recipe builds the draft.""" + from nemo_automodel.components.config.loader import ConfigNode + from nemo_automodel.recipes.speculative_decoding.train_dfly2 import TrainDFly2Recipe + from nemo_automodel.recipes.speculative_decoding.train_dspark import _DraftArgs + + target = _target() + for layer_id in _PAIRED_LAYERS: + paired = target.model.layers[str(layer_id)] + _randomize( + paired.attn.sinks_param, + paired.attn.q_norm, + paired.attn.kv_norm, + paired.attn_norm, + paired.ffn_norm, + paired.attn_hc, + paired.ffn_hc, + ) + recipe = TrainDFly2Recipe.__new__(TrainDFly2Recipe) + recipe.cfg = ConfigNode({"recipe_args": {"draft_attn_backend": "eager", "confidence_head_stop_gradient": False}}) + recipe.target_model = target + margs = _DraftArgs( + target_layer_ids=list(_PAIRED_LAYERS), + block_size=3, + num_anchors=4, + mask_token_id=63, + confidence_head_alpha=1.0, + ) + draft = recipe._build_model_owned_draft(target.config, margs) + assert draft.layers[0].attn.backend.attn == "eager" + assert draft.confidence_head is not None and draft.dfly2_config.confidence_head_stop_gradient is False + for layer, layer_id in zip(draft.layers, _PAIRED_LAYERS): + source = target.model.layers[str(layer_id)] + attn, source_attn = layer.attn, source.attn + _assert_copied( + { + "attn.wq_a": (attn.wq_a, source_attn.wq_a), + "attn.q_norm": (attn.q_norm, source_attn.q_norm), + "attn.wq_b": (attn.wq_b, source_attn.wq_b), + "attn.wkv": (attn.wkv, source_attn.wkv), + "attn.kv_norm": (attn.kv_norm, source_attn.kv_norm), + "attn.wo_a": (attn.wo_a, source_attn.wo_a), + "attn.wo_b": (attn.wo_b, source_attn.wo_b), + "attn.sinks_param": (attn.sinks_param, source_attn.sinks_param), + "attn_norm": (layer.attn_norm, source.attn_norm), + "ffn_norm": (layer.ffn_norm, source.ffn_norm), + "attn_hc": (layer.attn_hc, source.attn_hc), + "ffn_hc": (layer.ffn_hc, source.ffn_hc), + "ffn.shared_experts": (layer.ffn.shared_experts, source.ffn.shared_experts), + } + ) diff --git a/tests/unit_tests/recipes/speculative_decoding/test_train_dfly2.py b/tests/unit_tests/recipes/speculative_decoding/test_train_dfly2.py new file mode 100644 index 0000000000..9dc962f817 --- /dev/null +++ b/tests/unit_tests/recipes/speculative_decoding/test_train_dfly2.py @@ -0,0 +1,132 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the DFly2 recipe seams over the DSpark recipe. + +The recipe is constructed via ``__new__`` (bypassing ``setup()``), so only the +overridden seams are exercised: the unsupported-option gate, the draft options, the +warm-start check, and the FSDP units of the FP32 heads. The draft's start +from its paired target layers is tested with a real target in the model tests. +""" + +from __future__ import annotations + +import json +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +import torch.nn as nn + +from nemo_automodel.components.config.loader import ConfigNode +from nemo_automodel.recipes.speculative_decoding.train_dfly2 import TrainDFly2Recipe +from nemo_automodel.recipes.speculative_decoding.train_dspark import TrainDSparkRecipe, _DraftArgs + +pytestmark = pytest.mark.cpu_only + + +def _recipe(**recipe_args) -> TrainDFly2Recipe: + recipe = TrainDFly2Recipe.__new__(TrainDFly2Recipe) + recipe.cfg = ConfigNode({"recipe_args": dict(recipe_args)}) + recipe.target_model = object() + return recipe + + +def _margs(**overrides) -> _DraftArgs: + values = dict( + num_draft_layers=3, + target_layer_ids=[28, 32, 36], + block_size=6, + num_anchors=512, + mask_token_id=128799, + markov_rank=256, + markov_head_type="vanilla", + confidence_head_alpha=0.0, + confidence_head_with_markov=True, + confidence_head_stop_gradient=False, + ) + values.update(overrides) + return _DraftArgs(**values) + + +def _target_config() -> SimpleNamespace: + return SimpleNamespace(build_dfly2_draft=Mock(return_value=Mock())) + + +@pytest.mark.parametrize( + ("option", "value"), + [ + ("cached_target_path", "/cache"), + ("target_model_backend", "remote"), + ("packed_sequence_size", 4096), + ("multimodal", True), + ], +) +def test_setup_rejects_options_without_a_colocated_unpacked_target(option, value, monkeypatch) -> None: + called = Mock() + monkeypatch.setattr(TrainDSparkRecipe, "setup", called) + with pytest.raises(NotImplementedError, match=option): + _recipe(**{option: value}).setup() + called.assert_not_called() + + +def test_confidence_head_is_off_and_detached_by_default() -> None: + recipe = _recipe() + # DFly2 drafts without a head unless asked, so the released drafter (which has none) loads. + alpha = recipe._resolve_confidence_head_alpha(recipe.cfg.recipe_args) + assert alpha == 0.0 + dspark = TrainDSparkRecipe.__new__(TrainDSparkRecipe) + assert dspark._resolve_confidence_head_alpha(ConfigNode({})) == 1.0 + assert recipe._resolve_confidence_head_alpha(ConfigNode({"confidence_head_alpha": 0.5})) == 0.5 + target_config = _target_config() + recipe._build_model_owned_draft(target_config, _margs(confidence_head_alpha=alpha)) + options = target_config.build_dfly2_draft.call_args.args[0] + assert options.enable_confidence_head is False + assert options.confidence_head_stop_gradient is True + assert options.attn_backend == "sdpa" + + +def test_fsdp_units_include_the_heads_holding_fp32_tensors() -> None: + draft = SimpleNamespace( + layers=nn.ModuleList([nn.Linear(1, 1)]), + mtp_fusion=nn.Linear(1, 1), + hidden_correction=nn.Linear(1, 1), + confidence_head=None, + ) + assert TrainDFly2Recipe._draft_fsdp_units(draft) == [draft.layers[0], draft.mtp_fusion, draft.hidden_correction] + # The FP32 confidence head must not fall into the root unit, which all-gathers in BF16. + draft.confidence_head = nn.Linear(1, 1) + assert TrainDFly2Recipe._draft_fsdp_units(draft)[-1] is draft.confidence_head + + +@pytest.mark.parametrize( + ("location", "weights", "setting", "value"), + [ + ("config.json", "", "target_layer_ids", [24, 28, 32]), + # draft_weights_path may also name a .safetensors file next to the config. + ("config.json", "model.safetensors", "mask_token_id", 1), + # A step checkpoint's model/ directory keeps its config in .hf_metadata/. + (".hf_metadata/config.json", "", "block_size", 7), + ], +) +def test_warm_start_refuses_other_dfly2_settings_before_building(tmp_path, location, weights, setting, value) -> None: + released = {"block_size": 6, "target_kv_layers": [28, 32, 36], "mask_token_id": 128799} + (tmp_path / location).parent.mkdir(parents=True, exist_ok=True) + (tmp_path / location).write_text(json.dumps({"dfly_config": released})) + target_config = _target_config() + recipe = _recipe(draft_weights_path=str(tmp_path / weights) if weights else str(tmp_path)) + recipe._build_model_owned_draft(target_config, _margs()) + with pytest.raises(ValueError, match="other DFly2 settings"): + recipe._build_model_owned_draft(target_config, _margs(**{setting: value})) + assert target_config.build_dfly2_draft.call_count == 1 diff --git a/tests/unit_tests/recipes/speculative_decoding/test_train_dspark_helpers.py b/tests/unit_tests/recipes/speculative_decoding/test_train_dspark_helpers.py index b16103913d..ef5af9ba25 100644 --- a/tests/unit_tests/recipes/speculative_decoding/test_train_dspark_helpers.py +++ b/tests/unit_tests/recipes/speculative_decoding/test_train_dspark_helpers.py @@ -697,7 +697,12 @@ def test_cached_dspark_manifest_accepts_bf16_cache_on_cuda_dtype(): _validate_cached_manifest(manifest=_cached_manifest(dtype="bf16"), compute_dtype=torch.bfloat16) -def test_recipe_cached_path_does_not_load_target_model(monkeypatch, tmp_path): +class _NoConfidenceDefaultRecipe(TrainDSparkRecipe): + default_confidence_head_alpha = 0.0 + + +@pytest.mark.parametrize("recipe_cls", [TrainDSparkRecipe, _NoConfidenceDefaultRecipe]) +def test_recipe_cached_path_does_not_load_target_model(monkeypatch, tmp_path, recipe_cls): """The recipe-level offline path must skip building the live target wrapper.""" import nemo_automodel.recipes.speculative_decoding.train_dspark as train_dspark_module @@ -806,9 +811,10 @@ def to_dict(self): monkeypatch.setattr(TrainDSparkRecipe, "_build_checkpointer", lambda self, _target_path: None) monkeypatch.setattr(TrainDSparkRecipe, "load_checkpoint", lambda self, restore_from=None: None) - recipe = TrainDSparkRecipe(cfg) + recipe = recipe_cls(cfg) recipe.setup() + assert recipe.trainer_module.confidence_head_alpha == recipe_cls.default_confidence_head_alpha assert recipe.target_model is None assert recipe.target_wrapper is None assert len(recipe.train_dataloader.dataset) == 1 diff --git a/tests/unit_tests/speculative/test_dfly2_methodology.py b/tests/unit_tests/speculative/test_dfly2_methodology.py new file mode 100644 index 0000000000..2f011311a1 --- /dev/null +++ b/tests/unit_tests/speculative/test_dfly2_methodology.py @@ -0,0 +1,190 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Methodology invariants of the target-agnostic DFly2 pieces: key lists, objective, trainer metrics.""" + +from __future__ import annotations + +import pytest +import torch +import torch.nn as nn + +from nemo_automodel.components.speculative.dfly2.common import ( + KEY_LIST_ALIGNMENT, + build_block_key_indices, +) +from nemo_automodel.components.speculative.dfly2.core import DFly2TrainerModule +from nemo_automodel.components.speculative.dfly2.loss import compute_dfly2_loss +from nemo_automodel.components.speculative.dspark.common import DSparkForwardOutput + +pytestmark = pytest.mark.cpu_only + + +def _context_indices() -> torch.Tensor: + # Row r lists keys r and 10 + r (two segments of a 10-row context). + rows = torch.arange(5) + return torch.stack((rows, rows + 10), dim=-1).view(1, 5, 2) + + +def test_block_reads_the_row_before_its_anchor_then_its_own_block() -> None: + indices = build_block_key_indices( + _context_indices(), + torch.tensor([[3, 1]]), + torch.tensor([[True, True]]), + num_context_keys=20, + block_size=2, + causal=False, + ) + assert indices.shape == (1, 4, KEY_LIST_ALIGNMENT) and indices.dtype == torch.int32 + # Block 0 (anchor 3) reads row 2; block 1 (anchor 1) reads row 0. Draft keys follow the context. + assert indices[0, :, :4].tolist() == [ + [2, 12, 20, 21], + [2, 12, 20, 21], + [0, 10, 22, 23], + [0, 10, 22, 23], + ] + assert (indices[0, :, 4:] == -1).all() + + +def test_dropped_blocks_and_sequence_start_anchors_read_nothing_from_the_context() -> None: + indices = build_block_key_indices( + _context_indices(), + torch.tensor([[0, 4]]), + torch.tensor([[True, False]]), + num_context_keys=20, + block_size=2, + causal=True, + ) + # Anchor 0 has no verified token before it, but still sees its own block, causally. + assert indices[0, 0, :4].tolist() == [-1, -1, 20, -1] + assert indices[0, 1, :4].tolist() == [-1, -1, 20, 21] + # A dropped block sees no key at all, so its output is zero. + assert (indices[0, 2:] == -1).all() + + +def _outputs(draft_logits: torch.Tensor, target_logits: torch.Tensor, eval_mask: torch.Tensor, confidence=None): + return DSparkForwardOutput( + draft_logits=draft_logits, + target_ids=target_logits.argmax(-1), + eval_mask=eval_mask, + block_keep_mask=eval_mask.any(-1), + confidence_pred=confidence, + aligned_target_logits=target_logits, + ) + + +def _loss(outputs: DSparkForwardOutput): + return compute_dfly2_loss(outputs=outputs, dpace_alpha=0.5, lk_eta=3.0, confidence_head_alpha=1.0) + + +def _reference_loss(draft_logits, target_logits, target_ids, mask, alpha, eta): + """The objective written out slot by slot; the D-PACE weights and the LK mix carry no gradient.""" + q = draft_logits.float().softmax(-1) + p = target_logits.float().softmax(-1) + tv = 0.5 * (p - q).abs().sum(-1) + kl = (p * (p.log() - q.log())).sum(-1) + lam = torch.exp(-eta * (1 - tv)).detach() + lk = lam * kl + (1 - lam) * tv + confidence = q.gather(-1, target_ids.unsqueeze(-1)).squeeze(-1).detach() + smooth = torch.where(mask, (1 - alpha) * confidence + alpha, torch.ones_like(confidence)) + prefix = smooth.cumprod(-1) + weights = (prefix * mask).flip(-1).cumsum(-1).flip(-1) * mask + return (lk * weights).sum() / weights.sum(), (tv * weights).sum() / weights.sum() + + +def test_objective_matches_the_written_out_formula() -> None: + torch.manual_seed(0) + # 136 slots: the chunked terms run one full chunk and a partial one. + draft_logits = torch.randn(2, 17, 4, 11, requires_grad=True) + target_logits = torch.randn(2, 17, 4, 11) + mask = torch.ones(2, 17, 4, dtype=torch.bool) + mask[0, 1, 2:] = False + mask[1, 2] = False + outputs = _outputs(draft_logits, target_logits, mask) + loss, terms = _loss(outputs) + expected, expected_tv = _reference_loss(draft_logits, target_logits, outputs.target_ids, mask, 0.5, 3.0) + torch.testing.assert_close(loss, expected, rtol=1e-5, atol=1e-6) + torch.testing.assert_close(terms["l1_loss"], expected_tv, rtol=1e-5, atol=1e-6) + # The gradient is that of the weighted LK sum with the D-PACE weights and the mix held fixed. + loss.backward() + draft_grad = draft_logits.grad.clone() + draft_logits.grad = None + expected.backward() + torch.testing.assert_close(draft_grad, draft_logits.grad, rtol=1e-4, atol=1e-7) + assert draft_grad[1, 2].abs().max() == 0 + + +def test_identical_distributions_give_zero_distillation_and_full_acceptance() -> None: + logits = torch.randn(1, 2, 3, 7) + mask = torch.ones(1, 2, 3, dtype=torch.bool) + loss, terms = _loss(_outputs(logits.clone(), logits, mask)) + torch.testing.assert_close(loss, torch.zeros(()), atol=1e-6, rtol=0) + torch.testing.assert_close(terms["accept_rate_per_pos_num"], terms["accept_rate_per_pos_den"]) + # Every drafted token accepted: tau counts the anchor plus the three drafted tokens. + torch.testing.assert_close(terms["tau_num"] / terms["tau_den"], torch.tensor(4.0)) + + +def test_confidence_head_regresses_the_acceptance_probability() -> None: + torch.manual_seed(1) + draft_logits = torch.randn(1, 2, 3, 7) + target_logits = torch.randn(1, 2, 3, 7) + mask = torch.ones(1, 2, 3, dtype=torch.bool) + confidence = torch.zeros(1, 2, 3, requires_grad=True) + _, without = _loss(_outputs(draft_logits, target_logits, mask)) + loss, terms = _loss(_outputs(draft_logits, target_logits, mask, confidence)) + # At logit 0 the BCE is log 2 for any target; the loss adds it on top of the LK term. + torch.testing.assert_close(terms["confidence_loss"], torch.tensor(2.0).log()) + torch.testing.assert_close(terms["loss"], without["loss"] + terms["confidence_loss"]) + loss.backward() + accept = 1 - 0.5 * (target_logits.softmax(-1) - draft_logits.softmax(-1)).abs().sum(-1) + # d BCE / d logit = sigmoid(0) - target, so the gradient sign follows 0.5 - acceptance. + assert torch.equal(confidence.grad.sign(), (0.5 - accept).sign()) + assert terms["confidence_diag_den"] > 0 + + +class _StubDraft(nn.Module): + """Return fixed outputs over two drafted slots, recording the features it receives.""" + + def __init__(self, outputs: DSparkForwardOutput): + super().__init__() + self.weight = nn.Parameter(torch.zeros(())) + self.outputs = outputs + self.seen = None + + def forward(self, **kwargs): + self.seen = kwargs + self.outputs.draft_logits = self.outputs.draft_logits + self.weight + return self.outputs + + +def test_trainer_reports_per_drafted_token_acceptance_over_the_block() -> None: + torch.manual_seed(2) + outputs = _outputs(torch.randn(1, 2, 2, 5), torch.randn(1, 2, 2, 5), torch.ones(1, 2, 2, dtype=torch.bool)) + draft = _StubDraft(outputs) + trainer = DFly2TrainerModule(draft) + keys, indices = (torch.zeros(1, 4, 2),), (torch.zeros(1, 2, 3, dtype=torch.int32),) + metrics = trainer( + input_ids=torch.zeros(1, 2, dtype=torch.long), + loss_mask=torch.ones(1, 2), + context_keys=keys, + context_indices=indices, + target_last_hidden_states=torch.zeros(1, 2, 3), + ) + # A block of 3 slots drafts 2 tokens: the per-position sums have block_size entries and + # the last one, which no drafted token fills, stays empty so it is not logged. + assert metrics.accept_rate_per_pos_den.tolist() == [2.0, 2.0, 0.0] + assert metrics.accept_rate_per_pos_num[-1] == 0 + assert draft.seen["context_keys"] is keys and draft.seen["context_indices"] is indices + metrics.loss.backward() + assert draft.weight.grad is not None