Skip to content

feat(spec-decode): DFlash block-draft co-training (Megatron) - #3712

Draft
MarkXCloud wants to merge 2 commits into
NVIDIA-NeMo:mainfrom
MarkXCloud:spec-dflash
Draft

MarkXCloud wants to merge 2 commits into
NVIDIA-NeMo:mainfrom
MarkXCloud:spec-dflash

Conversation

@MarkXCloud

@MarkXCloud MarkXCloud commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

Adds the DFlash block drafter (policy.draft.speculator_type: dflash) co-trained with the policy during GRPO (Megatron policy backend), matching vLLM ≥ 0.25 serving.

Issues

Part of #3698 (2/5). Stacked on #3699 (EAGLE-3 TTT); #3713 (DSpark) → #4059 (sequence packing + CP) → #4060 (PP) stack on top — until that merges, this diff includes its commits; review only the last commit (feat(spec-decode): DFlash block-draft co-training).

Usage

policy:
  draft:
    enabled: true
    speculator_type: "dflash"
    model_name: <dflash ckpt or null>
    gamma: 8                # speculated tokens per block
    anchors_per_seq: 64
    mask_token_id: 151669   # reserved, unused-in-data token id
    loss_weighting: "exp"   # DFlash-paper per-slot decay; null = uniform
    loss_weight: 0.1

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 run the unit tests and functional tests locally? Visit our Testing Guide for how to run tests
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs.

Additional Information

Draft for visibility — actively being worked on. Main pieces:

  • DFlashDraftModel: anchor + mask-token blocks, bidirectional in-block attention, trunk truncated at the anchor (two-part varlen flash kernel, exact joint-LSE merge); policy taps injected as per-layer trunk K/V. Official DFlash contract: the draft owns no lm_head and no mask embedding — logits project through the policy's live (detached) head, mask slots embed via the frozen embed_tokens[mask_token_id] row, exactly matching vLLM serving where the drafter shares the target's modules.
  • Anchor sampling on the worker (generation-only segments by default), transported through dynamic batching as a [B, S] count map.
  • BlockDraftLossFn: chunked vocab-parallel soft CE over block slots, prefix-contiguous slot validity across multi-turn holes, per-slot global counts, named slot-weighting schemes (uniform / DFlash-paper exp).
  • HF weight interop with the vLLM DFlash checkpoint naming (refit streams draft.*; lm_head/embed/mask rows skipped by contract).

Evaluation verification

  • Model: Qwen3-8B
  • Benchmark: AIME24
  • Orange line: dflash pretrained by z-lab/Qwen3-8B-DFlash-b16
  • Blue line: no speculative decoding
image

Perf:
image

@copy-pr-bot

copy-pr-bot Bot commented Aug 19, 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.

Extends the single-pass EAGLE-3 draft co-training path to multi-pass
TTT (policy.draft.ttt_steps > 1):

- EagleModel.forward_ttt: sequential draft passes with the two-part
  trunk+branch flash attention (exact joint-LSE merge) folded into
  eagle.py, inference-aligned per-pass RoPE offsets, non-detached
  hidden-state chain between passes.
- ChunkedDistributedCrossEntropy: sequence-chunked vocab-parallel
  soft-CE whose fp32 buffers exist per chunk only (multi-pass logits
  stack up before the shared backward); chunk size configurable via
  policy.draft.loss_seq_chunk_size.
- DraftTTTCrossEntropyLossFn: the multi-pass sibling of the single-pass
  DraftCrossEntropyLossFn (which stays the ttt_steps == 1 loss,
  including the packed layout). Per-pass slicing convention (pass d
  predicts x_{i+d+1}), per-pass alpha weights, per-pass global
  valid-count normalization threaded from the worker (DP-only
  all-reduce).
- Draft-only optimizer param group (policy.draft.{lr,min_lr,
  weight_decay}); the group's resume identity rides mcore's
  param_group_identifier_keys (max_lr/min_lr/start_wd/end_wd), so the
  override must differ from the policy group in at least one of those
  fields.
- Aux-layer ids resolved rank-independently
  (resolve_draft_aux_layer_ids) and threaded into the hidden-state
  capture, so PP stages cannot disagree about the P2P schedule.
- vLLM: un-share the drafter lm_head before loading a trained head
  (refit would silently overwrite the target's head through vLLM's
  share-on-identical-weights alias), preserving vLLM's weight-loader
  attrs on the private copy; the drafter lookup covers the V1 `drafter`
  and V2 `speculator` runner attributes; draft refit weights with no
  reachable drafter raise on the owning PP rank and return quietly on
  earlier ranks.

Signed-off-by: Zili Wang <[email protected]>
Adds the DFlash block drafter (policy.draft.speculator_type=dflash)
co-trained with the policy during GRPO, matching vLLM >= 0.25 serving:

- DFlashDraftModel: anchor + mask-token blocks, bidirectional in-block
  attention, trunk truncated at the anchor via a two-part varlen flash
  kernel with exact joint-LSE merge; taps injected as per-layer trunk
  K/V. Official DFlash contract: the draft owns no lm_head and no mask
  embedding — logits project through the policy's LIVE (detached) head
  and mask slots embed via the policy's frozen embed_tokens row, so
  serving (which shares the target's modules) matches training.
- Anchor sampling on the worker (generation-only segments by default),
  transported through dynamic batching as a [B, S] count map.
- BlockDraftLossFn: chunked vocab-parallel soft CE over block slots
  with prefix-contiguous slot validity, per-slot global counts, and
  named slot-weighting schemes (uniform / DFlash-paper exp decay). The
  loss dispatch keys on the block logits the forward stashed
  (data_dict["draft_block_logits"]) — one config selector
  (speculator_type), no second method knob.
- HF weight mapping to/from the vLLM DFlash checkpoint naming (refit
  streams draft.* weights; lm_head/embed/mask rows skipped by contract).

Signed-off-by: Zili Wang <[email protected]>
yuekaizhang added a commit to yuekaizhang/RL that referenced this pull request Sep 9, 2026
- vllm_worker.py/vllm_backend.py: gate the draft module-sharing
  disable and the strict-cotraining/full-manifest-validation paths on
  the actual full-vs-partial stream signal (_draft_full_refit config
  flag / embed_tokens key presence via the renamed
  _is_full_draft_stream), not on the dspark/dflash method name --
  method names alone don't imply a DTensor-v2 full stream, so a future
  headless Megatron block-drafter using the same method name would
  otherwise hit a spurious "missing draft keys" refit failure.
- integration.py: shift input_ids/teacher_logits (and
  next_token_position_mask) left by one in Eagle3Runtime.compute_loss
  so the TTT forward trains h[t] + token[t+1] -> teacher_logits[t+1],
  matching vLLM's eagle proposer contract (previously trained the
  easier, misaligned h[t] + token[t] -> teacher_logits[t] task, which
  would look healthy in the loss curve while degrading refit
  acceptance).
- algorithms/utils.py: move finalize_draft_ratio_metrics out of the
  nemo_automodel-gated draft/integration.py into this dependency-free
  module and call it directly (no more try/except ImportError) --
  driver processes essentially never have nemo_automodel installed,
  so this was silently no-op'ing and leaving raw *_num/*_den keys in
  wandb instead of the finalized ratios. Also anchor the regex to
  draft_* so it can't rewrite unrelated *_num/*_den metric pairs.
- dtensor_policy_worker_v2.py: drop the dead stream_weights_via_http
  method (its stream_weights_via_http_impl callee was removed from
  utils.py in NVIDIA-NeMo#3612; this would ImportError the moment anything called
  it).
- policy/__init__.py, lm_policy.py, automodel/setup.py,
  dtensor_policy_worker_v2.py: drop DEFAULT_DRAFT_ALGO and read
  policy.draft.algo as a required key once draft is known to be
  enabled, instead of the forbidden cfg.get(key, MODULE_CONSTANT)
  pattern at 3 call sites (config-conventions) -- the exemplar YAML
  already supplies the default for every shipped recipe. Added the
  missing algo field to ppo_math_1B_megatron_single_controller.yaml's
  (disabled) draft block for consistency.
- automodel/setup.py, dtensor_policy_worker_v2.py: hoist the
  Eagle3DraftOptions/DSparkDraftOptions imports to module top (both
  files already import nemo_rl.models.policy there; no circular-import
  or heavy-dep reason to defer them).
- eagle3_llama.py: drop the unused (production-dead, only
  test-exercised) _kl_div_per_position checkpointed-chunking wrapper
  and correct the header/docstring claim -- the TTT loop's actual
  per-chunk compute_logits+KL loop caps the transient peak but, since
  no chunk is checkpointed, does not reduce the memory retained for
  backward across the step.
- dtensor_policy_worker_v2.py: fix a backwards comment about which
  path (sequence packing, not dynamic batching) can make microbatch
  counts differ across DP ranks.
- Test coverage: new parametrized table test for
  _draft_module_sharing_disable_required (all 3 cotrained methods x
  full/partial stream x load_format), rewrote the KL chunking test
  against the actual production chunking pattern instead of the
  deleted wrapper, and moved the ratio-metrics tests to
  tests/unit/algorithms/ (no longer nemo_automodel-gated).

Not addressed here: the lm_policy.py rebase conflict (main replaced
the blanket sequence-packing guard with Megatron-scoped guards in

Signed-off-by: Yuekai Zhang <[email protected]>
NVIDIA-NeMo#3463) and the cross-PR config-schema/nightly-budget discussion with
NVIDIA-NeMo#3712/NVIDIA-NeMo#3713, both left for separate follow-up.

This branch has not been deployed

No deployments
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.

1 participant