Skip to content

feat(spec-decode): pipeline parallelism for draft co-training via a one-sided tap channel (Megatron) - #4060

Draft
MarkXCloud wants to merge 7 commits into
NVIDIA-NeMo:mainfrom
MarkXCloud:spec-pp
Draft

MarkXCloud wants to merge 7 commits into
NVIDIA-NeMo:mainfrom
MarkXCloud:spec-pp

Conversation

@MarkXCloud

@MarkXCloud MarkXCloud commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

Draft co-training with megatron_cfg.pipeline_model_parallel_size > 1 (Megatron policy backend). The draft lives whole on the last pipeline stage, but what it consumes — the aux hidden states ("taps") of a few policy layers and the pass-1 input embeddings — is produced on earlier stages. This PR adds a one-sided tap channel that delivers them per microbatch without touching the pipeline schedule.

This is the PP half of the training-system work in our paper (https://arxiv.org/abs/2609.07108); the CP/packing half is #4059.

Why not send/recv inside the schedule. Taps are a detached data flow — no gradient crosses stages — but they are produced inside forwards that the 1F1B schedule is already driving with its own P2P. Blocking send/recv in forward hooks shares communicators and ordering with Megatron's pipeline P2P and can interleave with (or deadlock against) it, and the previous per-id gather assumed every stage could pair up per tensor. Multi-node PP additionally makes every stage pair cross-host (pp is Megatron's outermost rank dimension), so the transport has to work over the wire too.

How this PR does it.

  • Rings on the draft stage, one-sided writes from the sources. At setup the last stage allocates one ring of landing slots per source stage — ring_slots × slot_rows × width, where width covers that stage's tap layers (plus the embeddings on the first stage); the reservation is exact and static. Intra-node, the ring is exported over CUDA IPC and each source's capture hook writes its microbatch's tap straight into the next slot on a side stream, then stamps a header the consumer polls: no recv, no pairing, no message ordering. Cross-node, the same put/get runs over a dedicated NCCL communicator per PP column (GPUDirect RDMA on the wire); it never shares a communicator with the schedule's P2P and both ends post ops in the same monotone microbatch order, so it cannot deadlock the schedule either.
  • Rendezvous by position, checked by stamp. With a non-interleaved schedule every stage forwards microbatches in the same order, so the writer's n-th put and the draft stage's n-th get are the same microbatch; the header carries the writer's sequence number, and a mismatch raises instead of silently training on another microbatch's taps. Sources never block on the draft stage; the draft stage waits only when a tap has not landed yet (reported as draft_tap_wait_s, max over the PP group). A source running more than ring_slots microbatches ahead (slot overrun) and interleaved (virtual) PP are rejected rather than handled.
  • Mask row for block drafters. DFlash/DSpark read the policy's live mask-token embedding, which lives on the first stage; begin_pass broadcasts that row over the PP group once per step, outside the schedule.
  • PP correctness fixes uncovered along the way. The optimizer all-reduces a per-group flag across PP, so the draft grad-norm group must be registered on every rank, not only the owner stage (otherwise the collective order desyncs and optimizer.step deadlocks; regression test included). The block draft's TransformerConfig gets pipeline_model_parallel_size=1 so TransformerBlock does not split its few layers across stages, and the PP == 1 guard is dropped. Refit broadcasts the exported draft weights across PP so every rank yields the same draft.* key set to its paired vLLM engine.

Limits: interleaved (virtual) pipeline schedules are rejected (the channel matches microbatches by per-stage forward order); the async GRPO loop is not wired for the new metric yet.

Issues

Part of #3698 (5/5). Stacked on #4059 (CP/packing) → #3713 → #3712 → #3699 — until those merge, this diff includes their commits; review only the last commit (feat(spec-decode): pipeline parallelism for draft co-training via a one-sided tap channel).

Usage

policy:
  megatron_cfg:
    pipeline_model_parallel_size: 2   # draft on the last stage; taps arrive over the channel
    batch_p2p_sync: false             # drop Megatron-Core's device-wide sync after each pipeline p2p (see below)
  draft:
    enabled: true
    speculator_type: eagle3           # or dflash / dspark

The per-step rendezvous wait shows up as draft_tap_wait_s (max over the PP group, then over replicas).

batch_p2p_sync: false (new megatron_cfg key; omit = Megatron-Core's default true). Megatron-Core ends every batched pipeline p2p with torch.cuda.synchronize(), a guard for an old PyTorch batch_isend_irecv race. The sync is device-wide, so on a tap source stage it also waits for the tap send parked on the channel's side stream, which cannot complete before the draft stage posts the matching receive for that microbatch: the source stages get pinned to the last stage's schedule with no 1F1B slack (+170 ms/microbatch on every stage on a Qwen3.5-35B-A3B TP2/PP4 probe; step time 1.41x -> 1.17x of the no-draft baseline with the sync off, and on Qwen3.5-122B TP4/PP4/CP2 the update overhead went 1.60x -> 1.00x together with a 13/13/13/9 layer split). Ordering safety stays with the stream-level Work.wait() Megatron keeps either way. The principled fix, receiver-side pre-posted receives in the channel, is future work.

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.

Tests: channel round-trip / uneven-stage / slot-overrun / mask-row broadcast (2–4 GPUs, IPC and NCCL transports), capture-vs-local-semantics parity under PP2/PP4, and the grad-norm-group regression test. This is the code path behind the paper's PP experiments (see the paper for the full set of configurations), ported onto the stacked series.

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]>
Adds the DSpark block drafter (policy.draft.speculator_type=dspark),
the semi-autoregressive DFlash variant matching vLLM >= 0.26 serving:

- DSparkDraftModel subclasses DFlashDraftModel: W = gamma (the anchor
  slot predicts too), plus the official heads — a low-rank Markov
  transition bias teacher-forced with the ground-truth previous token,
  and a confidence head predicting per-slot TV acceptance.
- DSparkBlockLossFn: the official three-term loss (hard-label CE + TV
  distillation + confidence BCE) with configurable alphas
  (defaults 0.1 / 0.9 / 1.0 = official dspark_qwen3_8b), backed by a
  sequence-chunked TP-vocab CE+TV autograd kernel that keeps fp32
  buffers chunk-sized. The wrapper selects it from the confidence
  tensor the forward stashed (data_dict["draft_confidence_pred"]) —
  still one config selector (speculator_type).
- HF weight mapping for the extra heads; refit streams them with the
  draft.* weights.

Signed-off-by: Zili Wang <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Sep 9, 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.

… training

Lifts the packing/CP restrictions on draft co-training: the EAGLE-3 TTT
and DFlash/DSpark paths now run under sequence packing (THD varlen) and
context_parallel_size > 1 (zigzag ring layout). Draft losses thread the
CP group (teacher roll / coordinate-gather under CP; CP-summed metric
reduction), and the policy-level guard changes from rejecting CP
outright to requiring packing when CP > 1 (the trunk ring needs the THD
zigzag layout).

On top of the stacked eagle3/dflash/dspark PRs this also:
- folds DraftTTTCrossEntropyLossFn into DraftCrossEntropyLossFn (one
  class for single/multi-pass, packed/unpacked, CP), so DraftLossWrapper
  picks the loss purely from the tensors the train loop stashed
  (draft_block_logits / draft_confidence_pred) and every draft loss
  returns (loss, metrics);
- replaces the packed draft shift (per-segment id shift + re-embed) with
  roll_packed_left_cp on the captured embeddings, which drops the
  packing+PP guard that existed only because of the re-embed;
- lets sliding-window block-draft layers ride CP: the layer all-gathers
  its trunk K/V shard back to global order for its single windowed call
  (backward re-gathers and returns trunk grads home by reduce-scatter),
  replacing the sliding-layers-reject-CP guard; covered by 2/4-GPU tests;
- hides the draft-only stashed keys (block logits, anchors, packed coords,
  student logits) from the inner sequence-packing wrapper, whose
  per-sequence slicing assumes a leading sequence dim;
- keeps the reviewed fix package (flash-attn/dropout/mask guards,
  speculator_type selector, seq_chunk_size ctor param, block-aware
  resolve_draft_aux_layer_ids) on the CP versions of the files.
@MarkXCloud
MarkXCloud force-pushed the spec-pp branch 2 times, most recently from 553679a to fe71ddc Compare September 9, 2026 04:40
LossPostProcessor divided the combined policy+draft loss by cp_size. That
division compensates the policy path's differentiable CP logprob
all-gather (every rank evaluates the full-sequence policy loss, so each
local logit receives cp_size gradient copies). The draft losses are
rank-local numerators over a global denominator and reach the global
gradient through the dp_cp grad all-reduce alone, so the shared division
shrank every draft gradient by cp_size under CP > 1 while the draft
metrics (explicitly CP-reduced) stayed correct.

Apply the division to the policy loss before wrapping it with the draft
loss, and pin the split with a cp_size=2 unit test through the full
LossPostProcessor chain.

Reported by alexq (CPU reproduction of the wrapper/schedule scaling chain).

Signed-off-by: Zili Wang <[email protected]>
…ne-sided tap channel

Draft co-training with pipeline_model_parallel_size > 1. The draft lives
whole on the last stage while the aux hidden states (taps) and the pass-1
input embeddings it consumes are produced on earlier stages. TapChannel
(hidden_capture.py) replaces the per-id blocking send/recv gather: source
stages write their taps one-sided into a per-column ring on the draft
stage (CUDA IPC intra-node, a dedicated NCCL side channel across nodes),
stamped by microbatch so the draft stage's forward_step(i) rendezvous
with exactly microbatch i's taps; begin_pass broadcasts the live
mask-token embedding row from the first stage for block drafts. The
per-step rendezvous wait is exported as draft_tap_wait_s (max over the PP
group, then over replicas).

Also needed for PP > 1:
- register the 'draft' grad-norm group on every rank: the optimizer
  all-reduces a per-group flag across PP, so a stage-local tuple desyncs
  the collective order and deadlocks optimizer.step;
- build the block draft's TransformerConfig with
  pipeline_model_parallel_size=1 (TransformerBlock would otherwise split
  its few layers across stages) and drop the PP == 1 guard;
- broadcast the exported draft weights across PP in the refit iterator so
  every rank yields the same draft.* key set to its paired vLLM engine.

Interleaved (virtual) pipeline schedules are rejected: the channel
matches microbatches by per-stage forward order. The async GRPO loop is
not wired for the new metric yet.

Signed-off-by: Zili Wang <[email protected]>
…-training

Megatron-Core ends every batched pipeline p2p (P2PCommunicator._communicate)
with torch.cuda.synchronize(), a guard for an old PyTorch batch_isend_irecv
race. The sync is device-wide, so on a tap source stage it also waits for the
tap send TapChannel parked on its side stream, and that send cannot complete
before the draft stage posts the matching receive inside TapChannel.get() for
the same microbatch. The source stages are thereby pinned to the last stage's
schedule with no 1F1B slack: +170 ms per microbatch on every stage on a
Qwen3.5-35B-A3B TP2/PP4 probe (step time 1.41x -> 1.17x of the no-draft
baseline with the sync off), and on Qwen3.5-122B TP4/PP4/CP2 the update
overhead went from 1.60x to 1.00x together with a 13/13/13/9 layer split.

Pass the Megatron-Core field through as megatron_cfg.batch_p2p_sync (omit to
keep the default True). Ordering safety stays with the stream-level
Work.wait() that _communicate keeps either way. The principled fix,
receiver-side pre-posted receives in TapChannel, is future work.

Signed-off-by: Zili Wang <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>

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