How a NeMo-Gym call runs on Megatron engines: the same chat engine as vLLM, with a Megatron backend

PR #5097 (part 6 of 6, reviewed against #5025 at 62868966) · permalinks at head e6beabe5, base e85af6c2

Before
With backend: megatron and dynamo: true, NeMo-Gym could not run: setup refused expose_http_server: true (base check). Only vLLM served Gym's chat calls behind Dynamo, through a chat engine that lived in dynamo/vllm/.
This PR
Moves that chat engine up to dynamo/, behind backend hooks, and adds a Megatron backend. It renders and builds replies with Megatron-LM's ChatRenderer, and serves Gym's decode leg in a subclass of Megatron-LM's Dynamo adapter.
Status
New path, review open. It cannot serve a call until the Megatron-LM pin includes ChatRenderer (C1). Three steps behave differently from vLLM or from Megatron-LM's own endpoint (C3, C4, C5). Server faults reach Gym as "bad request" (C2, second page).

Four pages for this PR, one question each: this one compares the backends. The first two chips are earlier parts of the same stack.

Background. NeMo-Gym runs agent environments. Its agents call the policy model over an OpenAI-style chat API. To keep training exact, NeMo RL turns each chat into token ids itself and pastes in the model's own token ids from earlier turns (token capture). Dynamo's frontend is one HTTP server in front of a prefill engine and a decode engine. Dotted words have a short explanation: hover or tap them.

Both backends now run through one function, NemoRLChatEngine._serve. It calls the backend at four points: the sampling check ②, the render ③ (in render worker processes), the prompt preparation ④, and the reply ⑨. The final token ids go through Dynamo's router to the engines, whose adapter on rank zero runs the call and writes the capture to TQ once. The numbers below are the PR's own unit-test values: chat template [1,7,2,3,4], EOS id 2, context limit 16 tokens.

One call, two backends

NeMo-Gym agent① one chat call to the one frontend URL (POST /v1/chat/completions){messages:[user, assistant (turn 1), user], ng_capture:{mode:"token_in"}}Dynamo frontend process (one per run)NemoRLChatEngine._serve— one shared engine; each step calls the backend's hookvLLM backend · VllmChatBackendMegatron backend · MegatronChatBackend (new)② checked_sampling② checked_samplingon_policy_sampling: off-profile trained call→ 400 refusedfills omitted fields only (del on_policy)off-profile call → served [C3]③ render (RenderPool worker process × N)③ render: ChatRenderer.render(add_bos=None)template [1,7,2,3,4]history [1,7,2]template [1,7,2,3,4]history [1,7,2]④ prepare_prompt: splice, then clamp④ prepare_prompt: splice, BOS rule, clampmodel's prefix [1,5,6,2] (read from TQ)splice at EOS 2 → [1,5,6,2,3,4]clamp: 16 − 6 → max_tokens 10model's prefix [5,6,2] (read from TQ)splice at EOS 2 → [5,6,2,3,4]BOS rule, add_BOS always off [C5]clamp: 16 − 5 → max_tokens 11⑤ token ids + annotation nemo_gym:rollout + extra_args.ForwardedCall → Dynamo KV router → prefill, then decode⑨ respond: vLLM chat serving builds the reply⑨ respond: ChatRenderer.build_responseafter ⑧: {content, finish_reason, usage}after ⑧: same reply shapeEngine processes (GPU): prefill engine, then decode engine; each one's rank zero hosts the Dynamo adapterDynamoVllmAdapterNemoRLMegatronLLMEngine (new, subclass of Megatron-LM's)⑥ prefill leg: fills the KV cache⑥ prefill leg: Megatron-LM's, unchanged⑦ decode leg: generate, stage capture once⑦ decode leg: generate, stage capture oncechecks the caller is still therefinish_reason: the engine's own⑧ one chunk {output, result}finish_reason guessed by count [C4]any ValueError → 400 refusal [C2]⑧ one chunk {output, result}TransferQueue (TQ): W at ⑦ by the decode engine's rank zero · R at ④ by the frontend (the model's own prefix)new in this PRbehaves differently from vLLM or Megatron-LM's own endpoint (review comment)shared or unchanged

Where they meet, and what still differs

StepvLLMMegatron (new)Same?
② samplingon_policy_sampling refuses a trained call whose sampling is off the train/validation profilefills omitted fields only; min_p, penalties and logit_bias are droppedNo · C3
â‘¢ rendervLLM's own rendererMegatron-LM's ChatRenderer.renderSame token ids for the same chat
④ prepareOne function for both, gym_prompt.prepare_prompt: splice, then clamp. Megatron adds its BOS rule through the finish_prompt hook, the same order as Megatron-LM's endpoint.Yes, except add_BOS can never be sent · C5
⑦ decodethe engine's own finish_reasonfinish_reason guessed from the token count; any ValueError is answered as 400No · C4, C2
⑨ replyvLLM's chat servingChatRenderer.build_responseSame reply shape

The two paths share code up to prepare_prompt and the wire format (ForwardedCall, GymEngineReply). Render and reply stay per backend on purpose: each one must match its own native server, so Gym gets the same reply with or without Dynamo.

The chat engine, before (vLLM only, base)

# Dynamo frontend process, one task per call
async def _serve(request):
    body.update(on_policy_sampling(body))   # vLLM's check, imported directly
    rendered = await pool.render(body)        # vLLM renderer in worker processes
    plan = await prepare_prompt(rendered)     # vllm/prompt_and_capture.py
    data = await call_engine(plan.token_ids)  # router → prefill → decode
    return await pool.respond(data)

After (both backends)

# Dynamo frontend process, one task per call
async def _serve(request):
    body.update(backend.checked_sampling(body))  # Megatron: fills defaults only (C3)
    rendered = await pool.render(body)        # the backend's RenderWorker class
    plan = await backend.prepare_prompt(rendered)  # shared splice + clamp; Megatron adds BOS
    data = await call_engine(plan.token_ids)  # Megatron: NemoRLMegatronLLMEngine
    return await pool.respond(data)        # Megatron: ChatRenderer.build_response

Real code: MegatronChatBackend, MegatronRenderer, NemoRLMegatronLLMEngine, VllmChatBackend.

So what. The design is sound: one chat engine, and each backend reuses its own native render and reply code. Before it can serve a single call, the Megatron-LM pin must include ChatRenderer. Today every render worker fails with AttributeError, and the tests that would catch this are skipped (C1). Then the three red steps above need to match vLLM (C3, C4, C5).