One Gym chat call, three shared steps: prepare the prompt, capture on the worker, build the reply. Only the transport differs between native and Dynamo.

Design proposal for #4979, pinned at 5c7fa69e. Prototype: sketch PR. Example values come from test_dynamo_chat_engine.py.

Before
Each path has its own copy of the steps around generation: prefix read, splice, clamp, restore order, capture start, error handling, and the reply for a resumed call.
This PR
#4979 as it is: Gym calls run through Dynamo's frontend and KV router. It ports #4506's cut-and-resume to Dynamo with the shared restore functions, but writes their order once per path.
Status
Proposed — not implemented in #4979. A sketch on 5c7fa69e exists as a draft PR; the PR lists what has been tested.

Nine pages on this stack (#4905, #4979 and #5115), one question each. This one: how to split a Gym call so both paths run the same code.

Background. NeMo-Gym sends chat calls. On turn 2+, the earlier turns are swapped for the exact tokens the model made (the splice), read from TQ. The clamp fits the output budget. A restore resumes a call a checkpoint cut. Dynamo's KV router picks a worker by token ids. Dotted words: hover or tap.

On native, every step runs in one vLLM worker process (VllmAsyncGenerationWorkerImpl). On Dynamo, the KV router needs the final token ids first, so the frontend (NemoRLChatEngine) prepares the prompt and the worker (DynamoVllmAdapter) captures it. A restore must run on the worker, since it checks the saved tokens against the worker's weight version. So cut the call there, make each side one shared function, and send the prepared prompt as JSON.

Today's native code, then the same three boxes in both lanes

Native today (5c7fa69): no shared steps Gym: POST /v1/chat/completions (turn 2) max_tokens 20 · ng_capture: token_in, call "c2" vLLM worker process (Ray actor) create_chat_completion · L1055 preprocess_chat, part 1 INLINE · becomes A TQ read → prefix [1,5,6,2] splice: prefix[:3] + template[2:] clamp 20 → 10, written twice: L527,L584 chat_server.py L490-L573 still the same function no prompt object: the values stay in local variables render-only and splice branches each repeat B preprocess_chat, part 2 INLINE · becomes B restore: resolve_restored_call → swap prompt terminal check → clamp again for a restore media snapshot → remap images begin_call(prompt, prefix [1,5,6,2]) L496-L645 · same order again in adapter.py generate: vLLM's OpenAIServingChat → AsyncLLM vLLM's own queue check, SamplingParams, GPU full generator + route INLINE · becomes B ok: stage ids, logprobs, routes → TQ err: six except blocks, own status per error full queue → 500 (Dynamo: 503) L1077 same process full generator: build the reply INLINE · becomes C text, reasoning, tools, usage → OpenAI JSON restore fixes + top_logprobs check, after generation L741 Native, proposed: one worker process Dynamo, proposed: frontend → KV router → worker Gym: POST /v1/chat/completions (turn 2) max_tokens 20 · ng_capture: token_in, call "c2" Gym: POST /v1/chat/completions (turn 2) max_tokens 20 · ng_capture: token_in, call "c2" vLLM worker process (Ray actor) create_chat_completion · L1055 Dynamo frontend process NemoRLChatEngine._serve · L257 A · prepare_prompt SHARED · prompt_and_capture.py in: template [1,7,2,3,4] · history [1,7,2] TQ read, off the loop → prefix [1,5,6,2] splice: prefix[:3] + template[2:] · clamp 20 → 10 out: {prompt_token_ids:[1,5,6,2,3,4], prefix_len:4, splice:[3,2], max_tokens:10, admission:…} A · prepare_prompt SHARED · prompt_and_capture.py in: template [1,7,2,3,4] · history [1,7,2] TQ read, off the loop → prefix [1,5,6,2] splice: prefix[:3] + template[2:] · clamp 20 → 10 out: {prompt_token_ids:[1,5,6,2,3,4], prefix_len:4, splice:[3,2], max_tokens:10, admission:…} PreparedPrompt stays a Python object same process: no copy, no JSON KV router (Rust, same process) picks 1 worker by token_ids [1,5,6,2,3,4] request plane (TCP) → one worker token_ids: [1,5,6,2,3,4] extra_args prepared_prompt = prepared_prompt.to_json() {splice:[3,2], prefix_len:4, …} + request JSON, pickled media vLLM worker process (Ray actor) DynamoVllmAdapter._generate_gym · L302 PreparedPrompt (in memory) PreparedPrompt.from_json(…) B · start_capture SHARED · prompt_and_capture.py restore: resolve_restored_call (worker weights) no cut saved for c2 → None, the prompt stands terminal check → set max_tokens 10 → media → remap begin_call([1,5,6,2,3,4], prefix [1,5,6,2]) → serve a finished prefix (restore only) B · start_capture SHARED · prompt_and_capture.py restore: resolve_restored_call (worker weights) no cut saved for c2 → None, the prompt stands terminal check → set max_tokens 10 → media → remap begin_call([1,5,6,2,3,4], prefix [1,5,6,2]) → serve a finished prefix (restore only) generate: vLLM's OpenAIServingChat → AsyncLLM vLLM's own queue check, SamplingParams, GPU generate: adapter._generate → AsyncLLM queue check before B, SamplingParams, GPU B · save_capture / abort_capture SHARED · prompt_and_capture.py ok: ONE TQ write: ids, logprobs, routed experts err: error_reply → status, abort reason, ack to Gym full queue → 503 · bad token id → 400 B · save_capture / abort_capture SHARED · prompt_and_capture.py ok: ONE TQ write: ids, logprobs, routed experts err: error_reply → status, abort reason, ack to Gym full queue → 503 · bad token id → 400 same process engine_data: text + TQ location Dynamo frontend process (render pool) C · ResumedCallReplyMixin SHARED · chat_server.py text, reasoning, tools, usage → OpenAI JSON restore fixes once · in NeMoRLOpenAIServingChat C · ResumedCallReplyMixin SHARED · chat_server.py text, reasoning, tools, usage → OpenAI JSON restore fixes once · in FrontendServingChat A: prepare the prompt B: start / save / abort the capture C: build the reply path-specific one OS process crosses the network Token ids from the unit test: turn end 2, max_model_len 16. Clamp: 16 − 6 prompt tokens = 10. Left lane: today's native code, each part colored by the box it becomes. Right two lanes: same color and height = the same function. Gray = what each path keeps for itself.

Across a row, both boxes are one function with the same input and output. On Dynamo, the prepared prompt crosses to the worker as JSON beside the token ids and is rebuilt with PreparedPrompt.from_json. The restore sits in B, not A: A prepares the normal spliced prompt, and B swaps in the saved one when a cut resolves. Gray stays per path: native keeps vLLM's own serving; the adapter keeps its short copy of vLLM's SamplingParams build.

Today: each path has its own copy

StepNative copy (chat_server.py)Dynamo copy
A · prefix read, splicepreprocess_chat L490-L573frontend _splice L364-L386
A · clamptwice: L527-L533, L584-L591frontend _serve L300-L306; adapter again for a restore, L397-L408
B · restore order: restore → swap prompt → terminal check → clamp → skip media → remap → begin_call → serve terminalL496-L645adapter _serve_gym_call L367-L460
B · media → remap → begin_calltwice: L534-L551, L593-L634adapter L421-L451
B · error → statusroute, its own except blocks, L1077-L1184frontend L249-L255; adapter L316-L327 + finally
C · reply around the restore fixesfull generator L741-L868render pool respond L280-L380
checks before Atop_logprobs only, after generationn only, L269-L270

Both paths already call the same small restore functions. But the order they run in is written twice (row 3), and so is the reply code around them (row 6). Older copies drift too: a full queue is 500 on native and 503 on Dynamo, Dynamo checks the queue only after capture began (L549, after begin_call at L441), and n: 2 is refused on Dynamo but served on native.

What would change — proposed, not in #4979

Nothing below is in #4979. The hunks are from the sketch commit in the sketch PR, built on 5c7fa69e; line numbers are the old file's at 5c7fa69. The code still names its local variable plan.

Where the fix lands: RL only. New prompt_and_capture.py: A (prepare_prompt, PreparedPrompt) and B (start_capture, save_capture, abort_capture, error_reply). chat_server.py: native calls A and B, and holds C (ResumedCallReplyMixin). chat_engine.py: frontend calls A. adapter.py: worker calls B. render_pool.py: its FrontendServingChat uses C. No Gym or Dynamo change: the call Gym sends and the hook Dynamo calls stay the same.

@@ sketch · chat_server.py L481-L645 at 5c7fa69 · preprocess_chat (native)
             admission=admission,
         )
-        res = (rendered.conversation, [rendered.engine_prompt])
-        engine_prompt = rendered.engine_prompt
-        admission = rendered.admission
   ⋯ 155 more removed lines: prefix read, restore, splice, two clamps, two media → begin_call runs, serve terminal
-        return res
+        plan = await prepare_prompt(
+            rendered,
+            resolve_prefix=host._resolve_admission_prefix,
   ⋯ 7 more added lines: turn end ids, max_model_len, clamp only chat calls, tokenizer
+        )
+        await start_capture(
+            host,
   ⋯ 4 more added lines: request, rendered.engine_prompt, plan, max_model_len
+        )
+        return rendered.conversation, [rendered.engine_prompt]
@@ sketch · dynamo/vllm/chat_engine.py L285-L320 at 5c7fa69 · NemoRLChatEngine._serve (frontend)
-        prompt_token_ids, splice, prefix = await self._splice(
-            rendered, info["turn_end_token_ids"]
+        plan = await prepare_prompt(
+            rendered,
+            resolve_prefix=self._capture.resolve_prefix,
+            turn_end_token_ids=info["turn_end_token_ids"],
+            max_model_len=info["max_model_len"],
+            clamp=not extras.ng_measure,
         )
   ⋯ measure-call return; its count now reads len(plan.prompt_token_ids)
-        max_tokens = clamp_max_tokens(
   ⋯ 17 more removed lines: the rest of the clamp, the hand-built plan dict
+        wire: ForwardedCall = {
+            "prepared_prompt": plan.to_json(),
+            "request": rendered.request,
@@ sketch · dynamo/vllm/adapter.py L302-L328 at 5c7fa69 · _generate_gym (worker)
+        plan = PreparedPrompt.from_json(
+            wire["prepared_prompt"],
+            prompt_token_ids=list(request["token_ids"]),
+            parse_admission=host._parse_capture_admission,
+        )
+        chat = chat_request_from_render(wire["request"])
         try:
-            chunk = await self._serve_gym_call(
-                plan, list(request["token_ids"]), context
-            )
-        except (VLLMClientError, GracefulHTTPError) as error:
   ⋯ 10 more removed lines: this path's own error map
+            chunk = await self._serve_gym_call(chat, plan, wire, context)
+        except BaseException as error:
+            failure = await abort_capture(host, chat, error)
+            if failure is None:
+                raise
@@ sketch · dynamo/vllm/adapter.py L330-L460 at 5c7fa69 · _serve_gym_call
         host = self._host
-        chat = chat_request_from_render(plan["request"])
-        admission = host._parse_capture_admission(plan["admission"])
   ⋯ 119 more removed lines: docstring, imports, and restore → swap prompt → clamp → media → remap → begin_call → serve terminal, copied from native
+        # The worker's own engine client, as the native server uses it, with
+        # the queue limits vLLM's serving checks before the render.
+        engine_client = host._http_engine_client or self._llm
+        engine_client.check_admission(1, context.id())
   ⋯ the media unpickle, unchanged
+        await start_capture(
+            host, chat, engine_prompt, plan, max_model_len=self._max_model_len
+        )

Native's preprocess_chat shrinks to A then B. The frontend calls the same A and sends prepared_prompt.to_json(). The worker rebuilds it, checks the queue before capture, calls the same B (which now holds the restore order), and maps errors through abort_capture. Both serving chats get C from ResumedCallReplyMixin. The sketch makes three small behavior changes, each toward one answer: native now splices and clamps before resolving a restore (Dynamo's order); Dynamo sets a restored call's budget from the client's own max_tokens (native's rule); and a restored call with images keeps its media keys on Dynamo too.

🟠 review comment C88 — share the parent steps

The comment is in a pending review, so the link works only for its author until the review is submitted.

So what. With A, B and C shared, a fix to the prefix read, splice, clamp, restore order, capture start, error map or reply lands once and both paths get it. What stays per path is small and easy to see: the JSON hop, and who runs generation.