Skip to content

feat(megatron): serve NeMo-Gym through the Dynamo frontend's chat engine - #5097

Open
lauradang wants to merge 9 commits into
laurad/pd-sc-5-wire-upfrom
laurad/pd-sc-6-gym-proxy
Open

lauradang wants to merge 9 commits into
laurad/pd-sc-5-wire-upfrom
laurad/pd-sc-6-gym-proxy

Conversation

@lauradang

@lauradang lauradang commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

What this is

PR 6 of the Megatron prefill/decode stack: NeMo-Gym rollouts on the Megatron engines behind the Dynamo frontend, served the same way main serves them for vLLM.

Gym sends every chat call to the one frontend URL. The frontend's chat engine (NemoRLChatEngine, now shared by both backends) renders the call in RenderPool worker processes, splices earlier turns' exact token ids, and routes the final token ids through Dynamo's KV router to the prefill and decode engines. Rendering happens before routing so the router sees final token ids and can route by cached prefix.

For Megatron, rendering and reply building come from Megatron-LM's public ChatRenderer (NVIDIA/Megatron-LM#9579), the same code Megatron-LM's own chat endpoint runs. NeMo RL wraps it instead of copying the endpoint's private helpers.

NeMo-Gym on Megatron P/D engines through the frontend's chat engine

Numbered steps are one Gym call: chat into the frontend (1), render in a RenderPool worker through ChatRenderer (2), prefix read from TransferQueue when token capture is on (3), splice, BOS policy and clamp, then token ids to the router (4), prefill leg (5), decode leg with the KV pull (6), capture staged once from the decode engine (7), one result chunk back (8), reply built with ChatRenderer.build_response (9).

What it changes

  • Shared frontend pieces: the chat engine, render pool, frontend wrapper and generation-cut fan-out move from dynamo/vllm/ to dynamo/, behind a ChatBackend seam (sampling checks, prompt preparation, error replies) and a RenderWorker seam (render, respond). dynamo/vllm/chat_backend.py holds the vLLM side, and its behaviour is unchanged. generation_cut_route.py and the backend-neutral prompt preparation (gym_prompt.py) move up to generation/.
  • dynamo/megatron/chat_backend.py: MegatronRenderer wraps ChatRenderer (render(..., with_history, add_bos=None), build_response). MegatronChatBackend.prepare_prompt splices first, using ChatRenderer's end-of-turn ids, then applies ChatRenderer.apply_bos_policy, then clamps, in the same order as Megatron-LM's endpoint.
  • dynamo/megatron/adapter.py: NemoRLMegatronLLMEngine, a subclass of Megatron-LM's Dynamo adapter. It registers the chat settings with the engine, runs prefill legs unchanged, and serves Gym decode legs: it generates, stages token capture once, and answers with one chunk carrying the result.
  • Engines: no engine starts an HTTP server behind Dynamo. Engines attach neither prompt_preparer nor payload_stager, so Megatron-LM's own hooks cannot also splice or stage. Only the decode engine's rank zero builds a TransferQueue stager.
  • Removed: the per-engine Gym proxy (megatron/dynamo_gym_proxy.py, FrontendInferenceClient) and its port reservations.
  • MegatronDynamoGeneration: client_base_urls returns the frontend; chat settings and capture settings are published to the frontend; setup_token_capture is supported (text only).
  • Guide, design doc and exemplar recipe updated.

Depends on

Not in this PR

  • Multimodal Gym calls: Megatron-LM's Dynamo adapter takes token ids only, so media calls are refused.
  • Generation cuts at checkpoints: Megatron has no prefix recovery yet.
  • Router-replay routes and top-k log-probs for Gym calls.
  • A GPU functional test. Still to confirm on a real run: the prefill router forwards annotations and extra_args to the decode leg, and the decode leg's result reaches the chat engine.

Stack

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

All six PRs now include main 047d885 through merge commits.

Tests

New test_dynamo_megatron_chat_backend.py and test_dynamo_megatron_adapter.py; updated Megatron Dynamo generation, worker mixin, config, setup and decoupling tests. On CPU with a Megatron-LM checkout that has ChatRenderer: 568 passed. The vLLM and ai-dynamo frontend suites need those packages and were not run locally.

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)
  • Did you add or update any necessary documentation?

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Nov 5, 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.

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Nov 5, 2026
@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
lauradang force-pushed the laurad/pd-sc-6-gym-proxy branch from a9e5c4d to ffe29b2 Compare November 6, 2026 22:38
@copy-pr-bot

copy-pr-bot Bot commented Nov 6, 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.

…ntend

With policy.generation.dynamo=true and mcore_generation_config.expose_http_server=true,
each engine's rank zero serves NeMo-Gym as it does without Dynamo: Megatron-LM's
OpenAI endpoints (chat template, parsers, exact-prefix splice) run over a client that
posts token-id completions to the Dynamo frontend instead of this engine's coordinator,
so the frontend routes every Gym call across the prefill and decode engines. One server
address per engine is reserved before the engines exist, on the node each engine is
pinned to. NeMo-Gym itself is unchanged.

Token capture stays refused on this path: the capture admission is request metadata,
which a completion through the frontend does not carry to the engines.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@lauradang
lauradang force-pushed the laurad/pd-sc-6-gym-proxy branch from ffe29b2 to 61347ad Compare November 7, 2026 05:12
@lauradang
lauradang marked this pull request as ready for review November 10, 2026 20:05

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review

The review covers all 11 changed files and the directly affected reservation, startup, refit and rollout paths.

Suggestions

  1. (C1) Reject HTTP replica counts that the new proxy doesn't implement.
  2. (C2) Add the new proxy suite to an executing CI lane.
  3. (C3) Include the new source module in the explicit type-check list.

Validation and limits

No tests or linters were executed, and live CI results weren't available. The Megatron-Bridge submodule directory is empty in this snapshot, so the real Megatron endpoint contracts and Hypercorn integration remain unverified. All three local reviewers completed, but two reports weren't delivered; I directly inspected their client-contract and driver/configuration topics.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

model_name=str(generation_cfg["model_name"]),
request_timeout_s=frontend["request_timeout_s"],
)
app = build_gym_proxy_app(

Copy link
Copy Markdown
Contributor

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 — [GUIDELINE] Reject unsupported HTTP replica counts instead of silently starting one server.

PR-introduced configuration-handling issue, confidence 95. With Dynamo and HTTP serving enabled, setting the existing HTTP replica option to 4 passes validation, but this startup path always creates one app and one server task. The native path forwards the configured count. An accepted explicit setting should describe the server actually started, following the rule against silently ignoring user configuration.

AI-1

Action: Reject explicit counts other than one in the Dynamo generation validator, until this path implements replicas. The correction targets a different file than this anchor, so this is an insertion sketch rather than a committable suggestion. Insert after the local server configuration is assigned:

if (
    mcore["expose_http_server"]
    and "http_server_num_replicas" in mcore
    and int(mcore["http_server_num_replicas"]) != 1
):
    raise ValueError(
        "mcore_generation_config.http_server_num_replicas must be 1 "
        "when exposing the NeMo-Gym server with policy.generation.dynamo=true"
    )

Acceptance — proposed, not run: Extend the HTTP configuration acceptance case: an omitted count or a count of one remains accepted; four raises before worker construction. HTTP serving disabled must remain accepted with an otherwise unused replica setting. Keep native multi-replica forwarding unchanged, and retain the reserved-port and allocated-port cases, including their sampling-default and cancellation assertions. Verify the suggested guard before adopting it.

failed_record,
)

URL = "http://10.0.0.1:3000/v1"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

C2 · 1 action item.

TL;DR — [TEST] The new proxy suite has no executing CI lane because it lacks the Megatron marker.

PR-introduced test-selection failure, confidence 100. This module has no module or function-level Megatron marker. The Megatron jobs use the mcore-only filter, which removes unmarked tests. The base generation job's filename patterns don't match this filename, and the base model job excludes the generation directory. Consequently, the new request, response and server tests aren't exercised by the unit-test plan.

AI-1

Action: Add the same module marker used by the neighboring Dynamo rollout suite:

Suggested change
URL = "http://10.0.0.1:3000/v1"
pytestmark = pytest.mark.mcore
URL = "http://10.0.0.1:3000/v1"

Acceptance — proposed, not run: Collect this module with the existing Megatron job's options and confirm that its tests remain selected, then run it in that environment. Preserve the sampling and reply assertions, cancellation assertions, and server assertions; this correction should change selection, not their behavior. Report any skipped streaming case as skipped, not passed. Verify the suggestion before adopting it.

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""NeMo-Gym's OpenAI server for Megatron engines behind the Dynamo frontend.

Copy link
Copy Markdown
Contributor

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 — [GUIDELINE] Add the new proxy module to the explicit type-check list.

PR-introduced validation gap, confidence 100. This new module isn't listed beside the other checked Megatron Dynamo modules. The type-check hook does not pass changed filenames, so adding the source file doesn't automatically add it to routine checking. The protected contribution rule requires new modules to join this list.

AI-1

Action: Add this entry to the existing project-includes list, next to the Dynamo generation entry. This targets a different file than the anchor, so it isn't a committable suggestion here:

  "nemo_rl/models/generation/megatron/dynamo_gym_proxy.py",

Acceptance — static check plus proposed validation, not run: Confirm that the entry is active inside the list, then run the repository's normal pre-commit checks and resolve diagnostics introduced by this module. Keep the existing checked-file entries and backend import substitutions unchanged; the invariant is that the new module receives the same routine type checking as its neighboring Dynamo modules.

lauradang and others added 5 commits November 13, 2026 18:26
Each Gym request through the frontend-backed engines failed. Fixes:
- serve the endpoints without hypercorn's signal handlers (they run on
  the inference-loop thread, not the main thread) and stop closing the
  adopted socket twice;
- accept the endpoints' offload_params keyword and give the client a
  multimodal_prompt_config, so later turns no longer return a 500;
- report 408/429 as transient after the retries run out;
- send no stop_token_ids for ignore_eos and keep the frontend's
  finish_reason, so an EOS on the last budgeted token is not "length";
- refuse echo together with logprobs, add the profiler no-op, and fail
  fast when Megatron-LM's endpoint list is empty;
- type the frontend handle, fix stale docstrings, add the mcore marker
  to the proxy tests and the module to pyrefly.

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_generation.py
#	tests/unit/models/generation/test_megatron_dynamo_config.py
#	tests/unit/models/generation/test_megatron_dynamo_generation.py
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
Gym calls for Megatron P/D engines now go to the one Dynamo frontend URL,
like the vLLM path: the shared NemoRLChatEngine renders each call in
RenderPool worker processes, splices earlier turns, and routes final token
ids through the KV router. The Megatron renderer wraps Megatron-LM's public
ChatRenderer (render, EOS ids, BOS policy, build_response) instead of
copying its chat endpoint.

- Move the backend-neutral chat engine, render pool, frontend wrapper and
  generation-cut fan-out out of dynamo/vllm/ behind ChatBackend and
  RenderWorker seams; vLLM keeps identical behaviour.
- Add dynamo/megatron/{chat_backend,adapter}.py: MegatronRenderer over
  ChatRenderer; NemoRLMegatronLLMEngine serves Gym decode legs and stages
  token capture once from the decode engine's rank zero.
- Remove the per-engine Gym proxy (dynamo_gym_proxy.py) and its port
  reservations; engines start no HTTP server behind Dynamo.
- Behind Dynamo no engine attaches prompt_preparer/payload_stager; only
  decode rank zero builds a TQ stager.
- Allow token capture for Megatron behind Dynamo (text only).

Needs a Megatron-LM pin with ChatRenderer (NVIDIA/Megatron-LM#9579).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
@lauradang lauradang changed the title feat(megatron): serve NeMo-Gym from the engines behind the Dynamo frontend feat(megatron): serve NeMo-Gym through the Dynamo frontend's chat engine Nov 19, 2026
Found running the frontend chat engine on GPUs (4-node Nano 3.5 run):

- Megatron engines registered only the completions endpoint, so Dynamo
  never built the chat route and every NeMo-Gym chat call got a 404.
  Register chat too when the frontend serves NeMo-Gym's calls
  (mcore_generation_config.expose_http_server), as the vLLM path does.
- The prefill leg of a NeMo-Gym call ran with the frontend's router-only
  sampling. Prefill samples the call's first token and hands its log
  probability to decode, which rejected every handoff ("invalid
  first-token log probability count: expected 1, got 0"); the first
  token was also sampled with the wrong temperature and top_p. Give the
  prefill leg the call's sampling as well.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
lauradang and others added 2 commits November 20, 2026 17:53
Main's Dynamo 1.8 frontends load NeMo RL's chat engine as a custom chat
processor and its generation-cut route as a route extension, so the
frontend.py wrapper this branch moved is gone. On top of the merge:

- The chat engine, its render pool and the cut route stay backend-neutral
  under dynamo/: CHAT_PROCESSOR and CUT_ROUTES point there.
- The backend the chat engine serves rides in ChatProcessorOptions
  (chat_backend) instead of NEMO_RL_DYNAMO_CHAT_BACKEND; the runtime hands
  it to every frontend host.
- The shared render pool's workers exit with their frontend, as main's vLLM
  pool's now do.
- MegatronDynamoGeneration publishes its chat settings to every frontend,
  gives NeMo-Gym every frontend URL and drops generation_cut_control_urls,
  which main removed.
- The Megatron Worker keeps configure_logging=False.

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

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)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants