Skip to content

feat(draft): support packed context-parallel co-training - #3757

Open
seonjinn wants to merge 39 commits into
NVIDIA-NeMo:mainfrom
seonjinn:seonjinn/draft-cotrain-cp-v1-linear
Open

seonjinn wants to merge 39 commits into
NVIDIA-NeMo:mainfrom
seonjinn:seonjinn/draft-cotrain-cp-v1-linear

Conversation

@seonjinn

@seonjinn seonjinn commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

This PR adds online co-training for DFlash and DSpark drafts with packed context parallelism (CP).

  • One packed layout maps logical, global, CP-local, and target sequence-parallel (SP) positions.
  • Draft attention and draft loss stay inside sample boundaries. This includes CP ranks that own no tokens of a sample.
  • Autograd-safe tensor-parallel (TP) collectives rebuild the target SP values that the draft needs.
  • Draft gradients and draft metrics use one normalizer across data parallel (DP) x CP. No rank gathers full CP tensors.
  • Checkpoint, export, packed weight transfer, and online DFlash/DSpark lifecycle paths support the draft. ModelOpt real-quant refit rejects a draft before any weight moves.
  • Qwen attention with hidden_size != num_heads * head_dim works, including TP2 export and refit (Qwen3-30B-A3B).

Supported contract

Item Supported Behavior outside the contract
Target training TP2 (tested; other TP sizes must divide the draft dimensions), CP1/CP2/CP4, PP1 Setup fails before training.
CP > 1 Needs sequence packing. Packed target SP is supported. Setup fails before training.
CP > 1 entrypoint Synchronous GRPO with the data plane (split API) setup() fails. Async GRPO and data plane off are rejected.
Generation CP1, PP1 Setup fails. A Megatron generation backend with no override inherits the training PP and CP, and the same check applies.
Draft body Internal SP off Setup fails.
DSpark vocabulary Must match the target Setup fails.
Packed transport Ordered framing. Synchronous Python failures drain to the terminal frame. CUDA stream, allocation, kernel, OOM, and NCCL failures are communicator-fatal. The caller must tear down.

Review map

  1. nemo_rl/models/megatron/draft/sequence_layout.py, context_parallel.py, sequence_parallel.py: packed CP coordinates and collectives.
  2. nemo_rl/models/megatron/draft/training.py, dflash.py, dspark_provider.py, nemo_rl/algorithms/loss/: draft body, provider, and loss integration.
  3. nemo_rl/utils/packed_tensor.py: framed packed transfer and failure propagation.
  4. nemo_rl/models/generation/vllm/vllm_backend.py, speculator_runtime.py: draft weight load and post-load finalization.
  5. Unit and distributed tests under tests/unit/.

Review concerns and resolutions

Each row gives the concern, the code that resolves it, and the test that guards it. Rows 11, 13 to 18, 22, and 23 are new in this update. Row 3 changed after a second review.

# Concern Resolution in code Test
1 TP ranks with different shapes that are valid on each rank continue into sharded projections. DFlashBody._validate_inputs (draft/dflash.py) gathers the shape metadata of all TP ranks with a list-form all_gather. It raises "DFlash plan and input shapes must match across tensor-parallel ranks". test_dflash_body_tp.py::test_tp2_rank_local_valid_shapes_fail_before_first_projection, test_dflash_model.py::test_forward_rejects_device_dtype_and_index_type_mismatches, ::test_tensor_parallel_input_metadata_uses_rank_ordered_all_gather
2 Megatron generation with no override inherits training CP > 1 and skips the check. _validate_draft_training_setup (megatron_policy_worker.py) uses the training PP and CP when the backend is megatron and the override is absent. test_dflash_worker_validation.py::test_megatron_generation_inherits_training_parallelism_when_not_overridden, ::test_block_draft_setup_allows_generation_that_does_not_inherit_training_cp
3 The update probe fails on a step with no eligible windows. require_draft_update (draft/diagnostics.py) accepts every step with a zero draft gradient. On that step, optimizer momentum and weight decay can still move the parameters. It raises only when a nonzero gradient leaves the parameters unchanged. The worker (megatron_policy_worker.py) does the check only when update_successful is true, on the eager path and on the split path, so a step that the optimizer skips does not fail. test_draft_update_probe.py::test_require_draft_update_accepts_zero_gradient_step[static, decayed], ::test_require_draft_update_rejects_gradient_without_parameter_change
4 The eager path reduces draft counts over DP only. Both paths call _all_reduce_draft_normalization_counts with get_data_parallel_group(with_context_parallel=True). test_megatron_split_cp_distributed.py::test_context_parallel_finish_metric_and_draft_grad_parity (CP1/2/4)
5 A test name claims CP invariance, but a mock injects the counts. The test name is now test_draft_metric_uses_global_counts_before_replica_leader_filtering. A real multi-process test covers CP invariance. test_megatron_split_state.py::test_draft_metric_uses_global_counts_before_replica_leader_filtering, test_megatron_split_cp_distributed.py::test_context_parallel_finish_metric_and_draft_grad_parity
6 A packed batch with draft_sample_ids and no draft builds a draft layout and fails (Qwen3-VL). _draft_training_enabled (megatron/data.py) gates _get_packed_draft_sequence_layout. Only an enabled provider that needs the layout builds it. test_megatron_data.py::test_make_processed_microbatch_iterator_skips_draft_layout_when_draft_disabled
7 The synchronous NeMo Gym path drops draft_sample_ids. grpo.py calls _preserve_draft_sample_ids(gym_final_batch, repeated_batch) after Gym postprocessing. IDs use the list form of the index columns. test_grpo.py::test_sync_nemo_gym_draft_ids_reach_training_provider[dflash, dspark]
8 Draft CP > 1 without the split API fails late, after the first rollout. _validate_draft_trainer_entrypoint (grpo.py) runs in setup(). It rejects draft CP > 1 with async GRPO or with the data plane off. The worker check stays as a second guard. test_grpo.py::test_draft_trainer_entrypoint_fails_at_setup, ::test_draft_trainer_entrypoint_ignores_disabled_draft
9 Async GRPO without the data plane has no draft_sample_ids. The async trajectory collector (async_utils/trajectory_collector.py) calls _attach_grpo_draft_sample_ids when the draft needs IDs. test_async_utils.py::test_process_batch_non_gym_uses_one_batched_worker[block_draft], ::test_nemo_gym_groups_carry_input_draft_sample_ids_across_retry
10 Some consumer failures do not drain the remaining frames. packed_broadcast_consumer (packed_tensor.py) drains the lazy iterator in finally. The eager path holds callback errors until the terminal frame. The docstring marks CUDA and NCCL failures as communicator-fatal. test_packed_tensor.py::test_packed_broadcast_consumer_drains_after_load_failure, ::..._lazy_consumer_drains_when_closed_early, ::..._drains_after_metadata_failure, ::..._drains_after_unpack_failure
11 One nightly time budget covers the chained DFlash and DSpark runs. grpo-qwen3-8b-1n8g-megatron-dflash.sh sets NUM_MINUTES=90. The DSpark script is in disabled.txt because the DFlash script runs it. Nightly suite
12 The guide says the probe proves nonzero gradients. docs/guides/dflash-dspark-speculative-decoding.md now gives the rule from row 3: a gradient with no parameter change fails, and a zero-gradient step passes. It points to min(train/draft_loss) > 0 in the nightlies as the check that the draft trains. Docs only
13 The DFlash nightly recipe does not pin the draft revision. grpo-qwen3-8b-1n8g-megatron-dflash.yaml sets model_revision: 9b41424b7109f9c5413454f481b09a82b85333f4. Recipe
14 Validator tests miss CP outside {1, 2, 4}, provider capability checks, and Megatron inheritance. New tests call the real _validate_draft_training_setup. Each test runs for the DFlash provider and for the DSpark provider, and checks the provider name in the error. test_dflash_worker_validation.py::test_block_draft_setup_rejects_context_parallel_size_outside_supported_set[dflash, dspark], ::test_block_draft_setup_rejects_layout_the_provider_cannot_support[dflash, dspark], ::test_block_draft_setup_ignores_missing_capabilities_for_unused_features[dflash, dspark], and the two tests in row 2
15 DFlashSpeculator.forward and DSparkSpeculator.forward duplicate about 35 lines of capture checks. One helper, _validate_captured_sequence_layout (draft/training.py), holds the checks. Both speculators call it with their label. The CP boundary check is also one helper, _check_cp_boundary_exclusion. A contract test makes sure that each speculator calls both helpers with its own label. test_dflash_training_provider.py::test_captured_layout_validation_rejects_mismatches_with_provider_label[DFlash, DSpark] (all error paths, a layout with a different length, and a captured layout with no microbatch layout), ::test_cp_boundary_exclusion_rejects_only_fractions_above_limit, test_dflash_cp_provider_contract.py::test_block_draft_speculators_label_shared_checks_with_their_own_name
16 No TP2 forward test uses asymmetric attention. The TP2 parity test now also runs an asymmetric body: hidden 16, 4 heads, 2 KV heads, head_dim 16. It compares forward output, input gradients, all parameter gradients, and the checkpoint round trip. test_dflash_body_tp.py::test_tp2_projection_forward_gradient_and_checkpoint_parity[asymmetric]
17 Every test replaces _maybe_process_draft_after_loading, so its owner gate has no test. The test calls the real method. test_vllm_backend.py::test_maybe_process_draft_after_loading[no-manifest, no-draft, no-adapter, non-owner, owner]
18 A batch with no draft windows gives the draft no gradient and no signal. _check_cp_boundary_exclusion (draft/training.py) shows a UserWarning when the batch has no draft windows. The text says "batch" because the full-batch normalization count also calls this check. Python shows the warning one time for each call site. test_dflash_training_provider.py::test_cp_boundary_exclusion_warns_when_batch_has_no_windows
19 The step_state comment does not name the CP normalizer step. The comment in draft/step_state.py names the cp_normalize step in megatron/train.py. Comment only
20 Take _DRAFTER_OWNER_ATTRS and the refit order from #3750. DRAFTER_OWNER_ATTRS is in speculator_runtime.py. _validate_native_layerwise_refit() runs before _prepare_model_update_manifest in vllm_backend.py. test_vllm_backend.py
21 The branch is far behind main and carries stale copies of merged PRs. The branch was squashed to one commit on main d643cc4c11. It contains this PR and the open lower-stack PRs only. An audit of each hunk against main found no stale copy of a merged PR. The hunks that touch merged code are intentional, and rows 22 and 23 give the two that change behavior. Unit gate below
22 Packed EAGLE-3 with target SP worked on main (#3463). This PR rejects it. The packed EAGLE-3 path now goes through the draft provider and rolls the captured embeddings in each segment (roll_packed_seq_dim). With target SP, the captured states are SP shards, and a roll of a shard is not correct. Thus Eagle3DraftConfig.supports_target_sequence_parallel is False, and lm_policy.py rejects target SP at setup. The unpacked EAGLE-3 path on main also rolled SP shards, so the guard also stops that error. No EAGLE-3 recipe in examples/configs sets sequence_parallel: true. EAGLE-3 with target SP can come back in a follow-up PR that gathers the SP shards. test_lm_policy_draft_guards.py::test_draft_with_target_sequence_parallelism_is_rejected
23 tests/unit/conftest.py changes outside the draft code. On main, the session_data fixture reads the coverage total before the tests run. pytest_sessionfinish now reads cov_total from the pytest-cov plugin after pytest-cov combines the worker data. Unit CI coverage report
24 The DSpark contract checks and the DFlash negative-tap check have no test. No code change. test_draft_config.py::test_block_draft_config_rejects_invalid_contract[dflash-negative-tap, dspark-negative-tap, dspark-duplicate-tap, dspark-markov-without-confidence, dspark-all-zero-loss-weights]

Question from the 10-15 review: the old text said "TP2xPP2xCP2". That gate did not run, and the text was wrong. PP > 1 is not supported for training or generation. The validator rejects it. The tested layout is TP2xCP2 with PP1.

Stack and validation

Checklist

  • Contributor guidelines followed.
  • Tests added or updated.
  • Documentation and the supported contract updated.
  • OCI-HSG unit gate at the final head.
  • Maintainer approval and NVIDIA CI.

@copy-pr-bot

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

@seonjinn seonjinn added the CI:L1 Run doctests, unit tests, and functional tests label Aug 21, 2026
@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Aug 21, 2026

@seonjinn seonjinn left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Self-review before requesting reviewers -- the widest pass in this series: eight review agents mapped to the design doc's PR11 review allocation (packed-coordinate mappings, loss/normalization algebra, collective ordering/SP, support envelope, cross-PR composition, tests, line-level, CI/hygiene), then two independent adversarial verifiers (math lens and protocol lens) that re-opened every citation, re-derived the algebra, and executed empirical checks.

What survived is above (5 inline, all fixed in the follow-up commit). Equally important is what did NOT survive, recorded so human reviewers need not re-derive it:

  • The scariest candidate -- "eager train() reduces draft counts over DP-only while the deferred path uses DP x CP" -- is real asymmetry but UNREACHABLE: _validate_draft_training_entrypoint rejects draft+CP>1 on the sync path (its docstring anticipates exactly this hazard), and at CP=1 the groups coincide. The deferred path's normalization algebra was re-derived independently and is CP-invariant.
  • "Eagle exempt from draft validation" -- eagle3 cannot take the split API (supports_context_parallel=False) and the train() fallback raises on all ranks; the residue is only that eagle3+target-SP is unenforced (pre-existing).
  • Zero-owner CP ranks: verified EMPIRICALLY that backward traverses the zero-element graph via the deliberate gathered_dependency edge -- collective counts stay symmetric.
  • The packed coordinate systems (logical/global/CP-local, owner map, labels, RoPE frames) were hand-traced on boundary examples and re-executed: sample-boundary isolation is structural, the zigzag split matches Megatron's get_batch_on_this_cp_rank convention (a pinning unit test is a cheap follow-up worth adding), and CP1 degrades to exact identity.
  • draft_sample_ids dual-derivation concern: refuted -- both entrypoints stamp via the same helper.

Process, before undrafting:

  1. Restack. Every dependency branch carries review fixes this tree predates: 3701 8774f1d3d, 3703 895e0c212, 3706 76c2648d7, 3707 f658f69b9, 3711 54a3d9b4e+, 3715 7700a0774, 3723 abc74d779+, 3726 42cefa811, 3744 8a03385f2, 3750 f85be2ef2 (current drift vs dep tips: 1/1/14/18 commits for 3744/3750/3711/3723). The embedded copies in this tree lack all of them -- notably the dspark TP-attribute and checkpoint-group fixes and the eagle-ttt recompute guard class.
  2. No substantive CI has ever run on this PR (fork gate; no /ok to test in history). Issue it on the post-restack head.
  3. Follow-up tests worth scheduling: real 2-process CP test of _finish_train_step_body; a zigzag-vs-get_batch_on_this_cp_rank cross-check; real-distributed zero-owner coverage for the DSpark loss path (currently DFlash-attention-only).

Comment thread nemo_rl/models/megatron/draft/dflash.py Resolved
@seonjinn

Copy link
Copy Markdown
Contributor Author

Re-review at head 443e724 (previous review was at 815b783; delta = the restack merges plus +236 test lines):

Delta verdict — both remaining test asks are genuinely closed. test_megatron_split_cp_distributed.py is a real mp.spawn multi-process test of the production _finish_train_step_body (only parallel_state accessors are pointed at manually built real groups; the collectives themselves run), parametrized CP1/2/4 with zero-owner ranks, and its hardcoded expected value was independently re-derived by hand from the step_state formula — it matches exactly and cancels world_size, so it is a true oracle, not an impl mirror. This closes the earlier mock-stipulated-invariance finding. The new test_draft_refit case injects a payload-materialization failure on a non-owner rank only and verifies fingerprint-matched errors on every PP-lane rank with zero wasted broadcasts — the exact between-control-and-payload window flagged before.

Composition check: all five fixes from the previous review survived the restack merges (verified by marker), and no conflict artifacts remain. One item still open: the restack brought in the #3744/#3750 fix commits, but the embedded copies of the PR1–8 dependency content still predate their review fixes (spot-checked: dspark.py TP attributes, draft.py bin_ids range check, draft_config.py typo validator — all absent). Also note two fixes landed on dependency branches after this restack: #3711 1deb4beba (consumer-gated embedding TP reduction) and #3750 b4f7744da (preflight inside the fail-closed guard) — the next restack should pick up both plus the PR1–8 fix commits.

@seonjinn
seonjinn marked this pull request as ready for review August 23, 2026 05:50
@seonjinn
seonjinn requested review from a team as code owners August 23, 2026 05:50
@seonjinn

Copy link
Copy Markdown
Contributor Author

/nvskills-ci

1 similar comment
@seonjinn

Copy link
Copy Markdown
Contributor Author

/nvskills-ci

Comment thread nemo_rl/models/megatron/data.py Resolved
Comment thread nemo_rl/algorithms/grpo.py Resolved
@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test b52b1f4

seonjinn added a commit to seonjinn/RL that referenced this pull request Sep 12, 2026
seonjinn added a commit to seonjinn/RL that referenced this pull request Sep 12, 2026
@seonjinn
seonjinn requested a review from a team as a code owner September 12, 2026 02:16
@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 626a143

yuekaizhang added a commit to yuekaizhang/RL that referenced this pull request Sep 14, 2026
…_input_preparation

seonjinn (PR NVIDIA-NeMo#3960, item 6): DraftRuntimeLossWrapper sat directly after
DraftLossWrapper, inside the range the Megatron draft co-training stack's
NVIDIA-NeMo#3757 rewrites (DraftLossWrapper.__call__). Moving it after
wrap_loss_fn_with_input_preparation (the last thing in the file) gets it
out of that range at no cost, so a future rebase against that stack is an
ordinary append instead of an interleaved textual conflict. No behavior
change -- pure code motion, verified with the existing wrapper unit tests.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Yuekai Zhang <[email protected]>
seonjinn added a commit to seonjinn/RL that referenced this pull request Sep 15, 2026
@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test c499596

@seonjinn seonjinn removed the CI:L1 Run doctests, unit tests, and functional tests label Sep 17, 2026
@seonjinn

seonjinn commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 5a0f832

yeyu-nvidia added a commit to yeyu-nvidia/RL that referenced this pull request Nov 6, 2026
… NVFP4

Pipeclean recipe for the rollout speedup a co-trained LiLiCorr buys inside
MOPD. MOPD is the GRPO trainer with adv_estimator: opd, so this inherits
GRPO's drafter support rather than needing its own.

Two parent settings have to change, both for reasons that would otherwise be
startup failures or silent wrong training:

context_parallel_size 2 -> 1. DFlashBody raises on CP > 1, and LiLiCorr reuses
that backbone; the CP work is still in review (NVIDIA-NeMo#3750, NVIDIA-NeMo#3757). This is a real
change to the parallelism -- it roughly doubles per-rank activation memory for
a 120B policy -- so if it does not fit, raise TP/PP or land CP support in the
drafter rather than re-enabling CP and hitting the raise.

use_fused_linear_logprobs false. The fused path returns per-token logprobs and
never materializes the full next-token logits the draft's teacher needs.

model_name points at a DEQUANTIZED copy: the released drafter is NVFP4-packed
and co-training needs gradients.

Expectation recorded in the header rather than left implicit: measured
standalone, the released drafter gives 2.76x generation at concurrency 1 and
2.36x at 64, acceptance ~5.0 and flat across batch. Rollout is ~40% of a
real-quant step, so ~1.85-1.90x end to end -- 2x would need 3.77x on rollout.
@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 854a47d

Match the eager path: a skipped optimizer step changes no parameters, so
the split path no longer requires a draft update on that step. Correct the
guide's TP and async GRPO rejection list, and test the block draft config
reject branches.

Signed-off-by: seonjinn <[email protected]>
@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 1270cac

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test d6f1de4

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test eda02b8

@github-actions

Copy link
Copy Markdown

❌ Submodule Fast-Forward Check Failed

Check based on commit: eda02b8 (PR #3757 from seonjinn/draft-cotrain-cp-v1-linear)

❌ Submodules that need attention:

Gym: ❌ PR branch is BEHIND main branch
TARGET (main branch): https://github.com/NVIDIA-NeMo/Gym/commits/23557b7c2a48c60975c7719ee25cb6adb42963b7/
CURRENT (PR #3757 from seonjinn/draft-cotrain-cp-v1-linear): https://github.com/NVIDIA-NeMo/Gym/commits/5911d628c744d0bf43fe1d9ddf3bda72d59b0f9a/

Please ensure all submodule commits are fast-forwards of the main branch before merging.

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test dfa1922

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 94d6738

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 67b386d

Carry over the NVIDIA-NeMo#3750 review changes: required draft_weights, preflight
token before bulk reshard on Megatron and TRT-LLM receivers, and removal
of draft_metadata_only, include_draft and generation cp_size.

Signed-off-by: seonjinn <[email protected]>
@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 19abd4e

Take the manifest plus per-tensor PP stream from draft/refit.py and drop the readiness token, draft preflight and packed frame protocol. stream_draft_weights_for_refit gains an export_weights hook so DFlash and DSpark providers export their own weights.

Signed-off-by: seonjinn <[email protected]>
@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 044b960

@terrykong terrykong removed the Documentation Improvements or additions to documentation label Nov 28, 2026

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

Labels

CI:L1 Run doctests, unit tests, and functional tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants