Skip to content

feat(megatron): prefill/decode engines behind Dynamo, refit side - #4912

Merged
terrykong merged 55 commits into
mainfrom
laurad/pd-sc-2-refit-channel
Dec 2, 2026
Merged

terrykong merged 55 commits into
mainfrom
laurad/pd-sc-2-refit-channel

Conversation

@lauradang

@lauradang lauradang commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor
  • I, the PR author, have personally reviewed every line of this PR.

What and why

PR 2 of 6. PR 1 (#4801, merged) added the config for Megatron prefill/decode engines behind Dynamo; nothing builds those engines yet. This PR builds them and makes them the refit target. With policy.generation.backend: megatron and dynamo: true, generation now resolves to a new class, MegatronDynamoGeneration. Rollouts are not served yet: validate_settings still refuses the switch, and later PRs in the stack turn it on.

GenerationInterface
├── MegatronGeneration                 o-- Policy
└── MegatronDynamoGeneration           o-- N x MegatronGeneration (one per prefill/decode engine)
                                       o-- ManagedDynamoRuntime   (PR 3)

MegatronDynamoGeneration sits next to MegatronGeneration; it does not subclass it.

  • Engines (megatron/dynamo_generation.py). One MegatronGeneration per engine, on its own cluster. Each engine's config is a copy of the policy config with:

    • its role in generation._disaggregation_role;
    • its role's overrides from mcore_generation_config.prefill_engine / decode_engine (layout, plus a new per-role max_requests cap);
    • dynamo: false, so it is sized as one engine.

    Engines up to one node wide share nodes. Wider engines take whole nodes inside one NVLink segment.

  • Refit fan-out. Every refit call (collective init, prepare, transfer, suspend, KV-cache prepare, resume) goes to the engines' Ray workers in engine order, each at its own rank offset, so a TP 4 prefill engine can sit next to TP 2 decode engines. MegatronDynamoEngineHandle holds one engine's worker handles.

  • Suspend/resume follow the engine's real state, not the worker's asleep flag (megatron_worker.py). A stuck transition gives up at the caller's deadline. If a suspend fails, every engine is resumed before the error is raised.

  • One worker class. MegatronPolicyWorkerImpl gains MegatronDynamoGenerationMixin (megatron/dynamo_worker_mixin.py). With a role set, it builds Megatron-LM's DynamoDynamicInferenceEngine with NIXL KV transfer and a coordinator on the node IP. Without one, the hooks fall back to the plain engine. With a role, the worker fails before model load if Megatron-LM lacks the Dynamo integration or InferenceConfig.disaggregation_role.

  • Pickled copies keep only handles. The SingleController's copy can drive refits but never shuts an engine down.

  • resolve_generation_class and the SingleController setup pick the class through megatron_generation_cls(generation_config).

Stack: main ← PR 2 (#4912, this) ← PR 3 (#5023) ← PR 4 (#5024) ← PR 5 (#5025) ← PR 6 (#5097). PRs 2–4 change nothing at runtime on their own; PR 5 turns the feature on; PR 6 adds NeMo-Gym serving.

Tests:

  • test_megatron_dynamo_generation.py: engine build per role and layout, node placement (including engines wider than a node), partial-start teardown, pickled copy, refit fan-out and rank offsets, suspend/resume failures.
  • test_megatron_dynamo_worker_mixin.py: engine variant per role, fallback without a role, the Megatron-LM checks.
  • test_megatron_worker_sleep_wake.py: partial pause, stale asleep flag, stopped loop, stalled transition.
  • test_megatron_dynamo_config.py, test_policy_validation.py, test_setup.py: class resolution and config refusals.

Issues

None

Convergence / perf / functionality proof

N/A: nothing runs at runtime yet; validate_settings still refuses dynamo: true with backend: megatron. CPU unit suites pass; the GPU path is exercised once PR 5 turns the feature on.

Needs upstream changes

  • ci: bump MBridge to 1ec9ce8b0 #5427 (Megatron-Bridge bump): brings a Megatron-LM whose InferenceConfig has disaggregation_role, which the prefill/decode engines need. Until it lands, an engine with a role fails before model load on the current pin.
PR commands and CI
  • CI label, exactly one:
    • 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. Add mode=strict for a stricter review, reset=true for a fresh full review.
  • /resolve-conflict: Autobot merges main into this PR and resolves the conflicts. PRs from forks must allow edits by maintainers.
  • Locally: /review-pr-team <pr-number> for a team review before you ask for human review.
  • Contributor guidelines

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 26, 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.

@copy-pr-bot

copy-pr-bot Bot commented Oct 26, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

…bership shard widths

Megatron prefill/decode engines served through a managed Dynamo frontend are
switched on with policy.generation.dynamo=true on a backend=megatron config,
the way vLLM engines will be. A new megatron.dynamo_config module validates
the dynamo_cfg block (frontend args, timeouts, per-role prefill_engine /
decode_engine layout overrides), sizes each role's engine from the layout its
dedicated inference policy is built with (including the expert-parallel grid
check), and tiles replicas prefill-first.

RefitMembership gains per-shard widths with cumulative rank prefixes so a
prefill shard at TP 4 can sit next to decode shards at TP 2 in one refit
communicator; the vLLM and Megatron refit paths index workers through
worker_offset. The legacy GRPO entrypoint refuses the switch; the
SingleController sizes inference segments by the replica width.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@lauradang
lauradang force-pushed the laurad/pd-sc-2-refit-channel branch from 368f413 to 99e7df3 Compare November 4, 2026 03:00
@lauradang lauradang changed the title feat(dynamo): Megatron refit channel, worker hooks, and the refit protocol feat(megatron): worker hooks for prefill/decode engines behind Dynamo Nov 4, 2026
lauradang and others added 2 commits November 3, 2026 19:28
…layouts

- MegatronGeneration.validate_settings checks a dynamo config with
  validate_megatron_dynamo_generation and then refuses it, so the
  SingleController no longer trains plain aggregated engines with the
  switch on.
- Per-role TP/PP overrides must be positive.
- Type-check megatron/dynamo_config.py.
- Test the non-megatron backend guard in resolve_generation_class.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
A Megatron engine behind Dynamo learns whether it is a prefill or decode
engine from policy.generation._dynamo_role, which the engine fleet sets on
each engine's own copy of the config (as TrtllmGeneration injects
trtllm_cfg._engine_roles). The worker can then build the handoff engine for
that role without a separate pre-build attach call. Validation refuses the key
in a user's config.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@lauradang
lauradang force-pushed the laurad/pd-sc-2-refit-channel branch from 99e7df3 to 2b50e6a Compare November 4, 2026 03:39
Resolve tests/unit/single_controller/test_setup.py: keep the Megatron
Dynamo replica-sizing test and drop the MOPD recipe-resolution test, which
main removed under its new testing rules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@lauradang
lauradang force-pushed the laurad/pd-sc-2-refit-channel branch from ff720da to 9268d82 Compare November 5, 2026 09:26
lauradang and others added 2 commits November 5, 2026 01:27
policy.generation.dynamo=true on a backend=megatron config now resolves to
MegatronDynamoGeneration, a GenerationInterface implementation next to
MegatronGeneration (not a subclass) that owns one dedicated Megatron inference
engine per prefill or decode engine instead of one inference policy, and
routes the Megatron weight synchronizer's calls over them. The plain class
gains no branches; the Dynamo class runs MegatronGeneration's settings checks
before its own.

MegatronDynamoGeneration builds one MegatronGeneration per engine over its
own one-node virtual cluster from a copy of the policy config that carries
the engine's role and its role's layout overrides; the engines come up at
the first refit. It fans the controller's calls (collective init, prepare
the weights, transfer, suspend, prepare the KV cache, resume) out over the
engines' Ray workers in record order with cumulative rank prefixes, so a
prefill engine at TP 4 may sit next to decode engines at TP 2. A failed
suspend resumes every engine before the error propagates. A pickled copy
keeps only the engine records (plain data plus the workers' handles), so the
controller's copy drives refits without being able to shut an engine down.

On the worker, the role picks the engine variant: Policy builds a
MegatronDynamoPolicyWorker when generation._dynamo_role is set, and its
mixin builds Megatron-LM's DynamoDynamicInferenceEngine with NIXL KV
transfer for that role and a coordinator reachable from other nodes, through
three hooks the plain worker fills with defaults.

Rollouts are not served yet: nothing registers the engines with a frontend,
so validate_settings keeps refusing the switch and generate_async raises.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
… off

A MegatronDynamoPolicyWorker now checks for Megatron-LM's Dynamo integration
in its constructor, before the model loads, instead of failing at the first
refit when the engine is built. It is also registered in the actor
environments, with the same extras as MegatronPolicyWorker; without an entry
the worker group cannot pick a venv for it and the first engine fails to
start.

Each engine's config turns generation.dynamo off next to its role, so the
engine's own MegatronGeneration sizes its NVLink span by the engine's width
instead of a whole prefill/decode replica.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@lauradang
lauradang force-pushed the laurad/pd-sc-2-refit-channel branch from 9268d82 to 9232cf1 Compare November 5, 2026 09:27
@lauradang lauradang changed the title feat(megatron): worker hooks for prefill/decode engines behind Dynamo feat(megatron): prefill/decode engines behind Dynamo, refit side Nov 5, 2026
@lauradang
lauradang marked this pull request as ready for review November 5, 2026 09:27
@copy-pr-bot

copy-pr-bot Bot commented Nov 5, 2026

Copy link
Copy Markdown

Auto-sync is disabled for ready for review pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@lauradang
lauradang requested review from tdene, terrykong and wdykas and removed request for tdene November 5, 2026 09:34
lauradang and others added 4 commits November 24, 2026 15:33
- Add reject_megatron_dynamo_outside_single_controller in
  megatron/dynamo_config.py: for backend megatron it raises
  NotImplementedError when dynamo is on and ValueError when
  prefill_engine / decode_engine are set without dynamo. Call it from
  grpo.setup (replacing the inline check) and distillation.setup, so
  distillation no longer trains plain Megatron for a Dynamo config.
- Drop the unread DISAGG_BACKENDS constant from disagg_layout.py.
- Drop the duplicate dynamo guard in resolve_generation_class; the
  backend refusal test now targets configure_generation_config, the
  copy that runs.
- Drop the test-only Megatron replica_width helper and its asserts.
- Give each build_clusters Megatron Dynamo case an inference node count
  whole replicas fill.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
TRT-LLM kept its own copies of the layout helpers that disagg_layout.py
now holds, so main had two resolve_disagg_layout functions and two
engine planners.

- trtllm/config.py drops _as_dict and resolve_disagg_layout and uses
  the shared ones; replica_width sums through replica_width_from.
- TrtllmGeneration._plan_engines calls disagg_layout.plan_engines, so
  its layout errors are now ValueError instead of AssertionError.
- plan_engines refuses a replica without at least one prefill and one
  decode engine, the check TRT-LLM's planner had: without it 0/0 hit
  ZeroDivisionError and 0/1 planned decode-only replicas.
- grpo.py, nccl_reshard_utils.py and the TRT-LLM tests import
  resolve_disagg_layout from disagg_layout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
Conflicts: dynamo_config imports (PR 1 dropped the unused replica_width,
so replica_width_from goes too; plan_engines stays for
plan_megatron_engines), megatron_generation imports (keep PR 1's
reject_role_layouts_without_dynamo; validate_megatron_dynamo_generation
moved to MegatronDynamoGeneration), and the dynamo-config test (keep PR 1's
new rejection cases, keep the engine-role case in its own test).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
The merged validate_settings ran reject_role_layouts_without_dynamo in
the else branch, so a Dynamo config with a prefill_engine/decode_engine
layout was refused as 'ignored without Dynamo' before reaching
MegatronDynamoGeneration's own checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
Base automatically changed from laurad/pd-sc-1-plan-seam-config to main November 25, 2026 03:26
PR 1 was squash-merged to main at the head this branch already merged
(45337a5); conflicted files were resolved with 45337a5 as the merge
base.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@lauradang

Copy link
Copy Markdown
Contributor Author

/ok to test 10e753c

pyrefly rejected passing the GenerationConfig TypedDict to the plain
`dict` parameter, and the `type[GenerationInterface]` return type hid the
constructor, so constructing the returned class with keyword arguments
failed as `object.__init__` calls. Take GenerationConfig as the callers
do and return the concrete MegatronGeneration / MegatronDynamoGeneration
class union, which share one constructor signature. Annotation-only; no
runtime change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@lauradang

Copy link
Copy Markdown
Contributor Author

/ok to test 1944635

prepare_for_generation now passes a timeout_s to _wake so the engine
transition can be bounded by the caller's remaining refit time. The
param-gather-hook test replaced _wake with a zero-argument lambda, so
it failed with "unexpected keyword argument 'timeout_s'". The stub now
accepts the argument; the assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@lauradang

Copy link
Copy Markdown
Contributor Author

/ok to test 88c9ed5

@lauradang lauradang 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 of this PR at head 88c9ed5ad. Items for me to fix are below.

Earlier threads. C1–C13 are fixed in the code and resolved. The one open part is the deadline half of C7, which is now C15.

Merge order. The Megatron unit-test shards are red on the pinned Megatron-LM; terrykong's C14 covers what to change. Merge this PR after the Megatron-Bridge bump (#5427).

Open question. jthomson04's question (aggregated Megatron behind Dynamo, and the class name) has no reply yet. Answer it on the PR.

Follow-up (not for this PR). MegatronGeneration.nvlink_domain_span still has a dynamo branch (megatron_generation.py#L86-L87). This PR works around it by setting dynamo=False for each engine (dynamo_generation.py#L94-L96). A MegatronDynamoGeneration.nvlink_domain_span, picked through megatron_generation_cls, would let that branch go. Callers that use the class name today: setup.py#L619 and grpo.py#L1425.

To do:

  1. (C15) Pass the refit deadline from the synchronizer to the workers, and make the worker safe when it fires.
  2. (C16) Move the policy.quant_cfg refusal into validate_settings and give the reason.
  3. (C18) Add the nine mid-transition suspend/resume tests.
  4. (C19) Update the stale comment about the removed Dynamo worker class.
  5. (C20) Remove is_pickled_copy and _attempt's unused return value.
  6. (C21) Index the required mcore_generation_config directly.
  7. (C22) Test a filled generation config with no role.

Linter. ruff clean; the Lint job is green at 88c9ed5ad.

nemo-rl-review: kind=self harness=claude-code/2.1.329 model=claude-opus-5-5 effort=medium review-pr-team=v3 reviewed=88c9ed5

Comment thread nemo_rl/models/policy/lm_policy.py Resolved
- C15: the Megatron weight synchronizer passes the refit deadline to the
  Dynamo engines' suspend/resume, and MegatronGeneration forwards
  timeout_s to its workers, so a stuck transition gives up at the deadline.
- C16: the policy.quant_cfg refusal moves from Policy.__init__ to
  MegatronDynamoGeneration.validate_settings (quantized prefill/decode
  engines are not supported).
- C18: tests for suspend/resume from every mid-transition engine state.
- C19: stale comment about the removed Dynamo worker class.
- C20: drop the test-only is_pickled_copy property and _attempt's unused
  return value.
- C21: index the required mcore_generation_config directly.
- C22: test a filled generation config with no role.
- Tests that need InferenceConfig.disaggregation_role are strict xfails
  until the Megatron-LM pin has it; the integration-check test patches in
  an InferenceConfig with the field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@lauradang

Copy link
Copy Markdown
Contributor Author

Reviewed at 1e6a042 for the Dynamo side. It still needs the rebase onto #4801's head, so I skipped the refit rank code. +1 to Terry's C10: one worker class matches how the vLLM worker handles Dynamo.

One design question. Is aggregated Megatron behind Dynamo planned? This PR makes dynamo: true mean prefill/decode only: dynamo_config.py:242 refuses it without disaggregation, and the role has no aggregated value. The vLLM path on main and Megatron-LM's own integration (--role aggregated) both serve aggregated engines. Nothing in dynamo_generation.py is Dynamo-specific; it is a fleet of one-engine MegatronGenerations with refit fan-out. If aggregated is coming, I'd either let this class take an aggregated role (#4801's plan_engines already returns it, and C10's fallback hooks give it the plain engine), or name the class for the P/D fleet so Dynamo serving can attach to MegatronGeneration later.

@jthomson04 Aggregated Megatron behind Dynamo isn't planned. For aggregated serving, Megatron keeps using MegatronGeneration without Dynamo, so in this stack dynamo: true on the Megatron backend only ever means prefill/decode. That's enforced up front: validate_megatron_dynamo_generation refuses dynamo: true without disaggregation.enabled, with an error that says aggregated engines behind Dynamo aren't supported. Because of that I'd keep the name MegatronDynamoGeneration. Its docstring also already says it owns one engine per prefill or decode role

@svcnvidia-nemo-ci svcnvidia-nemo-ci added complexity:high Large or cross-cutting change. Set by Autobot PR classify (skills/pr-classify) convergence-risk:high Likely to change training results. Set by Autobot PR classify (skills/pr-classify) proof:functionality Needs proof that it works. Set by Autobot PR classify (skills/pr-classify) labels Dec 2, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the proof:convergence Needs convergence proof (W&B runs). Set by Autobot PR classify (skills/pr-classify) label Dec 2, 2026
@lauradang

Copy link
Copy Markdown
Contributor Author

/ok to test 54228a0

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the proof:perf Needs performance proof. Set by Autobot PR classify (skills/pr-classify) label Dec 2, 2026
…ence client

Only rank zero has an inference client. The suspend/resume steps read
self.inference_client.<signal> on every rank to build the send callback,
so the other ranks raised AttributeError at once. They then entered the
ranks' failure all_reduce while their engine still had a suspend to run.
The suspend's device synchronize blocked behind that all_reduce, and
rank zero waited for that engine, so the run deadlocked until the NCCL
timeout. The send callbacks now reach for the client only when called.

On the other ranks, resume also tolerates rank zero's UNPAUSE landing
before the rank looks at the engine again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@lauradang

Copy link
Copy Markdown
Contributor Author

/ok to test de49d57

terrykong
terrykong previously approved these changes Dec 2, 2026
@terrykong
terrykong dismissed their stale review December 2, 2026 19:14

Re-approving after turning on auto-merge.

@terrykong
terrykong enabled stacked auto-merge (squash) December 2, 2026 19:15
@terrykong
terrykong merged commit 75d9ebc into main Dec 2, 2026
101 checks passed
@terrykong
terrykong deleted the laurad/pd-sc-2-refit-channel branch December 2, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) complexity:high Large or cross-cutting change. Set by Autobot PR classify (skills/pr-classify) convergence-risk:high Likely to change training results. Set by Autobot PR classify (skills/pr-classify) proof:convergence Needs convergence proof (W&B runs). Set by Autobot PR classify (skills/pr-classify) proof:functionality Needs proof that it works. Set by Autobot PR classify (skills/pr-classify) proof:perf Needs performance proof. Set by Autobot PR classify (skills/pr-classify)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants