Skip to content

feat(megatron): host Megatron-LM's Dynamo adapter on each engine's rank zero - #5023

Open
lauradang wants to merge 40 commits into
mainfrom
laurad/pd-sc-3-adapter-sidecar
Open

lauradang wants to merge 40 commits into
mainfrom
laurad/pd-sc-3-adapter-sidecar

Conversation

@lauradang

@lauradang lauradang commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

What this is

PR 3 of 6: the prefill and decode Megatron engines register with the Dynamo frontend. Rank 0 of each engine runs Megatron-LM's Dynamo adapter inside its own process (no sidecar), at the same point the new vLLM Dynamo path starts NativeVllmEngine: once the engine is built.

One request: frontend → prefill rank 0 → KV handoff → decode rank 0 → frontend

What it adds

On each engine (MegatronDynamoGenerationMixin, dynamo_worker_mixin.py)

  • start_dynamo_endpoint (rank 0) builds the adapter's Config in external mode for the engine's configured role, picks node-local event and system ports, and runs dynamo.common.backend.Worker(MegatronLLMEngine(...)) as a task on the engine's inference loop. A repeat call returns the same endpoint.
  • attach_dynamo_events points every rank's event reporter at the adapter. Rank 0 sends "ready" with its coordinator address, and that registers the engine. The reporter is kept only after "ready" is sent, so a failed attach can be retried. A repeat call naming a different adapter address is refused.
  • dynamo_endpoint_error reports why the endpoint task ended (cancelled, exited, or its exception); a start after that is refused with the reason.
  • stop_dynamo_endpoint cancels the endpoint task and shuts down rank 0's event reporter. Cancelling skips Dynamo's graceful drain, and the discovery entry lapses only when the process exits; the docstrings say so. Dynamo serves one Worker per process, so a second start in the same process is refused.

On the controller (MegatronDynamoGeneration)

  • Starts etcd, NATS and the frontend from the engines' own environment through ManagedDynamoRuntime, right after the engines and in the order the vLLM backend uses.
  • The first resume after a refit is when the engines start: that refit built them. The resume starts each engine's endpoint through the workers' handles, then waits until the frontend lists every component and the model. The controller's pickled copy has no service processes, so it does this check over HTTP only.
  • expected_components, engine_python and check_alive support that wait; check_alive also raises, naming the engine, once an endpoint task has stopped, so the wait fails at once instead of at the startup timeout.
  • Teardown stops each engine's endpoint (bounded by the control timeout) before its policy, then stops the services.

Runtime split

  • ManagedDynamoRuntime (managed_runtime.py) now only runs services (etcd, NATS, frontend), and engines register with it themselves, as on the native vLLM engine path. It waits for either a total engine count or a count per component.
  • The dynamo.vllm subprocess setup behind DynamoGeneration keeps the previous class, renamed LegacyManagedDynamoRuntime (legacy_managed_runtime.py) and marked deprecated. It behaves exactly as before.

Dependency: ai-dynamo==1.5.1 and ai-dynamo-runtime==1.5.1 join the mcore extra so the adapter imports from the engine's own environment; uv.lock regenerated with the uv version pinned in the Dockerfile. ai-dynamo-runtime 1.5.1 pins pydantic 2.13.0, so the mcore extra now resolves pydantic 2.13.0 (pydantic-core 2.46.0) while the driver and the other extras stay on 2.13.5.

First refit: weights in, engines built, then rank 0 starts the endpoint and registers

Rollouts are not yet posted to the frontend, so validate_settings still refuses backend: megatron + dynamo: true; PR 5 turns it on.

Stack

main ← PR 1 (#4801) ← PR 2 (#4912) ← PR 3 (#5023, this) ← PR 4 (#5024) ← PR 5 (#5025) ← PR 6 (#5097)

Each PR is based on the one before it, so review each against its own base.

Tests

  • test_megatron_dynamo_worker_mixin.py: endpoint start/repeat/stop, start rejections, a failed or exited endpoint reporting why, event attach and retry, attach on a non-leader rank.
  • test_megatron_dynamo_generation.py: service start order, endpoint start on first resume, registration wait (runtime and HTTP-only copy) failing at once when an endpoint stops, teardown order with a bounded endpoint stop.
  • test_dynamo_managed_runtime.py / test_dynamo_legacy_managed_runtime.py: services-only runtime; legacy runtime unchanged.

Before your PR is "Ready for review"

  • 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? (CPU unit suites only; GPU path not yet run on this base)
  • Did you add or update any necessary documentation?

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Nov 2, 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-3-adapter-sidecar branch from 9dd85ca to f73800c Compare November 4, 2026 03:00
@lauradang lauradang changed the title feat(dynamo): adapter sidecar actor for Megatron engines behind Dynamo feat(megatron): host Megatron-LM's Dynamo adapter on each engine's rank zero 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-3-adapter-sidecar branch from f73800c to e7716c5 Compare November 4, 2026 03:39
@lauradang
lauradang force-pushed the laurad/pd-sc-3-adapter-sidecar branch from e7716c5 to e7c8156 Compare November 4, 2026 05:36
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-3-adapter-sidecar branch from e7c8156 to 33e004b Compare November 5, 2026 09:26
@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Nov 5, 2026
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-3-adapter-sidecar branch from 33e004b to a6808da Compare November 5, 2026 09:27
@terrykong terrykong added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Nov 5, 2026
lauradang and others added 3 commits November 5, 2026 13:24
…namo tests mcore

MegatronDynamoGeneration.validate_settings now refuses
policy.router_replay.enabled: the KV handoff moves a prompt's cache from
a prefill to a decode engine but not its routing-replay buffers, and the
engine would otherwise refuse it only at the first refit, after every
cluster and engine is up.

MegatronGeneration.validate_settings refuses a user-supplied
generation._dynamo_role whether or not Dynamo is on. The role is written
into each engine's own config, which never comes back through
validation, so a role in the user's config is always a stray one that
would hand the trainer's policy the Dynamo engine worker. The duplicate
check that only ran with Dynamo on is gone.

The fleet no longer stores a refit membership nothing reads; the
suspend docstrings say the resume after a failed suspend is best-effort
and the original error still propagates. The three Dynamo test modules
carry pytest.mark.mcore so the Megatron CI shards collect them; the
worker-class choice in Policy and its quant_cfg refusal get tests;
public members of the engine record and the fleet get docstrings.

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

The prefill/decode engines now serve through Dynamo. Rank zero of each
engine hosts Megatron-LM's Dynamo adapter in-process once the engine is
built, as the vLLM worker starts its endpoint on an engine that already
serves: start_dynamo_endpoint builds the adapter's Config in external mode
for the engine's configured role, picks node-local event and system ports,
and runs dynamo.common.backend.Worker(MegatronLLMEngine(...)) as a task on
the engine's inference loop. attach_dynamo_events then points every rank's
event reporter at the adapter and rank zero sends "ready" with its
coordinator address, which is what registers the engine. A repeat start
returns the same endpoint; stop_dynamo_endpoint forgets it.

MegatronDynamoGeneration starts etcd, NATS and the frontend from the
engines' own environment through ManagedDynamoRuntime right after the
engines, in the order the vLLM backend uses. The first resume after a refit
is the engines' startup: that refit built them, so the resume starts their
endpoints engine by engine through the workers' handles (the controller's
pickled copy can run it too) and waits until the frontend lists every
component and the model, over the runtime or, on a copy without the service
processes, over HTTP alone. Teardown stops each engine's endpoint before its
policy, then the services.

ManagedDynamoRuntime becomes the services-only runtime engines register with
themselves (etcd, NATS, frontend; engine count or count per component), as
the native vLLM engine path has it. The dynamo.vllm subprocess fleet behind
DynamoGeneration keeps the previous class, renamed
LegacyManagedDynamoRuntime and marked deprecated. ai-dynamo joins the mcore
extra so the adapter imports from the engine's own environment.

Rollouts are still not posted to the frontend, so validate_settings keeps
refusing the switch.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
attach_dynamo_events keeps its reporter only once rank zero has sent "ready",
so a failed attach can be retried, and it refuses a repeat call that names a
different adapter address. It returns None like its siblings, and its
docstring now says that only rank zero's reporter connects.

Stopping an engine's Dynamo endpoint cancels Dynamo's Worker.run, which skips
its graceful path: no request drain and no adapter cleanup, and the discovery
entry only lapses when the process exits. The docstrings now say so, and the
stop also shuts down rank zero's engine event reporter. The stopped task stays
recorded, so a later start in the same process is refused because Dynamo's
runtime serves one Worker per process.

Also note that Dynamo's Worker installs its own SIGTERM/SIGINT handlers in the
actor process, and correct the pyproject comment to the real switch
(backend=megatron with dynamo: true).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
lauradang and others added 8 commits November 18, 2026 11:52
… for P/D engines

- Refit: `refit_transport: mcore` (with `refit_backend` nccl or gloo) moves
  Megatron-Core shards straight from each training rank to the engine ranks
  that hold them, as the aggregated Megatron engines do. Each engine joins
  the refit group at its own offset, so a TP 2 prefill engine and TP 1
  decode engines take one transfer. The packed collective stays the default.
- Prefill request cap: `dynamo_cfg.prefill_engine.max_requests` sizes
  prefill's request slots apart from decode's. A prefill engine holds each
  finished prompt in a slot until decode claims it, so a shared cap also
  throttled prefill. `EngineLayoutOverrides` is renamed `EngineRoleOverrides`
  now that it carries more than the layout.
- Decode role: each engine passes its role to Megatron-LM, which then builds
  a decode engine without a Mamba prefix cache (decode writes each handoff
  straight into live recurrent state, so a cache there is refused).

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

# Conflicts:
#	nemo_rl/models/generation/megatron/dynamo_config.py
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
Main now returns (train, inference, value, teacher_topology) from _build_clusters; the Megatron Dynamo replica-sizing test still unpacked three values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
Conflicts resolved as in the main merge onto PR 6 (a70778b135): managed_runtime.py keeps PR 3's ManagedDynamoCfg/FrontendArgs Protocols, repeated-flag refusal and per-component wait_for_engine_registrations on top of main's runtime (chat engine, render workers, ray_address); its tests and the decoupling allow-list keep both sides; pyproject keeps PR 3's ai-dynamo pins on the mcore extra next to main's vLLM 0.33 bump; uv.lock relocked from main's with uv 0.11.28 (revision 3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
Main's ManagedDynamoRuntime now takes ray_address and serves_chat and reads frontend_args.session_affinity_ttl_secs and render_workers. MegatronDynamoGeneration passes the GCS address and serves_chat=False (NeMo-Gym reaches Megatron engines through their own chat proxies), MegatronDynamoFrontendArgs gains both fields (session affinity off by default), and the test runtime fake takes the new arguments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
Main's lock lacked PR 3's ai-dynamo==1.5.1 / ai-dynamo-runtime==1.5.1 on the mcore extra. Relocked from main's lock with uv 0.11.28 (revision 3); lock --check passes with uv 0.11.28 and 0.13.6.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@lauradang
lauradang added this pull request to stack #5339 November 20, 2026 21:15
lauradang and others added 8 commits November 20, 2026 17:08
Add num_frontends, session_affinity_max_entries and extra_env as the vLLM
frontend args have them, and drop the power-of-two router Dynamo 1.8 removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
# Conflicts:
#	nemo_rl/algorithms/single_controller_utils/setup.py
Brings in main's Dynamo 1.8 frontends (one or more, as Ray actors on the
generation nodes). On top of the merge:

- The runtime keeps main's frontend hosts and takes the backend-neutral
  dynamo_cfg Protocols, now with num_frontends, session_affinity_max_entries
  and extra_env. wait_for_engine_registrations takes every frontend's URL
  and checks each in turn on /health?instances=true.
- MegatronDynamoGeneration starts the frontends on the engines' own nodes
  (the parent cluster's placement groups stay unmaterialized), keeps every
  frontend URL, and its controller copy waits on each.
- The mcore extra pins the same ai-dynamo nightly as the vllm extra: the
  frontend runs from the engines' venv and needs 1.8's chat-processor flags.
- The Megatron Worker runs with configure_logging=False, as vLLM's does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
Main now runs pyrefly 1.4.0 over every file under nemo_rl/ against a
baseline. In _refit_leaders_by_shard, per_shard was only assigned when
no membership is recorded and read through a conditional expression in
the loop, which pyrefly reports as a new unbound-name error. Build the
(shard, leader offset) pairs inside each branch instead; behaviour is
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
# Conflicts:
#	pyrefly.toml

@terrykong terrykong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

These comments come from the review of #4801, the first PR in this stack. They are staged here so they are not lost; please verify them before publishing.

Context. On main, vLLM + Dynamo (#4905, #4979) plugs in through DynamoEngineAdapter: a backend writes serve_rollout, start, abort and kv_event_sources, and the native worker keeps refit, pause and capture. The goal for this stack is the same shape for Megatron, with one prefill/decode interface that each backend fills in. The design (a class sketch and what each PR does) is C1 below. Comparison page: https://terrykong.github.io/gh-pages-poc/terryk/pr-4801-pd-one-interface.html. The vLLM design it mirrors: https://terrykong.github.io/gh-pages-poc/terryk/pr-4905-one-chat-path.html.

  1. (C1) Base the Megatron Dynamo adapter on main's DynamoEngineAdapter, not Megatron-LM's MegatronLLMEngine.

  2. (C2) The fake worker takes **kwargs for the four Dynamo calls, so a renamed worker argument still passes the tests; bind each call to the real method's signature.

  3. (C3) After #4801, Megatron's config has no render_workers or session_affinity_ttl_secs; keep them off it and have each backend pass them to ManagedDynamoRuntime instead.

  4. (C4) The generate / generate_async docstrings still say the engines register with no frontend; match them to the updated error messages.

  5. (C5) Two engine ports are picked, released, then bound later, so another process can take one in between; when moving to C1's adapter, keep DYN_SYSTEM_PORT="0" and drop the event port.

Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-5023-engine-registration.html

Generated by Claude Code

Comment on lines +317 to +327
engine = MegatronLLMEngine(config, registration_model)
# This is NeMo RL's process: Dynamo's setup would replace its root
# handler and level.
worker_config = dataclasses.replace(
MegatronLLMEngine.worker_config(config, registration_model),
configure_logging=False,
)
# Dynamo's Worker installs SIGTERM/SIGINT handlers in this actor
# process and, on those signals, shuts the adapter down its own way
# (it force-exits the process if that overruns its deadline).
await Worker(engine, worker_config).run()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

C1 · 1 action item.
TL;DR — rank 0 runs Megatron-LM's own Dynamo adapter here, and #5097 later subclasses it, instead of main's DynamoEngineAdapter. Build a DynamoMegatronAdapter(DynamoEngineAdapter) so Megatron + Dynamo mirrors vLLM + Dynamo, and so capture, routed experts and generation cuts go through the native worker.

On main, DynamoEngineAdapter writes the Dynamo side once: _handlers() picks a handler per request kind, _generate_rollout returns RolloutResult (routed experts included), and start_dynamo_endpoint registers the engine. DynamoVllmAdapter writes only serve_rollout, start, abort and kv_event_sources, so the native worker keeps refit, pause and capture. Here, MegatronLLMEngine reaches the engine through Megatron-LM's own coordinator (engine_launch_mode="external"), and #5097's NemoRLMegatronLLMEngine subclasses it. Because capture skips the native worker, #5097 has to refuse routed experts and refuse generation cuts.

AI-1

Add nemo_rl/models/generation/dynamo/megatron/adapter.py with this shape, and build it here on rank 0 in place of MegatronLLMEngine (sketch, not exact signatures):

class DynamoMegatronAdapter(DynamoEngineAdapter):
    def start(self):
        # Register this engine (role prefill or decode) through main's
        # start_dynamo_endpoint, as DynamoVllmAdapter does.
    def serve_rollout(self, request, handoff=None):
        # Run the native Megatron worker's generate step, so capture, routed
        # experts and generation cuts work the same as without Dynamo.
        # A decode engine first reads `handoff`: the KV blocks prefill pinned.
    def serve_prefill(self, request):
        # Prefill engines only: run prefill, pin its KV blocks, and return the
        # handoff that Dynamo passes on to decode (disaggregated_params).
    def release_handoff(self, handoff):
        # Unpin the blocks once decode has read them.
    def abort(self, request_id): ...
    def kv_event_sources(self): ...

Call Megatron-LM's code that claims, sends and releases KV blocks from inside serve_prefill, serve_rollout and release_handoff; don't subclass MegatronLLMEngine. serve_prefill, the handoff argument and release_handoff are new optional hooks on DynamoEngineAdapter. Add them in this PR, because this is where each engine's prefill/decode handler is set up; vLLM can implement the same hooks later.

The rest of the stack then follows:

See it worked out: draft terrykong/RL#58 builds this on top of this PR (a proposal, not for merging; releasing and claiming handoffs are stubs until Megatron-LM makes those two calls public). Pictures: the classes side by side, with what each comment changes and one request three ways: vLLM on main, this PR, after this comment.

Not a suggestion block: it is a new class across files.

Context from the #4801 stack review

On main, vLLM + Dynamo (#4905, #4979) plugs in through DynamoEngineAdapter: a backend writes serve_rollout, start, abort and kv_event_sources, and the native worker keeps refit, pause and capture.

Terry's goal is one P/D (prefill/decode) interface, written once and stamped out per backend, so Megatron + Dynamo should look like vLLM + Dynamo.

Pictures of both: one P/D interface for every backend and the vLLM design to mirror.

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.

Re C1: I'd rather keep Megatron-LM's adapter and fix the gaps there.

Why not #58:

  1. It copies Megatron-LM's handoff protocol into NeMo RL. That's serve_prefill, _decode_from and _publish_kv_event, and the claim/release stubs need about 70 more lines of private HandoffChannel code. Megatron-LM changes that code often, and we'd have to port every change by hand.
  2. The native worker doesn't unblock the refused features. Routed experts are blocked in Megatron-LM's handoff, which doesn't carry prompt routes (inference_state_handoff.py:310); torch.compile #58 also returns routed_experts=None. Native Megatron refuses generation cuts too.

Instead, four small Megatron-LM changes:

  • a result hook, so we return engine_data.rollout like vLLM;
  • a sampling hook, so we build SamplingParams with the native builder from the rollout annotation, as vLLM does;
  • routes carried in the handoff;
  • an attached mode, which drops the event socket and port plumbing.

On matching vLLM's class shape: DynamoEngineAdapter's slots assume the backend returns one finished result from serve_rollout, and that the base class releases the KV separately via release_handoff. MegatronLLMEngine.generate does claim, read, stream and release in a single call, so filling those slots means copying its internals. If we want both backends as DynamoEngineAdapter subclasses, I'd add one slot to the base class that streams a whole request:

class DynamoEngineAdapter:
    async def generate(self, request, context):
        rollout = parse_annotation(request)
        async for chunk in self.serve(request, rollout, context):
            yield chunk                       # base packs engine_data.rollout

    async def serve(self, request, rollout, context):
        ...  # default: today's serve_prefill / serve_rollout / release_handoff (vLLM unchanged)

class DynamoMegatronAdapter(DynamoEngineAdapter):
    async def serve(self, request, rollout, context):
        async for chunk in self._mlm.generate(request, context):   # Megatron-LM owns the handoff
            yield chunk

That's the same class shape for both backends, with no copied protocol code. Since it only changes how the code is organized, I'd do it as a follow-up.

Comment on lines +78 to +81
# Idle seconds a NeMo-Gym session stays on one engine; None disables it.
session_affinity_ttl_secs: Annotated[int, Field(gt=0, le=31_536_000)] | None = None
# Processes in the frontend that render chat calls; see the vLLM dynamo_cfg.
render_workers: PositiveInt = 8

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

C3 · 1 action item.
TL;DR — after #4801 C10, Megatron's frontend_args has no render_workers or session_affinity_ttl_secs. This PR adds both back only because the new runtime reads them for every backend, and neither does anything on Megatron until #5097 turns chat on.

So once this PR is rebased onto #4801, either the two keys come back on Megatron's config and do nothing, or the runtime fails when it reads them.

AI-1

When rebasing onto #4801, leave render_workers and session_affinity_ttl_secs off Megatron's config, trim FrontendArgs to the fields DynamoFrontendArgsBase has, and have each backend pass those two vLLM-only values to ManagedDynamoRuntime, with chat_render_workers replacing its serves_chat argument:

        # From vLLM's dynamo_cfg.frontend_args; Megatron passes None until #5097.
        session_affinity_ttl_secs: int | None,
        # Render workers for NeMo RL's chat engine; None when the engines serve
        # no chat, so the frontend gets no chat settings file.
        chat_render_workers: int | None,

vLLM passes its session_affinity_ttl_secs and, when it serves chat (vllm_generation.py L827), its render_workers, so vLLM runs behave as today. Keep self.serves_chat = chat_render_workers is not None, since vllm_generation.py L771 reads it. #5097 then passes Megatron's values when it turns chat on. Not a suggestion block: it spans managed_runtime.py and both backends.

Comment on lines +264 to +280
event_port = _get_free_port_local(
DEFAULT_DYNAMO_SYSTEM_PORT_RANGE_LOW,
DEFAULT_DYNAMO_SYSTEM_PORT_RANGE_HIGH,
max_retries=None,
excluded_ports=used,
)
used.add(event_port)
system_port = _get_free_port_local(
DEFAULT_DYNAMO_SYSTEM_PORT_RANGE_LOW,
DEFAULT_DYNAMO_SYSTEM_PORT_RANGE_HIGH,
max_retries=None,
excluded_ports=used,
)
# A fresh owner per launch: prefill pins KV blocks per decode owner.
handoff_owner = uuid.uuid4().hex if role == "decode" else None
# The Rust runtime reads these when the first Worker is constructed.
os.environ.update({**manager_env, "DYN_SYSTEM_PORT": str(system_port)})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

C5 · 1 action item.
TL;DR — both ports here are picked, released, then bound later by another component, so anything on the node can take one in between; a lost race fails the endpoint for good ("restart the engine"). With C1's adapter neither port needs picking: keep DYN_SYSTEM_PORT="0" and drop the event port.

_get_free_port_local binds a port only long enough to learn its number. Here the two numbers are used much later:

  • DYN_SYSTEM_PORT is bound by Dynamo's Rust runtime when Worker.run starts, after fetch_model. This line also overrides the runtime's DYN_SYSTEM_PORT: "0", where the OS picks a free port at bind time and nothing can race it. vLLM engines keep "0".
  • The event port is bound by Megatron-LM's event receiver inside the adapter's start(), also after fetch_model.

If another process on the node takes either port in that gap, Worker.run fails, dynamo_endpoint_error turns non-None, and every later start is refused. The repo has fixed this pattern before (#2380, port holders kept bound until the server starts in grpo.py).

AI-1

When moving to C1's DynamoMegatronAdapter, don't carry these ports over:

  • Register through main's start_dynamo_endpoint with the runtime's engine_env unchanged, so DYN_SYSTEM_PORT stays "0".
  • The adapter runs in the engine's own process and calls the worker directly, so there is no event socket to bind: delete both _get_free_port_local calls, the DEFAULT_DYNAMO_SYSTEM_PORT_RANGE_* constants and the [4000, 4100) port-map line.

Not a suggestion block: it spans this file, virtual_cluster.py and the controller's excluded_ports bookkeeping.

Ports that are already claimed safely (no change needed)

@terrykong terrykong removed the Documentation Improvements or additions to documentation label Nov 28, 2026
Base automatically changed from laurad/pd-sc-2-refit-channel to main December 2, 2026 19:15
lauradang and others added 2 commits December 4, 2026 00:49
…the frontend

The generate / generate_async docstrings still said the engines register
with no frontend; match them to the error messages below them.

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

The fake engine took **kwargs for start_dynamo_endpoint,
attach_dynamo_events, stop_dynamo_endpoint and dynamo_endpoint_error, so a
renamed worker argument still passed. Each call is now bound to the real
MegatronDynamoGenerationMixin method before dispatch; renaming
start_dynamo_endpoint's engine_start_timeout_s fails 9 tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@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: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) labels Dec 4, 2026
main now carries the engine-refit-channel PR (squash-merged), so this
merge takes main and reapplies this PR's changes on top, resolved as in
the review-fix branch. uv.lock relocked with uv 0.13.6: only the
ai-dynamo / ai-dynamo-runtime entries for the mcore extra are added.

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 4965ccf

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: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.

3 participants