Skip to content

feat(speculative): add dfly2 draft training for deepseek v4.1 - #4971

Open
kashif wants to merge 20 commits into
NVIDIA-NeMo:mainfrom
kashif:kashif/feat/dfly2-drafter
Open

kashif wants to merge 20 commits into
NVIDIA-NeMo:mainfrom
kashif:kashif/feat/dfly2-drafter

Conversation

@kashif

@kashif kashif commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

Adds a DFly2 trainer (https://arxiv.org/abs/2611.34776) for DeepSeek-V4.1-Flash, matching the released DS-V4.1-Flash-DFly2-B6 drafter.

Changelog

  • TrainDFly2Recipe: a thin subclass of the DSpark recipe. DSpark gets small overridable seams for this (target wrapper, model owned draft, trainer module, FSDP units, default confidence weight), with no behavior change.
  • components/speculative/dfly2: target agnostic parts (per block key lists, D-PACE weighted LK objective, trainer module, target feature protocols).
  • models/deepseek_v41/dfly2.py: the draft. Each layer is paired with a ratio-1 target layer and reads that layer's own keys at the slots it attends from the row before the anchor. Includes MTP fusion on the anchor slot and the hidden plus attentive correction.
  • models/deepseek_v41/dfly2_target.py: captures the paired layers' keys and key lists during the frozen forward.
  • State dict adapter for the released layout, so draft_weights_path can warm start from the released checkpoint. Warm start checks the paired layers, block size and mask token recorded in its config.json.
  • Consolidated save of an FSDP sharded draft now lists every expert.
  • dpace_position_weights pulled out of DFlashDecayLoss so it can be shared.
  • Example config, docs page, README rows and tests (capture against a tiny V4.1 target, the recipe starting each draft layer from its paired target layer, a perturbation test pinning which rows each slot reads and must read, 2 rank FSDP2 gradient match under FP32 and BF16 policies, consolidated save and warm start round trip).

Differences from the paper, also in the guide:

  • Routed experts and the router start fresh instead of being drawn from the paired layer (the paper's attention only ablation: 3.51 vs 3.57).
  • The example uses AdamW with FP32 master weights (paper: Muon), at the paper's global batch of 256.
  • A block is supervised up to its first unsupervised label, as in the DSpark recipe.
  • The optional confidence head reads the final normalized states, as the V4.1 DSpark draft does, rather than the residual stream.

Not covered yet: sequence packing, the cached and remote target backends, and the aux free expert bias update.

Code provenance

  • Source: https://github.com/Tencent/AngelSpec at revision e02ea36e65d44e6e165c4ba73c139d500e12f2d9.
    • angelspec/models/draft/dsv41_attentive_correction.py (Apache-2.0, Copyright (C) 2026 Tencent): the attentive correction's gated prefix read and its initialization from the last draft layer.
    • angelspec/models/dflash.py (MIT, Copyright (c) 2026 LightSeek Foundation): the draft-key part of the per block key lists.
  • Files in this PR: nemo_automodel/components/models/deepseek_v41/dfly2.py (_prefix_read, initialize_attentive_correction) and nemo_automodel/components/speculative/dfly2/common.py (build_block_key_indices). The code was rewritten for this layout; the design of those parts follows the source.
  • Licenses: Apache-2.0 and MIT.
  • Notices: the source and license are recorded in the header of both files; the MIT copyright and permission notice is kept in full in common.py.

Before your PR is "Ready for review"

Pre checks:

  • Make sure you read and followed Contributor guidelines
  • Did you write any new necessary tests?
  • Did you add or update any necessary documentation?

Additional Information

  • Related to # (issue)

Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>
@copy-pr-bot

copy-pr-bot Bot commented Nov 27, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>
Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>

@HuiyingLi HuiyingLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bot review of 4035067d087a (round 1). The PR is a draft; this round was asked for by a maintainer. Five findings, inline. The first three need a fix before merge.

  1. Code provenance: _read_block and two more places correspond statement for statement to Tencent/AngelSpec, while the description says "Not applicable".
  2. tools/check_types.py fails on four new object annotations. That CI job has not run on this PR yet.
  3. With confidence_head_alpha > 0 the first training step stops on two ranks: mat1 and mat2 must have the same dtype, but got Float and BFloat16.
  4. The guide gives confidence_head_alpha a default of 0.0. The recipe's default is 1.0, so a YAML without the key runs into finding 3 on more than one GPU, and its warm start from the released drafter fails.
  5. 14 of 26 single-line defects, planted one at a time, pass all 26 new tests. Two of them leak the label into the draft.

Apart from these, the drafter's forward does what the paper describes. With the released weights it computes the same function as the authors' trainer, and warm-started by this PR against the real 40-layer target it accepts 79 % at slot 1 on held-out text. Nothing on main trains this drafter: the DSpark draft for V4.1 builds its own context keys from hidden states of layers 37 to 39, this one reads the keys its paired layers already cached.

Against the paper (arXiv 2611.34776: Section 4, Table 4, footnote 1, Section 5.1), the authors' trainer (Tencent/AngelSpec at 9f11dd0) and the release (AngelSlim/DS-V4.1-Flash-DFly2-B6 at d08e55a):

Paper This PR Result
Eq. (6), (7): the draft reads the paired layer's cached latents; one attention over context and block dfly2_target.py, _DeepseekV41DFly2Attention matches. DS-V4.1's latent is key and value at once, so there is no W^UK / W^UV
Eq. (8) and Table 4: top-512 of row A-1 plus the 128-token window before the anchor, layers 28 / 32 / 36, 646 keys build_block_key_indices, _window_key_indices matches
Eq. (9): attention and norms start from the paired layer initialize_from_target matches
Eq. (10): 128 routed experts drawn from the paired layer, with their router rows and biases routed experts and router start from a fresh initialisation differs. The guide and the YAML say so; "Not covered yet" in the description does not; please add it there. The paper's "Attention only" ablation: 3.51 against 3.57 accepted length (Table 11)
Last-layer hidden state fused into the anchor slot, gate starts at zero _DeepseekV41DFly2MTPFusion matches (row A-1, after the final norm)
Eq. (11): SwiGLU correction, context read, gated prefix read _DeepseekV41DFly2HiddenCorrection matches as the authors' trainer implements it: the SwiGLU output projection also starts at zero, and slot k's prefix read includes its own key
Eq. (12): D-PACE weights without gradient, LK mix compute_dfly2_loss matches. The mixing weight is per slot of every block, as in the authors' trainer (the LK paper aggregates over the batch)
Section 5.1: Muon, global batch 256, 3 epochs, 32K example YAML: torch.optim.AdamW with weight decay 0; by its launch line 64 ranks x 8 accumulation steps = 512 sequences per update optimizer and batch differ, not stated

What this rests on:

  • An oracle written from the paper's equations, sharing no code with the PR, against the code in FP32 on CPU: the loss within 9.8e-7 and its gradient within 4.4e-7 over 8 cases; the two-rank averaged gradient equals the global one (2 Gloo processes, 7.8e-9); key lists equal Eq. (8) on a small target whose selection is really sparse (window 4, top-k 4, 36 of 44 queries per paired layer dropped valid keys): 0 wrong rows.
  • The authors' trainer with the released weights loaded into both sides, identical synthetic inputs, CPU, FP32, 2,048 rows, 34 anchors beyond row 640: the same key set for 288 of 288 queries in each layer, logits within 2.0e-6 (relative L2), same argmax, loss 3.0102508 against 3.0102503. With the key list taken from row A, 18 of 288 key sets still agree. The three places of finding 1 are not independent of that trainer; the oracle above is.
  • The release: all 2,392 stored tensors (1,240 and the 1,152 FP4 scales) are read, the loaded draft equals an independent decode for 1,240 of 1,240, only the embedding and the LM head come from the target, and the round trip through the adapter is bit-identical.

One difference sits on the target side. The draft is fed Automodel's target caches: window keys in FP8, global keys in NVFP4, the selection scored on MXFP4 index keys. The authors' trainer feeds FP8 records for both segments and scores the selection on FP8 (dsv41_target.py). On synthetic unit-RMS latents the global segment is 9.4 to 9.8 % (relative L2) from that record. On the real target the latent formats do not show: the last two rows of the table below. The selection scoring (MXFP4 against FP8) was not varied.

The released drafter against the real target. 3 nodes x 4 GB300 (12 ranks, ep_size: 12), BF16, through TrainDFly2Recipe.setup() and its _forward_batch: the full 40-layer deepseek-ai/DeepSeek-V4.1-Flash (revision 314113f), the released drafter warm-started through draft_weights_path, TileLang for target and draft, seq_length: 16384, 48 held-out rows of allenai/tulu-3-sft-mixture, 24,576 blocks of six slots. Every row is evaluated on the same batches and anchors; the controls wrap the PR's functions. The text is not regenerated by the target (the target's top prediction equals the corpus token at 74 % of the slots), so the absolute numbers cannot be compared with the release card; the differences between rows are the evidence. Acceptance is 1 - TV per slot, as the recipe logs it; no optimizer step.

Variant Slot 1 2 3 4 5 tau
this PR, released weights 0.790 0.717 0.660 0.606 0.567 3.44
control: draft layer i reads the keys and key lists of paired layer i+1 0.641 0.555 0.495 0.442 0.403 2.59
control: key list of row A-2 0.746 0.685 0.634 0.585 0.547 3.23
control: key list of row A 0.825 0.743 0.679 0.622 0.582 3.58
control: the 128 window keys removed 0.687 0.620 0.570 0.522 0.487 2.89
control: the top-k picks removed 0.386 0.282 0.221 0.184 0.157 1.62
control: fusion fed the hidden state of row A 0.730 0.694 0.638 0.584 0.549 3.16
control: fusion fed zeros 0.640 0.638 0.600 0.556 0.525 2.83
control: the correction's previous token one older 0.790 0.078 0.035 0.029 0.028 1.86
global keys without cache quantisation 0.791 0.718 0.661 0.607 0.569 3.44
both segments as FP8 records, the authors' format 0.791 0.718 0.661 0.607 0.568 3.44

For the first row the standard deviation over the four batches is 0.018 to 0.025 per slot, and a repeat gives the same numbers. The draft's top prediction equals the target's at 79.6 % of slot 1 and 59.4 % of slot 5. That agreement at slot 1 does not drop where the selection is sparse: 79.2 % for anchors before row 640, 79.5 % up to row 8,192, 80.2 % beyond; 23,880 of the 24,576 blocks sit at rows with more causal keys than top-k.

Row A's key list scores higher than row A-1's. It holds the anchor's own cached keys and the selection the target makes one step later; neither exists when a block is drafted (Section 3.3 of the paper measures the selection part of this gap). The paper, the authors' trainer and this PR read row A-1, and row A-2 scores lower.

Four optimizer steps through the recipe's loop on the same target (AdamW, the first four of 20 warm-up steps towards the example's lr of 5e-4): all 88 trainable tensors have finite gradients, and none is exactly zero from the third step on. From the PR's initialisation the training loss is 40.3, 43.1, 30.3 and 33.9 and acceptance stays below 0.03: four steps show that it runs, not that it learns. From the released drafter, slot 1 on the held-out rows falls from 0.790 to 0.657 after the four steps, and the gradient norm before clipping is 1.0, 6.3, 18.4 and 6.2. This is the step size of AdamW at these learning rates on a converged drafter, not the gradient. In an emulation without the target (the released drafter at a near-optimal point of this PR's loss, one GB300) the recipe's optimizer does the same from the first step (loss 0.307 to 1.948 in four steps), FP32 master weights do not help (0.307 to 5.100), a small step along the gradient lowers the loss as first order predicts (0.169 against 0.163), and at one hundredth of the peak learning rate the loss stays at 0.317. The guide and the YAML offer draft_weights_path together with this optimizer block.

Runs (torch 2.14.0a0 nv26.08 unless torch 2.15.0a0 nv26.11 is named; BF16 on GPU)

  • TileLang draft attention, the path the description lists as not yet run on GPU. On H100, at the release's per-query shapes (64 heads x 512, key lists of width 704 from build_block_key_indices, queries without keys, -1 slots in the middle of a list): forward and backward run; against an FP64 oracle the output is 1.82e-3 off (relative L2) where BF16 rounding of the exact result alone is 1.66e-3; sdpa 1.72e-3, eager 1.67e-3; a query without keys returns exactly zero. On GB300 with the released drafter and synthetic target features, 512 anchors x 6 slots at 4,096, 16,384 and 32,768 rows: finite loss, no missing, zero or non-finite gradient in 88 trainable tensors, peak 61.65 GiB on one GPU at 32,768 rows. Whole-draft logits of tilelang against sdpa differ by 0.0356 (relative L2); sdpa against eager differ by 0.0359, so this is rounding.
  • The recipe through python -m nemo_automodel.recipes.speculative_decoding.train_dfly2 on a small random V4.1 target with the release's per-head shapes (window 16, top-k 32, 1,024-token Tulu-3 rows, TileLang for target and draft): one H100, 48 steps and validation, loss 7.76 to 2.40; two ranks with FSDP2, 24 steps and validation, loss 7.09 to 3.58 in both of two runs. The selection was sparse for 12,004 of 12,011 anchors. After setup on two ranks each draft layer's attention, norms, mHC parameters and shared expert equal the paired target layer's tensors bit for bit. On two ranks every run trained and validated and then stopped in the final consolidated save (RuntimeError: Safetensors consolidation failed before final synchronization, caused by KeyError: 'model.layers.0.ffn.experts.64.w1.weight'). The DSpark recipe does the same on the merge base, so this is not counted against this PR; the new example also sets save_consolidated: final.
  • Shared code. dpace_position_weights against the merge base's DFlashDecayLoss._dpace_weight: 6,000 of 6,000 cases bit-equal on CPU and H100, torch 2.14 and 2.15. The DSpark recipe, seeded, on the merge base and on this head: every step metric and every saved draft tensor bit-equal for Qwen/Qwen3-0.6B (one GPU, two ranks with FSDP2, two ranks with DDP), MiniMax M3 (two ranks, the model-owned draft branch) and Gemma4-12B (one GPU). The DSpark adapter's outputs are identical on both trees.
  • The three new test files: 26 passed on torch 2.14 and on torch 2.15, CUDA hidden. The suites of the four touched test directories on both trees: no failure that exists only on this head.

Smaller things, no inline comment

  • Warm start does not compare the release's config.json with the YAML: target_layer_ids: [24, 28, 32] and another mask_token_id load the released weights without an error or a warning. The existing check reads dspark_meta.pt only, which a release does not have.
  • Like the DSpark example, this one trains BF16-stored weights with torch.optim.AdamW, and the recipe prints its precision warning. In the small-target runs the 12 norm gains copied from the target were bitwise unchanged after 144 optimizer steps at a peak lr of 5e-4, and the 5 new ones were still exactly 1.0. The authors' trainer steps an FP32 master copy, and the released drafter's gains are not at 1.0: final_norm 0.77 to 0.99, hidden_correction.embed_norm 0.30 on average.
  • In blocks with unsupervised labels the supervision mask and the D-PACE weights differ from the authors' trainer (the cumulative mask of build_eval_mask cuts a block at its first unsupervised label).
  • build_block_key_indices says an anchor at the sequence start "sees no key"; it sees its own block. The comment above self.config.dfly_config says the exported config.json is "as the released draft stores it"; the export is a flat text config without index_topk, rope and dense_dtype. examples/speculative/README.md has no DFly2 row.

Comment thread docs/guides/speculative/dfly2.mdx Resolved
Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>
Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>
Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>

@HuiyingLi HuiyingLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bot review of 85eceb902900 (round 2). The PR is a draft; this round was asked for by a maintainer. Round 1: review 6094029351.

Three of round 1's five findings are fixed and one is partly fixed. The first one, code provenance, is still open and needs an answer before merge. One point is new. Three inline comments.

Round 1 On this head
1 Code provenance Open. The three places were rewritten and compute what they computed before. The source is still not recorded. Inline.
2 tools/check_types.py Fixed. Exit status 0 in CI's lint environment, and 1 on the old head with the same four lines.
3 Confidence head on two or more ranks Fixed. With the head on, training runs on 2, 4 and 12 ranks, and the head's linear gets FP32 weight, bias and input on every rank. The old head stops with the old error on the same command.
4 Guide default of confidence_head_alpha Fixed. With the key left out the recipe uses 0.0, builds no head, and the released drafter loads. The DSpark recipe keeps 1.0.
5 Tests Partly. 21 of the 26 planted defects now fail a test (12 before), both label leaks among them. The same push removed tests the old head had. Inline.

New: with 12 ranks, and with 6, 24, 48 or 96, the first checkpoint save raises on some ranks and the job does not exit. The cause is shared code on main; the rule for choosing the number of ranks is in this PR's example. Inline.

Is the PR needed? Yes, as in round 1. Nothing on main (591bdc1) trains this drafter and no other open PR adds it. One part is not needed here: the three lines added to models/deepseek_v41/dspark.py are the statement that #4973 (open) adds at the same place, with its own test. This PR has no test for them, and the two PRs conflict in that file. The lines do what the description says: on two ranks the V4.1 DSpark recipe trains with the same losses as on the merge base and writes its final export, where the merge base stops with a KeyError.

The other points of round 1's body

  • Eq. (10) is still not implemented. The description and the guide now say so, with the paper's 3.51 against 3.57.
  • Optimizer and batch size: changed and now stated. See "The example's optimizer block".
  • Warm start now compares the checkpoint's config.json with the run. The release passes; other paired layers, another block size or another mask token are refused before the draft is built. A step checkpoint given as <step>/model is not covered: its config.json sits in model/.hf_metadata/, and a draft saved with block size 6 loads into a run with block size 7 without a message.
  • The supervision mask is now stated in the guide and in the description.
  • The two stale sentences are corrected and the README has its rows. The exported dfly_config holds all 19 fields of the release's.

What the fix commits changed in the forward (CPU, torch 2.14)

  • build_block_key_indices equals the old one element for element in 172,800 of 172,800 cases. initialize_attentive_correction gives 12 of 12 tensors bit-equal, also at the released size.
  • _prefix_read against the old _read_block: within 1.6e-7 (relative, FP32) and 2.9e-16 (FP64). The same comparison differs in 199 to 212 of 216 cases when the sink is removed or the prefix is made exclusive.
  • The whole draft with the released weights, old head against new head: logits within 2.6e-7 (relative L2, FP32), the same top token in 240 of 240 slots, the same loss.
  • Unchanged from round 1: parity with the authors' trainer (Tencent/AngelSpec at 9f11dd0, released weights in both, 2,048 rows, FP32: the same key set for 288 of 288 queries in each layer, logits within 2.8e-6 on both heads; round 1's 2.0e-6 was measured on another node with another thread count), the oracle written from the paper's equations (54 of 54 checks, all 26 planted defects caught) and the release round trip (2,392 stored tensors read, 1,240 of 1,240 equal to an independent decode, also with the head's two tensors).

The real target again. 3 nodes x 4 GB300 (12 ranks, ep_size: 12), BF16, through TrainDFly2Recipe.setup() and its _forward_batch: the full 40-layer target, the released drafter through draft_weights_path, and the 48 held-out rows of round 1 with the same batches and anchors (48 of 48 input and anchor hashes equal), 24,576 blocks. The text is not regenerated by the target, so the differences between rows are the evidence. Acceptance is 1 - TV per slot.

Slot 1 2 3 4 5 tau
released weights, old head (round 1) 0.790 0.717 0.660 0.606 0.567 3.44
released weights, this head 0.790 0.717 0.660 0.606 0.567 3.44
control: draft layer i reads paired layer i+1 0.641 0.555 0.495 0.442 0.403 2.59
control: the 128 window keys removed 0.687 0.620 0.570 0.522 0.487 2.89
four optimizer steps with the example's optimizer block as it is (lr 5e-4) 0.656 0.551 0.478 0.424 0.383 2.72
four optimizer steps with the same block and lr 5e-6 0.790 0.716 0.660 0.606 0.567 3.44

The two heads differ by at most 1.7e-6 per slot; a repeat within the job differs by 1.6e-7.

With the confidence head on (an observation; the head is off by default). Same setup: the released drafter plus a fresh head, confidence_head_alpha: 1.0, four steps at lr 5e-6. Acceptance at step 0 equals the second row of the table within 1.8e-7. The head reads the backbone states before final_norm, which have a per-element RMS of 34.5 on this target. The confidence loss starts at 39.4, and the head's gradient norm is 1,751 to 1,891 where the rest of the draft has 1.007, 0.832, 1.196 and 0.774. The recipe clips the whole trainer module as one vector (max_grad_norm: 1.0), so about 1/1,800 of the draft's gradient is left, an RMS of about 5e-9 per element against the optimizer block's eps of 1e-8. In these four steps the draft's cross entropy on the held-out batches changed 0.38 times as much as without the head. With the head fed final_norm(backbone) instead (through a wrapper in this review's driver, not a change of the PR; same rows), the confidence loss starts at 1.30, the head's gradient norm is 36 to 38 (still about 36 times the rest of the draft's), and the cross entropy changes 0.92 times as much. The authors' config for this drafter also feeds the head the state before the final norm (confidence_on_prenorm_hidden: true); the V4.1 DSpark draft in this repository feeds it the normalised state. This is four steps on four batches: it shows the size of the effect at the start of a run, not what a full run does.

The example's optimizer block. It now builds Transformer Engine's FusedAdam in AdamW mode with FP32 master weights. The recipe logs that, and its precision warning is gone. Two different things were measured.

Weights that cannot move. Small V4.1 target, two ranks, 144 steps, peak lr 5e-4. With the example's block none of the 88 trainable tensors is bitwise unchanged at the end, and all 19 norm gains move, by up to 0.023. With torch.optim.AdamW in the same run, and with master_weights: false, all 19 norm gains are bitwise unchanged after 144 steps, although their gradients are not zero. One rank gives the same counts. A resume from an epoch checkpoint restores the FP32 state: on both ranks 88 of 88 parameter shards, moments and remainders equal the uninterrupted run's, and the first resumed step has the same loss to the last digit.

The step size on a warm start. On the real target, four steps from the released drafter with the block as it is (the first four of 20 warm-up steps, lr 2.5e-5 to 1e-4) lower slot 1 from 0.790 to 0.656. FP32 master weights do not help here: round 1 measured 0.657 / 0.570 / 0.509 / 0.461 / 0.421 with torch.optim.AdamW. With lr 5e-6, the value the YAML comment and the guide now give for a warm start, slot 1 stays at 0.790 (0.790488 to 0.790431) over four steps, in which the lr is 2.5e-7 to 1e-6. More steps at that value were not run on the real target.

The final consolidated save. save_consolidated: final through the recipe on this head, small V4.1 target:

Layout Result
one rank finishes; 1,242 of 1,242 tensors, each bit-equal to the live draft
two ranks finishes; 1,242 of 1,242, bit-equal (1,244 with the head on). The old head stopped with the KeyError
two ranks, single_rank_consolidation: true finishes; 1,242 of 1,242 (666 on the old head)
four ranks finishes
two ranks, a 12.4 GB draft exit 0, but 128 of 1,242 tensors are in no file; a warm start from it stops with Expert weights missing from checkpoint: 128/1152

A warm start at lr 0 from each complete export reproduces the last validation of the run that wrote it in every field.

The last row comes from the checkpointer on main: every rank sizes the output shards from the tensors it exports itself, so the ranks can disagree once one rank's export passes 5 GiB, and they do when a shard boundary falls among a layer's routed experts. The old head stopped in this save with the KeyError; with this push it exits 0 with the tensors missing. Every DFly2 export takes this path, because the draft's names are never in the target's index. It is the cause of the open thread on #4973. At the released shapes (CPU ranks, nothing patched) two ranks leave 128 of 1,242 tensors in no file and three ranks 92. Computed with the checkpointer's _divide_keys_by_size, which predicted these three runs exactly, 4, 8, 16, 32 and 64 ranks give a complete export. The 40-layer target did not load on fewer than 12 GB300, so the shipped config is not affected. With single_rank_consolidation: true the 12.4 GB export is complete.

The DSpark recipe. train_dspark.py changed again, so round 1's comparison was repeated. Seeded DSpark runs on the merge base and on this head are bit-identical in every step metric and every saved tensor: Qwen/Qwen3-0.6B on one GPU and on two ranks with FSDP2, MiniMax M3 on two ranks (the model-owned draft) and Gemma4-12B on one GPU, each with the key left out and with it set to 0.5. Two runs of one tree are identical as well, and a scratch copy with another default differs.

Tests and gates. The three test files: 29 passed on torch 2.14 and on torch 2.15 (CPU). The suites of the four touched test directories pass on this head and on the merge base (CPU, torch 2.14). In CI's lint environment ruff, tools/check_types.py, the import contracts, bandit, tools/recipes/check_recipes.py and tools/docs/check_docs.py are green. No CI job has run on this PR; nothing was triggered.

Correction to round 1's body. Round 1 counted 17 norm gains that never move under torch.optim.AdamW. The count is 19: the two norm gains of the attentive correction (q_norm, kv_norm) were not counted.

Smaller things, no inline comment

  • initialize_attentive_correction now reaches q_norm, wq_b, kv_norm and wo_a by string name (dfly2.py#L673-L674). The old head accessed the attributes directly, which is what "Avoid reflection" asks for.
  • The docstring of initialize_from_target and the YAML header say "attention, norms and mHC mixes". The code also copies the shared expert, as the guide now says.
  • The guide says "Launch the same command on every node" above a command with --node-rank=0. The YAML header adds "and vary --node-rank".

Not run: the example's own layout (64 ranks, 32K rows, accumulation 4); more than four optimizer steps on the real target; target-regenerated data; Eq. (10), which is not implemented; a consolidated export at the released size on GPU; CI's -n 2 --dist loadfile invocation.

Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>
Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>
Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>

@HuiyingLi HuiyingLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bot review of 8d3334912c66 (round 3). The PR is a draft; this round was asked for by a maintainer. Earlier rounds: review 6094029351 and review 6098447847.

The point that had to be answered before merge, code provenance, is closed. Nothing in this round blocks. There are three inline comments, all about this push: the new rank-count check copies a rule that an open PR changes, it also refuses runs that never save, and tests were narrowed. This review is a comment. GitHub keeps showing "changes requested" for this account, because a comment review does not replace the two earlier ones; a maintainer has to dismiss both.

Round 2 On this head
1 Code provenance Closed. Both file headers and the description name the source, the revision, the files and the licences, and each of these is true.
2 Tests Partly. All but one of the defects round 2 named now fail a test, and 22 of round 1's 26 defects fail a test (21 on the round-2 head). The same push narrowed three other tests. Inline.
3 Rank counts that cannot save Answered with a check in setup(). On today's main it refuses exactly the rank counts whose save fails, on every rank, and the job exits. Two inline comments.

Is the PR needed? Yes. main (cb998c9) has no file that mentions this drafter, and none of the other open PRs (322 in all) has it in its title or branch. The part that was not needed is gone: models/deepseek_v41/dspark.py is byte-identical to the merge base again, and this head merges cleanly with #4973 (the round-2 head conflicted there) and with main. The new check is needed only as long as main maps expert shards the way it does today; see the first inline comment.

Code provenance

  • The headers of dfly2.py and speculative/dfly2/common.py and the description's section carry every field that CODING_GUIDELINES.md, "Code provenance" and the PR template ask for: source URL, 40-hex revision, original path, licence, the affected functions, and where the notices are kept. The form is the one main already uses in nemotron_decision/serving_prompt.py.
  • The revision is right. Tencent/AngelSpec at e02ea36 is the commit that added dsv41_attentive_correction.py, 30 hours before this PR's first commit. Rounds 1 and 2 compared against its child 9f11dd0; the 261 Python files are byte-identical in the two, so the earlier comparisons hold.
  • The MIT notice in common.py equals the header of upstream's angelspec/models/dflash.py character for character. dsv41_attentive_correction.py has no header upstream; "Copyright (C) 2026 Tencent" and Apache-2.0 are what upstream's LICENSE states. Upstream has no NOTICE file.
  • The four behaviours of _prefix_read that round 2 listed are inside the function the record names. Beyond the three recorded places the comparison with the whole upstream tree finds nothing: by round 1's measure (at least five statements equal in order after renaming, and half of the function) 0 functions match on this head, 1 on the first head, and 0 for the merge base's own DSpark code as a control.
  • "Closed" means the record is complete and true. Whether the adapted code is accepted is the maintainers' decision under the rule's first sentence ("Make every effort to avoid copying code from external repositories"). One detail for that decision: _create_dflash_sparse_kv_indices was added by Tencent to a file that carries only the LightSeek MIT header, and upstream's LICENSE says that Tencent's modifications are Copyright (C) Tencent.

The rank-count check on today's main

  • For every expert count and every world size from 1 to 256 (65,536 pairs, CPU) check_fsdp_expert_split raises exactly where torch's FSDP2 split and the export's get_expert_slice_for_rank disagree on some rank: no false refusal and no miss. A real fully_shard confirms the split in 14 of 14 cases. For 128 experts it lets through 1, 2, 3, 4, 8, 16, 32, 43, 64, 128 and every count above 128, so the sentence in the guide, the YAML header and the description is right.
  • It checks the right rank count. For a V4.1 target the draft is always sharded over all ranks; ep_size and dp_replicate_size only shape the target's mesh (runs with ep_size 2 and 4 and with dp_replicate_size 2 on 4 ranks).
  • Runs with small V4.1 targets and the unmodified 128-expert draft:
Ranks Result
6 GPU ranks, the recipe CLI refused in setup() on 6 of 6 ranks 32 s after launch; the launcher exits 1 after 35 s
8 GPU ranks, the recipe CLI trains 4 steps, writes step checkpoints and the final export, exit 0; the export holds all 1,242 names
5, 6, 7, 12, 24 CPU ranks refused in setup() on every rank; the launcher exits 1 after 29 to 40 s; nothing is written. With the check switched off, the first save raises on the ranks that the split predicts
1, 2, 3, 4, 8, 16, 43 CPU ranks train, write a step checkpoint and the final export; 1,242 of 1,242 tensors are bit-equal to the live draft

The V4.1 target load needs CUDA. So every CPU-rank run in this review, here and in the inline comments, ran the recipe's setup() and loop through a driver that replaces only the target load.

The real target again. 3 nodes x 4 GB300 (12 ranks, ep_size: 12), BF16, the full 40-layer target, the released drafter through draft_weights_path.

With the recipe CLI, unmodified, setup() raises the new ValueError on 12 of 12 ranks, 302 to 304 s after launch. By then the target is loaded (167 s) and the draft module is built (about 107 s). Each launcher exits 1 by itself 7 to 8 s later and nothing is written. So on 12 GB300, the smallest layout on which this target loaded in these reviews, the round-2 head trains and cannot save, and this head does not start.

The forward was measured through TrainDFly2Recipe.setup() and its _forward_batch on the 48 held-out rows of rounds 1 and 2 (same batches and anchors, 48 of 48 hashes equal, 24,576 blocks). Nothing is saved in this run; the check had to be switched off for it, in the review's driver process only (second inline comment). Acceptance is 1 - TV per slot.

Slot 1 2 3 4 5 tau
released weights, round-2 head 0.790 0.717 0.660 0.606 0.567 3.44
released weights, this head 0.790 0.717 0.660 0.606 0.567 3.44
control: draft layer i reads paired layer i+1 0.641 0.555 0.495 0.442 0.403 2.59

The two heads differ by at most 5.2e-8 per slot; a repeat within the job is identical.

The confidence head (off by default) now reads the final-normalized states. Round 2 reported its input as an observation and asked for nothing; the description lists the change. With the same fresh head as in round 2, the confidence loss starts at 1.30 (39.4 on the round-2 head) and the head's gradient norm is 35.6 to 38.5 (1,751 to 1,891 before), against about 1 for the rest of the draft. Acceptance at step 0 equals the second row of the table within 2.1e-7, and the head's linear gets FP32 operands on all 12 ranks.

What the fix commits changed in the forward (CPU, torch 2.14, FP32, released weights, 2,048 rows): nothing. Between the round-2 head and this head all 31 recorded stages are bit-equal and the logits are identical; with the head on, the draft's logits and the gradients of its 88 tensors are bit-equal to the head-less ones with the default stop-gradient. On this head, parity with the authors' trainer is 2.9e-6 (relative L2) with the same key set for 288 of 288 queries in each layer, the oracle from the paper's equations passes 54 of 54 checks and catches 26 of 26 planted defects, and the release round trip reads all 2,392 stored tensors, and the 1,240 tensors they decode to all equal an independent decode.

The final consolidated save. save_consolidated: final through the recipe on this head, small V4.1 target, BF16, H100 ranks:

Layout Result
one rank finishes; 1,242 of 1,242 tensors, each bit-equal to the live draft (1,244 with the head on)
two ranks finishes; 1,242 of 1,242 tensors, each bit-equal to the live draft (1,244 with the head on)
two ranks, single_rank_consolidation: true finishes; 1,242 of 1,242, bit-equal
four ranks finishes; 1,242 of 1,242, bit-equal (1,244 with the head on)
two ranks, a 12.3 GB draft (the row round 2 called 12.4 GB) exit 0, and 128 of 1,242 tensors are in no file: the same 128 as on the round-2 head

A warm start at lr 0 from each complete export repeats the last validation of the run that wrote it in every field. The DFly2 draft records its own list of released names (dfly2.py#L625), so it does not need the lines this push removed from dspark.py; with that one line removed in a scratch copy, the two-rank save stops with round 1's KeyError.

The DSpark recipe. train_dspark.py changed again: between the round-2 head and this head only setup differs among its functions, plus the new method. Seeded DSpark runs on the merge base and on this head are bit-identical in every step metric and every saved tensor, in 35 of 35 pairings: Qwen/Qwen3-0.6B on one GPU, on two ranks with FSDP2 and on two ranks with DDP, MiniMax M3 on two ranks, and Gemma4-12B on one GPU, each with confidence_head_alpha left out and with 0.5 and 0.0. Two runs of one tree are identical as well, and scratch copies with another default differ. The V4.1 DSpark recipe on two ranks trains bit-identically on the merge base and on this head, and both stop at the final save with the same KeyError, which is what #4973 fixes. This head merged with #4973 writes that export, and it equals the export of #4973's own tree in 1,226 of 1,226 tensors.

Tests and gates. The three test files: 34 passed on torch 2.14 and on torch 2.15 (CPU). The suites of the four touched test directories pass on this head and on the merge base (CPU, torch 2.14). In CI's lint environment ruff, tools/check_types.py, the import contracts, bandit, the copyright check, tools/recipes/check_recipes.py and tools/docs/check_docs.py are green, also on this head merged into main at 591bdc1. main has since moved by one test-only commit (cb998c9); on this head merged into it the three test files pass on both torch versions as well. No CI job has run on this PR; nothing was triggered.

Round 2's other points, one line each

  • Eq. (10): still not implemented; the description and the guide say so. Unchanged.
  • Warm start from <step>/model: fixed. It is now checked through model/.hf_metadata/config.json. On one rank a draft saved with block size 6 is refused for a run with block size 7, where the round-2 head loads it without a message. On two ranks another block size, other paired layers and another mask token are each refused on both ranks before the draft is built, and the job exits. The last correction below says whether such a folder can be used as a warm-start source on two ranks.
  • The confidence head's input: changed, see above.
  • The 12.3 GB two-rank export that loses 128 tensors: unchanged (the checkpointer on main; see the table above).
  • The three smaller things: all fixed.

Corrections to round 2

  • Round 2's third comment and its body said that after the raise at the first save the job "does not exit". Round 2 did not show that: its runs were ended by hand at most 3 min 55 s after the raise, with the example's dist_env.timeout_minutes: 120. Measured in this round on 6 H100 ranks with the check switched off and nothing ended from outside: with timeout_minutes: 1 the launcher exits 1 by itself 128 s after the first raise, with timeout_minutes: 2 after 188 s. Until then the ranks that did not raise wait in all_gather_object and the ranks that raised in destroy_process_group. The right sentence is: the run stalls at its first checkpoint for dist_env.timeout_minutes, 120 in the example, and then fails. The two hours themselves were not run. This PR's new notes say "hang"; that word came from round 2 and needs no change.
  • Round 2's third comment asked for the rank rule to be written into the YAML header and the guide. It did not say that #4058, open since September, changes the shared code that the rule describes. This head followed the request and added a check on top; all of it describes today's main only (first inline comment).
  • Round 2 compared with Tencent/AngelSpec at 9f11dd0 and asked for "the revision that was used". 9f11dd0 is younger than this PR; the revision the record now names is its parent.
  • Round 2's second comment listed four defects that the removed tests had caught. The removed recipe test also pinned the block size, the number of anchors and the mask token that the recipe hands to the builder; a recipe that hands over other values passes every test on the round-2 head and on this one.
  • Round 2's body said that a step checkpoint given as <step>/model loads into a run with another block size without a message. That holds for a checkpoint written by one rank, which is what round 2 measured. A step checkpoint written by two ranks does not load through draft_weights_path at all, with any settings: its files hold per-rank shards and the loader stops with size mismatch, on the round-2 head, on this head, and for the V4.1 DSpark draft on the merge base. On two or more ranks only the consolidated export is a warm-start source.

Smaller things, no inline comment

Not run: the example's own layout (64 ranks, 32K rows, accumulation 4); a save on 16, 32, 64 or 128 GPU ranks; the two hours of the example's distributed timeout; more than four optimizer steps on the real target; target-regenerated data; Eq. (10), which is not implemented; CI's -n 2 --dist loadfile invocation.

…t saves

Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>
Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>
@kashif

kashif commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough reviews. The latest push addresses the remaining points:

  • the draft's router bias now stays in FP32, and the corpus cross entropy runs chunked without autograd
  • the rank-count check only runs when checkpointing is enabled, and its test now compares against the export's own split, so it will flag the change in fix(moe): map FSDP expert shards with torch.chunk layout #4058
  • the init, BF16 FSDP and recipe tests were tightened as suggested (per-tensor BF16 bound, non-default source values, the sdpa default and the .safetensors path)
  • the attribute lookup in initialize_from_target is gone, plus the small doc and typing fixes

Each of the planted defects mentioned now fails a test.

@HuiyingLi HuiyingLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bot review of d9633a7aa85d (round 4). The PR is a draft; this round was asked for by a maintainer. Earlier rounds: review 6094029351, review 6098447847 and review 6100966043.

One thing has to change before merge. #4058 is on main now and this branch does not have it. Merged with main, the rank-count check refuses rank counts that save, and the test that this push added for the check fails (first inline comment). The fix is to merge main and remove the check; on this head taken by itself the check is exact. Round 3's other two comments are answered. Two small inline comments ask for one test each. This review requests changes for the first inline comment only. Nothing else from rounds 1 and 2 is asked again.

Round 3 On this head
1 The check copies the export's split by hand; a test should compare the two Done as asked. Without #4058 the check and the export agree for every expert count and world size from 1 to 256 (65,536 pairs). Merged with main they do not, and the new test fails. First inline comment.
2 The check also refused runs that never save Fixed. With checkpoint.enabled: false, 6, 12 and 24 CPU ranks start, train, validate and exit 0; no checkpoint is written, and the export code is not entered on any rank. The unmodified recipe CLI on six H100 ranks with the same setting trains, validates and exits 0, and writes no checkpoint. With checkpointing on (no checkpoint block, enabled: true, or --checkpoint.enabled true on the command line), 12 CPU ranks are refused on every rank. For 25 ways to write the checkpoint block or its command-line override, the new condition equals what the recipe's resolved checkpoint config says.
3 Tests were narrowed; the two start-up tests compared fresh with fresh; the head's new input was not pinned Fixed for everything the comment asked. Each of these now fails a test: the six zeroed BF16 gradients, the eager default of draft_attn_backend, a path to a .safetensors file, the head reading the states before final_norm, each of the 13 copies of initialize_from_target and each of the 4 copies of initialize_attentive_correction left out, and the default read inline in setup(). The restored BF16 bound passed in 8 of 8 runs on torch 2.14 and in 8 of 8 on torch 2.15. 23 of round 1's 26 single-line defects fail a test (22 on the previous head). Not asked again, and still passing every test: the three defects from round 2's comment (position ids shifted by one, an exclusive prefix read, a causal block), and a recipe that hands another block size, number of anchors or mask token to the builder.

The two changes that answer the other review on this PR

The router bias stays FP32 (dfly2.py#L539). The change is right.

  • On the previous head cast_model_to_dtype turned the buffer layers.*.ffn.gate.e_score_correction_bias into BF16 before the warm start copied the checkpoint's values into it. On this head it is FP32 and bit-equal to the checkpoint after the cast, after the load, after FSDP2 wrapping and after a forward, on every rank. This was read at released size, with the released weights in one process on an H100 and on two CPU ranks, and with the control checkpoint of the third point on two and four CPU ranks and on two H100 ranks.
  • The released drafter stores its three router biases as FP32, and all 384 values are representable in BF16. So the previous head held the same values. On the recipe's BF16 path on an H100, at released size with the released weights (3,072 gate tokens per layer), both heads select the same experts for every token and their logits are bit-identical. The acceptance numbers of rounds 1 to 3 stand for that reason. What changes for the released drafter is the stored dtype of the three exported tensors: BF16 on the previous head, FP32 now, as in the release (31 FP32 tensors in the export; 28 before).
  • With biases that BF16 cannot hold (a control: the released drafter with the three biases shifted by up to 0.02), the previous head rounds all 128 values of every layer, by up to 0.0199, and selects another expert set than an FP64 recomputation for 224, 326 and 258 of 3,072 tokens in the three layers. This head selects the oracle's set for every token. Through the recipe on a small V4.1 target, on one and on two ranks, such biases are FP32 and bit-equal after setup(), before the save and in the export.

The corpus cross entropy runs in chunks, without autograd (loss.py#L100-L125). It changes no number.

  • Every returned term and the gradient with respect to the draft logits are bit-equal to the previous head's in 57 of 57 cases, on CPU and on CUDA: FP32, FP64 and BF16 logits, 127 to 645 slots, with and without the confidence term, non-contiguous inputs, masked slots, all blocks dropped. At released size with the released weights (CPU, FP32), all 13 terms and the gradients of all 88 draft tensors are bit-equal. On CPU, a cross entropy and D-PACE weights written out in FP64 from the paper's Eq. (12) agree to 1.2e-6 and 5.6e-7.
  • The cross entropy carried no gradient on the previous head either. On this head only the decorator keeps it out of the graph: with @torch.no_grad() removed the gradient changes in 51 of 57 cases, and test_objective_matches_the_written_out_formula then fails.
  • Memory, measured for the loss and its backward alone on an H100 at the example's shapes (512 anchors, 5 drafted slots, a vocabulary of 129,280). With FP32 logits, which is what the draft emits on the recipe's BF16 path, the forward of the loss needs 1.23 GiB less, and the peak over forward and backward is 4.99 GiB on both heads, because the backward of the distance terms is higher than the old forward. With BF16 logits the peak is 1.20 GiB lower.

The rest of the draft on this head

What Result on this head
Forward (CPU, torch 2.14, FP32, released weights, 2,048 rows) all 31 recorded stages and the logits are bit-equal to the previous head's
Start from the target the draft after initialize_from_target is bit-equal to the previous head's in every tensor (72 of 72 with a small target, 96 of 96 at released size), from the same copies in the same order
Parity with the authors' trainer 2.9e-6 relative L2 on both heads, the same key set for 288 of 288 queries in each layer
Oracle from the paper's equations 54 of 54 checks pass; 26 of 26 planted defects are caught
Release round trip (the recipe's BF16 cast, then the released weights) all 2,392 stored tensors are read, and the 1,240 tensors they decode to all equal an independent decode: 88 bit for bit and 1,152 as exact FP4 decodes. This is the one row of this table that the push changes: on the previous head 85 were bit-equal and 3, the router biases, had the same values in another dtype
Final consolidated save through the recipe (small V4.1 target, BF16, H100 ranks) one rank, two ranks, two ranks with single_rank_consolidation: true, four ranks: 1,242 of 1,242 tensors, each bit-equal to the live draft; a warm start at lr 0 from each export repeats the validation in 8 of 8 fields
The shared DSpark recipe in train_dspark.py no function has other compiled code than on the previous head; one differs in an annotation. Seeded DSpark runs on the merge base and on this head are bit-identical in every step metric and every saved tensor in 27 of 27 pairings: Qwen/Qwen3-0.6B on one GPU, on two ranks with FSDP2 and on two ranks with DDP, Gemma4-12B on one GPU, and MiniMax M3 on two ranks

The real target was not run in this round. The push changes two things on its forward path. The router bias has the same values on both heads for the released drafter, and they are added to FP32 scores. The loss is bit-identical. Round 3's 12-rank run had already recorded, on rank 0, that the BF16 buffer of the previous head equals the released values in 128 of 128 elements per layer.

Tests and gates. The PR's four test files: 138 passed on this head on torch 2.14 and on torch 2.15 (CPU). Merged with main: 137 passed and 1 failed on both, the test of the first inline comment. The suites of the four touched test directories pass on this head (680, 1,403, 502 and 370 tests passed; torch 2.14, CPU); on the merge the only failure is that test. In CI's lint environment, ruff, tools/check_types.py, the import contracts, bandit, the copyright check, tools/recipes/check_recipes.py and tools/docs/check_docs.py pass on this head and on the merge. No CI job has run on this PR; nothing was triggered.

Round 3's open points, one line each

  • Code provenance: closed in round 3; this push does not touch the two headers or the functions they name.
  • Eq. (10): still not implemented; the description and the guide say so. Unchanged.
  • Warm start from <step>/model: unchanged.
  • The confidence head's input: now pinned by a test. The states before final_norm fail it; the corrected states, which equal the normalized ones in a fresh draft, do not.
  • The 12.3 GB two-rank export that loses 128 tensors: the checkpointer on main; its file is byte-identical on this head and on the merge. Not run again.
  • Round 3's three smaller things: all fixed.

Corrections to rounds 1 to 3

  • Rounds 1, 2 and 3 each recorded that the three router biases change from FP32 to BF16 in the draft, with unchanged values for the released drafter. None of the three reviews reported it; round 3's body said only that the 1,240 tensors of the release round trip equal an independent decode. The other review found it.
  • Round 3's fixture for test_recipe_starts_each_draft_layer_from_its_paired_target_layer gives the mHC mixes no values of their own. base and scale of attn_hc and ffn_hc still start equal on both sides (8 of the 38 compared tensors), and a copy that skips only these passes every test. With paired.attn_hc, and paired.ffn_hc, added to the tuple of modules in that loop, the test passes on this head and fails for both (torch 2.14 and 2.15).
  • The per-tensor BF16 bound that round 3 proposed has an absolute term of 1e-6. In this fixture the FP32 reference gradient of two tensors outside the exemption is smaller (layers.0.ffn_hc.scale 3.5e-7, layers.1.attn_hc.scale 3.3e-7), so a zeroed gradient of either still passes (planted for the first).
  • Round 3 named one recipe_cfg parameter without an annotation. The PR's new signatures have five more gaps; see below.

Smaller things, no inline comment

Not run: the real target; the example's own layout (64 ranks, 32K rows, accumulation 4); a save on more than six GPU ranks or more than 24 CPU ranks; the two hours of the example's distributed timeout; target-regenerated data; Eq. (10), which is not implemented; CI's -n 2 --dist loadfile invocation.

…rafter

Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>
…ards

Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>
Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>

@HuiyingLi HuiyingLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bot review of e73bd22e2d5e (round 5). The PR is a draft; this round was asked for by a maintainer. Earlier rounds: review 6094029351, review 6098447847, review 6100966043 and review 6103215820.

Round 4's three comments are answered, and nothing has to change before merge. The three new commits merge main, remove the rank-count check, and change four tests. Two small things are left, neither of them blocking: one set-up line of the removed check and three return types that round 4's count missed (both under "Smaller things"). One statement of rounds 3 and 4 about a test bound is corrected further down; nothing is asked there. This review is a comment: it does not lift the three earlier reviews that requested changes (rounds 1, 2 and 4). Nothing else from those three reviews is still asked.

Round 4 On this head
1 Has to change: merged with main (#4058), the rank-count check refuses rank counts that save (comment) Fixed as asked, but for one set-up line in a test (first of the smaller things). main is merged: the merge commit has the tree of an automatic merge of the round-4 head and main, and the head contains all of main. check_fsdp_expert_split, its call and the lines of train_dfly2.py that served it, the two tests with _ShardedExperts, the guide's note, the example header's sentence and the description's line are gone. No text in the tree states the old rank rule. The runs are in the next table.
2 Small: the FP32 router-bias fix has no test (comment) Fixed, with a test of the author's own. test_warm_start_reads_the_released_layout now gives layer 0 a router bias that BF16 cannot hold, sends the source draft and the loading draft through cast_model_to_dtype, and asserts that the loaded buffer and the exported tensor are bit-equal to the FP32 value. With the entry taken out of _keep_in_fp32_modules_strict again it fails (torch.bfloat16 != torch.float32), on torch 2.14 and on torch 2.15.
3 Small: no test runs the chunk loop a second time (comment) Fixed. test_objective_matches_the_written_out_formula now has 136 slots, so the corpus cross entropy and the distance terms each run a chunk of 128 and a chunk of 8. It fails with the first chunk's targets used for every chunk (0.58689 against 0.58560), with the chunks concatenated in reverse order (0.60344), and with @torch.no_grad() removed (on its gradient comparison), on torch 2.14 and on torch 2.15.

Saving at the rank counts the check refused

Runs with a small V4.1 target and the unmodified 128-expert draft, each with a step checkpoint and the final consolidated export. The V4.1 target load needs CUDA, so CPU-rank runs go through the recipe's setup() and loop with only the target load replaced.

Run Result on this head
6, 12 and 24 CPU ranks Not refused. Each run trains, writes the step checkpoint and the final export on every rank, and exits 0. 1,242 of 1,242 exported tensors are bit-equal to the live draft. A warm start at lr 0 from the export repeats the validation in 8 of 8 fields. Step records, validation and the live draft before both saves are bit-equal to round 4's runs of the same removal.
Controls at 12 CPU ranks The round-4 head and the merge commit's tree are refused on 12 of 12 ranks. This head with moe/state_dict_utils.py as it was before #4058: the first save raises on ranks 8 to 11 (rank 8: Expected local tensor first dimension to be 10 (experts 88:98), got 11).
Resume at 12 CPU ranks From the step checkpoint, through checkpoint.restore_from: it loads on 12 of 12 ranks, and the restored draft is bit-equal to the saved one in 96 of 96 tensors.
Six H100 ranks (BF16, NCCL), the unmodified recipe CLI Trains, writes the step checkpoint and the final export, exits 0; the export holds all 1,242 tensors. In a second run with a read-only observer, both saves finish on 6 of 6 ranks and 1,242 of 1,242 exported tensors are bit-equal to the live draft. The same command on the merge commit's tree is refused on 6 of 6 ranks.

What else the push changes

  • Source: against the merge commit's tree, _build_model_owned_draft is the only function with other compiled code, and check_fsdp_expert_split is gone. Five functions differ in an annotation only, and dfly2.py lost a comment. These are the five annotations and the orphan comment that round 4 listed as smaller things; all six are done as proposed.
  • The two corrections that round 4 made to round 3's test suggestions were taken up. With paired.attn_hc and paired.ffn_hc in the fixture, none of the 38 compared tensors is equal on both sides before the copy (8 were), and a copy that skips base or scale of the mixes fails. With the bound's absolute term at 1e-8, a zeroed gradient of layers.0.ffn_hc.scale or of layers.1.attn_hc.scale fails. The two-rank gradient test passes at its committed inputs, with the same values in every run on torch 2.14 and on torch 2.15. The bound fits these inputs only: see the correction to rounds 3 and 4 below.

The draft is the draft of round 4

What Result on this head
Forward (CPU, torch 2.14, FP32, released weights, 2,048 rows) all 31 recorded stages and the logits are bit-equal to the round-4 head's
Start from the target the draft after initialize_from_target is bit-equal to the round-4 head's in every tensor (72 of 72 with a small target; 96 of 96 at released size, with a released-size stand-in for the target layers)
Loss loss.py is byte-identical; 57 of 57 cases are bit-equal in every term and in the logits gradient
Parity with the authors' trainer 2.9e-6 relative L2 on both heads, the same key set for 288 of 288 queries in each layer
Release round trip (the recipe's BF16 cast, then the released weights) all 2,392 stored tensors are read, and the 1,240 tensors they decode to all equal an independent decode: 88 bit for bit and 1,152 as exact FP4 decodes
The shared DSpark recipe train_dspark.py differs from the round-4 head in one annotation. Seeded DSpark runs on main and on this head are bit-identical in 9 of 9 pairings (2,160 step metrics, 108 gradient norms, 574 saved tensors): Qwen/Qwen3-0.6B on one GPU, on two ranks with FSDP2 and on two ranks with DDP

Tests and gates. The PR's four test files: 136 passed on torch 2.14 and 136 on torch 2.15 (CPU). The two tests of the check are gone and no other test id changed. The suites of the three directories with the PR's tests and of tests/unit_tests/loss pass on this head (678, 1,403, 370 and 502 tests passed; torch 2.14, CPU), and so does tests/unit_tests/moe (1,082 passed). In CI's lint environment, ruff, tools/check_types.py, the import contracts, bandit, the copyright check, tools/recipes/check_recipes.py and tools/docs/check_docs.py pass. On this head only the DCO check and the PR-title check have run, both green. The secrets, recipe-config and type-coverage workflows wait for a maintainer's approval, and no run of the test and lint workflow exists for this head. Nothing was triggered.

Smaller things, no inline comment

Correction to rounds 3 and 4: the per-tensor BF16 bound. Nothing is asked here. Round 3 proposed the bound at test_dfly2.py#L436-L438 with an absolute term of 1e-6. Round 4 said that this term lets a zeroed gradient of two small tensors pass. This push sets it to 1e-8, and both zeroed gradients fail now. Both rounds checked the bound at the test's own inputs only. At these inputs it holds, also when the CPU kernel path is switched on a node whose native path is AVX512: with PyTorch's own kernels or MKL restricted to AVX2 (ATEN_CPU_CAPABILITY=avx2, MKL_ENABLE_INSTRUCTIONS=AVX2), with PyTorch's kernels without AVX (ATEN_CPU_CAPABILITY=default), or with MKL in its compatibility mode (MKL_CBWR=COMPATIBLE), the recorded values change and the tensor closest to its bound stays at 66 % of it (torch 2.14 and torch 2.15). With only the seed of _fsdp_draft_features changed and the code under test untouched, the BF16 case fails at 11 of 16 other seeds, on torch 2.14 and on torch 2.15 alike; with 1e-6 it fails at 2 of 16. The BF16 error of the small tensors does not shrink with their reference: for layers.0.ffn_hc.fn it stays between 4.8e-7 and 8.6e-7 over the test's seed and seeds 1 to 8, while the FP32 reference goes from 1.1e-6 to 2.3e-5. So the bound describes these inputs, and a later change to the fixture can fail the test without a defect. The committed test is deterministic and passes.

Unchanged since round 4, not asked

  • Eq. (10) is not implemented; the description and the guide say so.
  • 23 of round 1's 26 single-line defects fail a test, as on the round-4 head. Still passing every test: position ids shifted by one, an exclusive prefix read, a causal block.
  • Warm start from <step>/model, and the two-rank export above one 5 GiB shard that loses tensors (the checkpointer on main): not run again.

Not run: the real target (the two commits after the merge change no line of the draft's forward, start, warm start or loss; the forward, the start and the loss give the round-4 head's bits on this head, and the release round trip equals the independent decode as it did there; the save and the resume, where main changed the expert split, are run above with the draft's 128 routed experts); the example's own layout (64 ranks, 32K rows, accumulation 4); a save on more than six GPU ranks or more than 24 CPU ranks; CPUs of another vendor; CI's -n 2 --dist loadfile invocation.

@khazic

khazic commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

LGTM, looks like all the review comments have been addressed. Why not undraft it so we can get CI running and move forward? @kashif

Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>
Signed-off-by: Kashif Rasul <kashif.rasul@gmail.com>

@HuiyingLi HuiyingLi left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bot review of 320033d167b6 (round 6). The PR is a draft; this round was asked for by a maintainer. Earlier rounds: review 6094029351, review 6098447847, review 6100966043, review 6103215820 and review 6104742548.

Round 5's smaller things are done. The second commit moves repeated test code into helpers, and one of the new helpers breaks a sentence of CODING_GUIDELINES.md (inline comment 2). Under this repository's written rules it blocks, although the code under test behaves the same. (Edited on 2026-12-01: inline comment 1, a test helper without a return type, is withdrawn, because type annotations in test files are not checked in review.) Comment 3 is not blocking: the same commit drops two assertions that no other test makes.

Round 5 On this head
recipe.dist_env = SimpleNamespace(world_size=1) at test_dfly2.py#L735 only set up the removed check Removed. The rest of that test's set-up has the same effect as before: the same seven modules of each paired layer get new values, in the same order, through _randomize.
-> None on DFly2TrainerModule.__init__ (core.py) Done.
-> None on DFly2TargetModel.__init__ (target.py) Done.
A return type on the nested _capture (dfly2_target.py) Done: Callable[..., None]. _capture returns _hook, whose own signature is fully annotated and which returns nothing, so the forward hook leaves the attention output as it is.

What ran on this head

  • Source: with annotations, docstrings and imports set aside, the syntax trees of dfly2_target.py, core.py and target.py equal those of e73bd22e2d5e; the only other change adds Callable to an import. Ruff's annotation rules find 3 missing return types in the three files at e73bd22e2d5e and none here. In CI's lint environment tools/check_annotation_policy.py prints the same single line at both heads ("Annotation policy: checked 1067 files, 129 object annotations") and tools/check_types.py ends in "All checks passed!" at both; the PR's files are not among ty's opt-in targets. Ruff's lint and format checks pass on the six changed files.
  • Tests: the PR's four test files collect the same 136 test ids as at e73bd22e2d5e (none removed, renamed or added), and all 136 pass on torch 2.14 and on torch 2.15 (CPU; the three changed files are marked CPU-only). The helpers build the same draft heads, parameter values, process groups and FSDP units as the lines they replace. Two tests now take their random inputs from _draft_features (a seeded generator instead of the global one; in test_fresh_draft_starts_as_its_backbone_and_trains_every_head the key lists are 4 wide instead of 5), and both still check what they checked before. Round 5's regression tests still catch their defects: with e_score_correction_bias taken out of _keep_in_fp32_modules_strict, test_warm_start_reads_the_released_layout fails; with the first chunk's targets used for every chunk, test_objective_matches_the_written_out_formula fails.
  • main has 16 commits since this PR's base; none of them changes a file of the PR. The merge is clean, and the four test files pass on it (136 of 136, torch 2.14).
  • CI: on this head only the DCO check and the PR-title check have run, both green; the type-coverage, recipe-config, secrets and PR-title workflows wait for a maintainer's approval. Nothing was triggered.

@HuiyingLi
HuiyingLi marked this pull request as ready for review December 2, 2026 08:46
@HuiyingLi
HuiyingLi requested a review from akoumpa as a code owner December 2, 2026 08:46

@HuiyingLi HuiyingLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion: Approve

Bot suggestion for f53116e08d5e (round 7), after review 6135189608 on 320033d167b6. Since then the PR has two commits that change only test_dfly2.py and test_train_dfly2.py, and a merge of main. Nothing blocks.

Round 6 On this head
Comment 2 (blocking): _assert_copied read both modules with getattr(..., name) Answered. The helper takes the module pairs; no getattr, hasattr, attrgetter, __dict__ or name-filtered module walk is left in it or in the lines the commit changed. A syntax-tree comparison with 320033d167b6 gives the same 17 (copy, source) pairs in the same order. With q_norm, attn_hc, shared_experts or the sinks left un-copied by initialize_from_target, or q_norm or wq_b left un-copied by initialize_attentive_correction, the test that covers it fails (6 of 6 defects); without a defect both tests pass.
Comment 3 (not blocking): two assertions dropped from test_confidence_head_is_off_and_detached_by_default Answered. Both are back as they were. With DSpark's default weight changed from 1.0 to 0.0, or with _resolve_confidence_head_alpha returning the recipe's default whatever recipe_args sets, this test now fails (on 320033d167b6 it passed with either defect).

The second commit sets TORCH_COMPILE_DISABLE=0 before test_fsdp_gradient_matches_the_single_process_global_batch spawns its two workers. Other unit-test modules set it to 1 when they are imported, the workers inherit it, and the MoE activation compiled with fullgraph=True (_swiglu_clamped_deepep_compiled) then raises "found no compiled frames". That is how L0_Unit_Tests_CPU failed on dc6e5432ffe7 (2 failed, 23,200 passed). Reproduced here with test_compile_utils.py collected in the same run: without the line both parametrizations fail with that error in a worker; with it both pass; the test run alone passes either way. The workers now run the activation compiled, as training does by default and as the test did when run alone, so it checks what it checked before (test_dspark_fsdp2.py on main does the same).

Merge of main. The head's tree equals a fresh merge of main 023d89298f72 into ddfed8b803f4 (no conflicts), and the PR's 20 other files have the same patches against the new merge base as 320033d167b6 had against its own. Of the 40 commits main gained since that base, one changes a file of the PR (#5037 adds 7 lines to docs/fern/versions/nightly.yml, apart from the PR's lines); #4948, #4949, #4972, #5017 and #5038 change moe/ (the draft builds MoE layers), #4973 changes DSpark's V4.1 draft next to the PR's files, #5002 pins Transformers 5.22.2, and #5046 adds tests/conftest.py with a start-up hook for spawned processes. The tests below ran on the merged head.

What ran on this head (Transformers 5.22.2, torch 2.14)

  • The PR's four test files collect the same 136 test ids as on 320033d167b6; CPU form: 136 passed; with one H100 visible and no --cpu: 136 passed.
  • In CI's lint environment (ruff 0.12.12, ty 0.0.91, import-linter 2.5.2, as in uv.lock): ruff format --check and ruff check (no cache) pass on the two changed files and on the whole repository; tools/check_types.py ends "All checks passed!" and names none of the PR's files; tools/check_annotation_policy.py prints "checked 1083 files, 134 object annotations" with nothing on the PR's files; lint-imports keeps 5 of 5 contracts; the tools/lint_*.py steps pass, lint_test_rendezvous.py among them.
  • CI on this head (run through #5052): all 85 check runs have finished, 75 passed and 10 were skipped, none failed; L0_Unit_Tests_CPU (red on dc6e5432ffe7), both GPU unit-test shards, L0_Kernel_Parity_GPU and the unit-test coverage job are among those that passed. The workflows of the fork's own branch still wait for a maintainer's approval; the same workflows passed on #5052.

Not run here: torch 2.15, the real V4.1 target, recipe runs and multi-GPU runs (the production code is unchanged since round 6, whose evidence stands).

@HuiyingLi

Copy link
Copy Markdown
Contributor

/ok to test 17fc88c

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

This branch is waiting to be deployed

1 inactive and 1 waiting deployments
test — 17fc88cc Waiting Dec 2, 2026 by copy-pr-bot[bot] via cicd-wait-in-queue #13678
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants