Repository navigation
feat(automodel): add pipeline parallelism to the Automodel policy worker - #4960
Conversation
Add pipeline parallelism (PP) to the Automodel training backend, following the Automodel PP RFC (phase 1: 1f1b and interleaved_1f1b, SFT and GRPO with colocated generation). Automodel's AutoPipeline splits the model into stages and builds the PyTorch schedule; NeMo RL keeps batch planning, the RL loss, gradient normalization and clipping, the optimizer step, logprobs, the reference policy, checkpoints, and weight refit. - Config: policy.automodel_cfg.pipeline_parallel_size and the Pydantic `pipeline` block (pp_schedule, microbatches_per_step, layers_per_stage). validate_automodel_pipeline_config rejects unsupported combinations (sequence packing, dynamic batching, CP, EP, SP, CPU offload, LoRA, draft, router replay, VLM, non-colocated generation, tied embeddings, ...) before any worker is created. - Model parts: ModelRuntime holds the local stages with their global stage IDs and one optimizer and LR scheduler per part. - Execution: plan_execution_batches pads each chunk to whole schedule calls and equalizes the call count over DP; PipelineOutputAdapter runs the existing loss/logprob post-processors on the last stage, keyed by sample ID, with the non-PP backward scale. - Update lifecycle: train() now runs _open_update / _run_update_chunk / _close_update per global batch (known-N normalization only); the non-PP path is bitwise identical to before. - Logprobs, reference swap, offload (releases PP buffers), multi-part checkpoints with optimizer_part_ids, TQ write-back coordinates with PP, and PipelineWeightExporter for full-model refit streams. - Docs (design-docs/automodel-pipeline-parallel.md), exemplar configs, unit/GPU tests, and two 1n8g nightly recipes. Signed-off-by: larkzhang-nv <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
Automodel builds the expert-parallel mesh inside each pipeline stage, so pipeline parallelism no longer rejects expert_parallel_size > 1; EP must divide the dp * cp * tp ranks of one stage (for example EP8 with PP2 on 16 GPUs). Models that implement get_pipeline_kwargs_chunk_dims (such as Qwen3.5-MoE) are no longer rejected at setup. The batch planner now checks the hook on one microbatch's inputs and rejects only inputs whose batch dimension is not dim 0 (for example multimodal M-RoPE position IDs); text-only inputs run. Tests: tiny Qwen3-MoE PP2xEP2 vs PP1xEP2 parity, planner chunk-dims checks, and validation accepting EP. Qwen3.5-35B-A3B GRPO on 2x8 GPUs (PP2 x EP8 vs the EP16 baseline, 10 steps) matches per-step token_mult_prob_error and gen_kl_error and passes the recipe's metric checks. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
Pipeline parallelism no longer rejects context_parallel_size > 1. As Automodel's own pipeline trainer does, the batch planner shards each execution batch once for all of its microbatches with Automodel's ContextParallelSharder (num_chunks = microbatches per schedule call), and the schedule call runs inside the sharder's context. That context may shard the inputs in place, so the stage shapes are set from the input length inside it. The loss adapter maps each microbatch's targets and logprobs through the call's sharder, which is valid because the layout depends only on the sequence position. The CP preparation shared with the non-pipelined path moves into shard_model_batch_for_cp, and the worker plans execution batches through one helper. Tests: validation accepts CP under PP, the planner shards each call once without touching the canonical loss data, and a PP2xCP2 vs PP1xCP2 GPU parity test on a tiny Llama. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
The fp32 parity runs use memory-efficient SDPA, whose log-sum-exp is padded to 32 tokens, and torch's load-balanced ring attention merges it per chunk of seq_len / (2 * cp_size) tokens without trimming. The 32-token batches gave 8-token chunks and failed in the non-pipelined CP reference run. The CP test now uses 128-token sequences; the other tests keep their 32-token batches. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
…only Match the Megatron backend, which keeps one model chunk per rank: under 1F1B every pipeline rank owns exactly one stage, so the worker no longer needs per-rank lists of model parts, optimizers, and LR schedulers. - Remove ModelRuntime (model_handle.py). The worker holds this rank's stage as self.model with its optimizer and scheduler, plus self.pipeline (the AutoPipeline, None without PP). Lifecycle code is main's again; only execution, logprobs, refit, and the optimizer checkpoint namespace branch on self.pipeline. - Setup takes the stage from AutoPipeline.parts and runs the shared post-processing; only the MoE flag is reduced over the PP group. - Checkpoints pass the stage index as optimizer_part_ids, as Automodel's own pipeline trainer does; the manager keeps single-module signatures. - policy.automodel_cfg.pipeline keeps only microbatches_per_step; the block forbids extra keys, so pp_schedule and layers_per_stage fail at startup. - Drop the interleaved GRPO nightly recipe and the interleaved test cases. - Register the new pipeline modules with pyrefly and fix the type errors that surfaced (all_gather_object buffer, Annotated field constraints, narrowing automodel_cfg). Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
…arallelism Drop the open / run-chunk / close update lifecycle. Nothing outside train() used it, it did not match the framework's begin_train_step / train_microbatch / finish_train_step contract, and its streaming paths were unreachable. - train() is main's loop again: one optimizer update per global batch, with a pipeline branch for the forward and backward pass and one broadcast of losses and metrics from the last stage after the loop. - pipeline_forward_backward runs Automodel's gradient-accumulation hooks itself, as Automodel's own pipeline trainer does, and loses the always-on sync_expert_grads argument. - The micro batch size check moves into _plan_execution_batches, shared by training and logprobs. - Remove the test-only chunked-update worker and its tests. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
ExecutionBatch and plan_execution_batches only feed the pipeline schedule call in pipeline_parallel, so batch planning and execution now live in one module, matching the single-file Megatron pipeline_parallel. The weight exporter stays in pipeline_refit. No behavior change. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
This reverts commit 4cbe738. Signed-off-by: larkzhang-nv <[email protected]>
Move execution batch planning and full-model weight export into pipeline_parallel alongside schedule execution. Update worker and test imports, the CP monkeypatch target, type-checker paths, and documentation references without changing runtime behavior. Signed-off-by: larkzhang-nv <[email protected]>
Pass a padding mask to model forwards that explicitly accept it so synthetic pipeline rows do not contribute router auxiliary losses or expert load. Add planner and distributed MoE regression coverage and document the masking behavior. Signed-off-by: larkzhang-nv <[email protected]>
Signed-off-by: larkzhang-nv <[email protected]>
Signed-off-by: larkzhang-nv <[email protected]>
This reverts commit d23cdd4. Signed-off-by: larkzhang-nv <[email protected]>
This reverts commit e15818c. Signed-off-by: larkzhang-nv <[email protected]>
Match the submodule revisions recorded by NVIDIA-NeMo/RL main at 6e68b17. Automodel and Megatron-Bridge were restored by the preceding revert; update Gym and its lockfile metadata to complete the alignment. Signed-off-by: larkzhang-nv <[email protected]>
…lism Fail driver-side validation when PP is enabled with a nonzero clear_cache_every_n_steps. Preserve disabled settings and non-PP behavior, with regression tests and documentation. Signed-off-by: larkzhang-nv <[email protected]>
Signed-off-by: larkzhang-nv <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
…peline in LoRA refit test Defer annotation evaluation so test_automodel_pipeline_parallel.py collects (and skips) when nemo_automodel is unavailable, and set worker.pipeline in test_refit_metadata_excludes_grouped_adapters now that prepare_refit_info reads it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
Drop the unused return value, make model_config required (the driver always loads it for PP), and shorten the error messages. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
DPO runs microbatches of 2 * train_micro_batch_size, which the pipeline stage buffers cannot hold, so it previously failed at the first train step. Document that Automodel PP supports SFT and GRPO. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
Turn the stateless PipelineOutputAdapter into pipeline_loss_fn, merge the exporter's manifest builder into manifest(), inline the padding_mask signature check, and drop a broadcast shape check its only caller already guarantees. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
Restructure the note around configuration, constraints, design, and limitations, and sync it with the current code: pipeline_loss_fn, DPO and value worker rejection, and CP-produced M-RoPE inputs being rejected. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
Signed-off-by: larkzhang-nv <[email protected]>
sharonyu-115
left a comment
There was a problem hiding this comment.
Thanks for this contribution. The PR adds pipeline parallelism to the Automodel policy worker for GRPO and SFT: Automodel's AutoPipeline runs the 1F1B schedule, one stage per PP rank, while NeMo RL keeps batch planning, the RL loss on the last stage, clipping, the optimizer step, logprobs, checkpoints and a full-model weight stream for colocated refit. PP=1 stays on the existing code path, and the loss, metric scaling and CP sharding helpers are shared between both paths.
Review by seven lanes (RL guidelines, Automodel API check against the pinned submodule, tests and CI logs, bug hunt, design, existing threads, adversarial pass) plus an editing pass. No GPU was available to the review, so no test was run; CI at head is green on every lane except codecov/patch. Every Automodel and torch 2.13 pipelining call the PR makes was checked against source; no wrong API use and no bug with a reachable failing case was found. The author's eleven self-review items (C1–C11) are all applied at head and the threads are resolved.
Inline comments:
- (C12) The six "needs 4 GPUs" tests skip in CI, so no CI test drives a padding microbatch through a real schedule call; a 2-GPU padding test is proposed.
- (C13) The TQ-coordinates test also skips in CI; the same property holds on 2 GPUs.
- (C14) The logprobs loss-function test does not check that the logits storage is freed.
- (C15) Telemetry and the observability doc still say Automodel has no PP dimension.
- (C16)
pipeline_parallel_sizeis in 2 of the 7 base exemplar YAMLs that carryautomodel_cfg. - (C17) A pipeline-parallel distillation teacher passes setup and fails after the first rollout.
- (C18) Evidence ask: name the two recipe differences that PP forces, and add step time and memory for the three 2n8g recipes.
No action: the direct schedule.step(..., loss_kwargs=...) call needs torch 2.13 or newer, which the automodel extra pins exactly. The pre-existing HSDP divisibility check in setup_distributed divides world size by tp*cp*ep as if EP were outside DP; this PR only multiplies pp into it, and it can be looked at separately.
Generated by Claude Code
Signed-off-by: larkzhang-nv <[email protected]> # Conflicts: # tests/unit/test_recipes_and_test_suites.py
- Reject a pipeline-parallel teacher at setup in distillation and xtoken distillation, where get_topk_logits / get_full_logits_ipc have no PP path. - Report nv.dl.topology.size.pp for Automodel and update the telemetry docs. - Run the PP padding and TQ-coordinate tests on 2 GPUs so CI covers them. - Check that the logprobs loss path frees the logits storage. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
|
/ok to test 1c7b952 |
|
@sharonyu-115 Thanks for the review! All comments are addressed in 1c7b952, except C16: I kept the other example configs unchanged because this PR only supports PP for GRPO and SFT, and the other algorithms reject PP > 1 at setup. Could you take another look when you have a chance? |
yuki-97
left a comment
There was a problem hiding this comment.
Merge blockers — please rebase on main and resolve conflicts.
Really solid work bringing pipeline parallelism to the Automodel policy worker for GRPO and SFT: Automodel's AutoPipeline runs the 1F1B schedule while NeMo RL keeps batch planning, the RL loss on the last stage, clipping, logprobs, checkpoints and refit.
Great to see the baseline vs PP2 vs PP2+CP2 curves for three recipes, the step-time table and the 32-node PP4 run posted in the description: the effect of PP is easy to see. Thanks also for the two rounds of self-review and review fixes already applied.
Scope: the whole PR, at 1c7b952
- GPU tests were not run in this review; CI at this head and the runs in the description are the execution evidence.
- Earlier reviews by the author's self-review and @sharonyu-115 (thanks!) covered tests, docs and validation; this pass concentrated on the Automodel and
torch.distributed.pipeliningcalls, batch planning and padding, and the support matrix.
Checked:
- Upstream APIs — every Automodel pipelining, CP, clipping and checkpoint call and the
schedule.step/schedule.evalusage match the pinned Automodel b916107a and torch 2.13 sources. - Non-PP path — unchanged: the extracted helpers (
post_process_logits,shard_model_batch_for_cp,backward_loss_scale,scale_metrics_for_global_batches) are shared by both paths, andnum_label_tokens=Noneonly matters whenpp_enabledis true. - Padding rows — masks are zeroed on copies, valid-sequence and token counts are computed before padding, and both loss functions mask every term, so padded microbatches add nothing to loss or metrics.
- Results and refit — both are broadcast from the owning stage and every PP rank consumes the full weight stream;
Policyuses one PP rank per DP rank, so nothing is double counted. - Setup checks — every combination listed in the validator and in the DPO / value / teacher checks is rejected at setup, before workers start.
- Nightly budget — the GPU-hour cap increase equals the cost of the two new entries.
Remaining comments are on:
- MTP models under PP are not rejected
pipeline_parallel_sizemissing from most base configs, which keeps a fallback helper alive- the DP formula in a config comment and in the
dp_replicate_sizecheck - end-to-end checkpoint resume on a PP recipe
convert_dcp_to_hf.pyon a PP checkpoint
nit
- stale
optimizer_part_idswording - stale "Automodel has no PP" test comments
DistributedContext.pp_sizedefault- the PP refit weight stream chosen at each call site
- placement of two tests
nemo-rl-review: kind=expert harness=claude-code/2.1.330 model=claude-fable-5-2 effort=medium review-pr-team=v2 reviewed=1c7b952
Signed-off-by: larkzhang-nv <[email protected]> # Conflicts: # pyrefly.toml # tests/unit/algorithms/test_distillation.py # tests/unit/test_recipes_and_test_suites.py
- Reject MTP models (num_nextn_predict_layers > 0) under PP. - Make automodel_cfg.pipeline_parallel_size a required key: add it to every base config, teacher list entry and reference config, and drop the automodel_pipeline_parallel_size fallback helper. - Derive the HSDP data-parallel size from pp * tp * cp; EP does not divide DP. - Route every refit path through one _iter_refit_params entry point and build the pipeline weight exporter in __init__. - Make DistributedContext.pp_size required. - Move the build_pipeline_config and TQ coordinate tests next to their modules. - Refresh stale PP docstrings and test comments; unwrap the design doc lines. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
|
/ok to test 72c33cc |
…gine worker The checkpoint-engine stream now goes through _iter_refit_params, which reads the attribute __init__ sets. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
|
/ok to test 6122f8e |
…ip config Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
|
/ok to test 1a15b2f |
jQizhang
left a comment
There was a problem hiding this comment.
Self-review of head 1a15b2f by a team of 7 agents (RL, Automodel, design, bugs, tests, existing threads, adversarial check).
No correctness bug found in the product code. Run locally: test_automodel_pipeline_parallel_worker.py 10 passed / 6 skipped on 2 GPUs and 16 passed on 4 GPUs; PP2 matches PP1 under CP2 and EP2; pre-commit passes. CI has not run at this head yet.
Two reviewer questions were resolved without an answer and are reopened as replies in their threads:
- (C19) PP resume end to end on
ep8pp2. - (C20)
convert_dcp_to_hfon a PP checkpoint ofep8pp2.
nemo-rl-review: kind=self harness=claude-code/2.1.332 model=claude-fable-5-2 effort=medium review-pr-team=v3 reviewed=1a15b2f
|
Hi @yuki-97 , thanks for the careful review! I've addressed all of your comments. I also tested the two cases you asked about locally, and both work: training resumes correctly from a PP checkpoint, and a PP checkpoint can be exported to Hugging Face format with The self-review format has changed on main, so I re-ran Could you take another look at the new changes when you have time? Thanks! |
yuki-97
left a comment
There was a problem hiding this comment.
Merge blockers — please rebase on main; the PR is 12 commits behind and the "Check if PR branch is up to date" job allows at most 10.
Thanks for resolving the previous comments.
Scope: fix commits c63c236 through 1a15b2f, checked against the threads from the previous review, plus a scan of the changed files for new issues.
Checked:
- Required
pipeline_parallel_size— every enabledautomodel_cfgblock in the repo resolves to the key through itsdefaults:chain, so the direct reads cannot hit a missing key. - HSDP check —
pp * tp * cpis the data-parallel size Automodel infers (mesh_utils.py:300-306). - Refit under PP — every full-model refit path goes through
_iter_refit_params, and building the exporter in__init__runs no collective and reads no parameter. - Moved tests — both passed, not skipped, in CI at 1a15b2f.
- PP resume, and
convert_dcp_to_hfon a dense model — the tiny-model results posted in the threads are sufficient.
Remaining comments:
- Whether PP with MTP is supported for Qwen3.5-MoE, which passes the MTP check; reject it there if not.
- If it is supported, the HF export of a PP checkpoint of that model has no
mtp.*weights.
nit
- Old data-parallel formula in the parallel-plan doc.
- One more test docstring that says Automodel has no pipeline parallelism.
nemo-rl-review: kind=expert harness=claude-code/2.1.332 model=claude-fable-5-2 effort=medium review-pr-team=v3 reviewed=1a15b2f
Qwen3.5 has no num_nextn_predict_layers; Automodel falls back to mtp_num_hidden_layers, so the PP MTP check let it through and the MTP head was silently dropped at the stage split. Read the MTP depth the same way Automodel does and name the exact override in the error. Turn MTP off in the Qwen3.5 PP recipes, and fix the data-parallel formula in the parallel-plan doc and a stale test docstring. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: larkzhang-nv <[email protected]>
|
/ok to test 67d38f2 |
Brings in main up to dfe2dcd. #4960 added a pipeline-parallel guard for teachers to xtoken_off_policy_distillation.py and its unit test, which this branch renames; the merge carries those lines into cross_tokenizer_distillation.py and test_cross_tokenizer_distillation.py. Signed-off-by: Adithya Hanasoge <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
The shared _clip_policy_grad_norm helper now reads self.pipeline for the PP-aware clip arguments (from NVIDIA-NeMo#4960). The split-state fixture builds the worker with object.__new__ and never set the attribute, so three tests failed with AttributeError in L0_Unit_Tests_Automodel_Policy_{1,2,3}. Match the existing worker fixtures in test_automodel_worker.py. Signed-off-by: Shuang Yu <[email protected]>
What and why
The Automodel policy worker had no pipeline parallelism, so large models on the Automodel backend could only be split with FSDP, TP, CP and EP. This PR adds pipeline parallelism (PP) to the Automodel policy worker, for GRPO and SFT.
How it works
AutoPipelinesplits the model into stages and runs the 1F1B schedule (one stage per PP rank). NeMo RL owns batch planning, the RL loss, grad clipping, the optimizer step, logprobs, checkpoints, and refit.post_process_logitspath as non-PP, so loss, metrics, and logprobs match PP1. Results are broadcast from the last stage, so every PP rank returns whatPolicyexpects.worker.model. Optimizer, scheduler, clipping, offload, and the reference swap are shared with the non-PP path; only execution, logprobs, refit, and checkpoints branch onworker.pipeline(Nonewithout PP). PP=1 is unchanged.microbatches_per_stepmicrobatches. All DP ranks issue the same number of calls; the tail is padded with masked samples.PipelineWeightExporterstreams the full model (HF names) on every PP rank for colocated refit.Design note:
docs/design-docs/automodel-pipeline-parallel.md.Support matrix
refit_transportnum_nextn_predict_layers > 0, ormtp_num_hidden_layers > 0for Qwen3.5; Qwen3.5 PP recipes setpolicy.hf_config_overrides.text_config.mtp_num_hidden_layers: 0)Usage
With EP,
expert_parallel_sizemust divide thedp * cp * tpranks of one stage (e.g. EP8 with PP2 on 16 GPUs).Issues
None.
Convergence / perf / functionality proof
Experiments
Each PP run uses the same recipe as its baseline, except for the parallelism and two settings PP requires: dynamic batching off and
defer_fsdp_grad_sync: false. Across all runs, reward, generation length,gen_kl_error, and validation accuracy track the baseline.GRPO: Qwen3.5-35B-A3B, 2n8g, 50 steps
Recipe:
grpo-qwen3.5-35ba3b-2n8g-automodel-ep16(baseline); PP runs are the nightlies added in this PR,...-ep8pp2and...-ep8pp2cp2.Medians over steps 2–50. Generation (~245 s) dominates the step in all three runs. Ray-sampled GPU memory peaks at ~55 GB in all three runs; per-process peak training memory was not logged.
DAPO: Nemotron-3.5-Lightning-30B-A3B, 4n8g, 27 steps
Recipe:
dapo-nanov3.5-30BA3B-4n8g-automodel-ep8.DAPO: Qwen3.5-35B-A3B-Base, 4n8g, 50 steps
Recipe:
grpo-qwen3.5-35ba3b-dapo-4n8g-automodel-ep32.GRPO: Muse Spark 816B, 32n8g, PP4, 30 steps
Large-scale run with this PR. Setup guide: Muse Spark guide.
Tests
mbs=2, eval-mode train, checkpoint resume, reference policy, offload, and colocated vLLM refit.grpo-qwen3.5-35ba3b-2n8g-automodel-ep8pp2andgrpo-qwen3.5-35ba3b-2n8g-automodel-ep8pp2cp2.Needs upstream changes
None. The Automodel pin on main (
b916107a) already has the pipelining APIs this PR uses.PR commands and CI
CI:Lfast: the default for most PRs. Runs a fast test subset.CI:L1: dependency or container changes (pyproject.toml,uv.lock,Dockerfile) or broad core changes. Builds a new image and runs unit and functional tests.CI:docs: docs-only changes. Runs doc tests only./ok to test <full-commit-sha>: start CI for that commit. Post again after each push./internal-ci test-case=<job>: run NVIDIA's internal nemo-ci pipeline for the PR head; eligible teams only./review: automated review comments. Addmode=strictfor a stricter review,reset=truefor a fresh full review./resolve-conflict: Autobot mergesmaininto this PR and resolves the conflicts. PRs from forks must allow edits by maintainers./review-pr-team <pr-number>for a team review before you ask for human review.🤖 Generated with Claude Code