Skip to content

perf(vllm): optimize native HTTP request processing - #3892

Open
jthomson04 wants to merge 12 commits into
NVIDIA-NeMo:mainfrom
jthomson04:perf/native-vllm-http-path
Open

jthomson04 wants to merge 12 commits into
NVIDIA-NeMo:mainfrom
jthomson04:perf/native-vllm-http-path

Conversation

@jthomson04

@jthomson04 jthomson04 commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Fastokens: pass the existing policy.tokenizer.use_fastokens setting to native async vLLM actors, and apply Fastokens before vLLM creates its tokenizer and HTTP renderer.
  • Fewer copies: replace the full message-history deep copy with shallow copies of the message list, message mappings and tool_calls lists.
  • orjson:
    • Parse native HTTP request bytes with orjson, and serialize non-streaming success and error responses with it. Pydantic validation and streaming are unchanged.
    • Responses use OPT_NON_STR_KEYS, so int-keyed dicts such as prompt_logprobs serialize as they did with json.dumps.
    • Declare orjson as a direct dependency. It was only a constraint, which broke L0 test collection on the previous CI run.
  • Gym prefix:
    • Consume the Gym-derived exact prefix from perf(vllm): derive required prefix token IDs in Gym Gym#2836. Gym now derives it only when derive_prefix_token_ids_from_messages is set, so setup_nemo_gym_config turns that flag on for the native vLLM backend.
    • Keep the metadata scan as a compatibility fallback, using Gym's rule: only the newest assistant message counts, and if it has no token information no prefix is sent. It no longer falls back to an older turn's tokens.

This targets main directly and does not depend on NeMo-RL #3761.

Gym dependency

3rdparty/Gym-workspace/Gym is pinned to 9691c00178df341833428ae002f8a66699f85019, the head of NVIDIA-NeMo/Gym#2836 (two commits on Gym main 75bb53e6d4). The previous pin was 17abf2dd. The uv.lock changes come from Gym's own pyproject. Before merge, the pin must move to the Gym main commit that contains #2836.

How NeMo-RL sets derive_prefix_token_ids_from_messages:

  • Where: in the env.nemo_gym policy_model overlay, for the vllm backend only. Dynamo is handled in refactor(dynamo): move native token response handling to Gym #3763.
  • Override: it's set with setdefault, so an explicit value in the recipe wins.
  • Conflicts: it's skipped when the overlay sets supply_prefix_token_ids. That option owns the same request field, and Gym rejects the two together.
  • Sharded jobs: without a policy_model overlay, it's set through common_overrides, so every shard gets it without an unclaimed overlay.
  • Token capture: the Gym actor turns it off together with return_token_id_information. Gym rejects derivation without token information, and external staging supplies the prefix from the ledger.

End-to-end result (vLLM 0.26, measured before the rebase)

These numbers come from the original branch on vLLM 0.26, before it was rebased onto main with vLLM 0.29.0. They have not been re-measured on 0.29.

Matched 48-GPU Nano V3.5 native vLLM 0.26 runs used:

  • the same model and data;
  • six TP4 serving workers and six policy nodes;
  • 144 trajectories per step, four optimizer steps, concurrency 192;
  • eight Gym workers.
Metric Before After Change
Model calls 59,753 62,389 +4.41%
Generated tokens 14,501,490 15,397,347 +6.18%
Summed client model-call time 261,684.84 s 199,291.67 s -23.84%
Seconds per model call 4.3794 3.1943 -27.06%
Generated tokens per model-call second 55.42 77.26 +39.42%
Summed rollout wall time 8,851.27 s 8,042.62 s -9.14%
Token-normalized rollout wall time 1.000 0.856 -14.42%

Generated work differed by 6.18%, so the raw rollout-wall result is only directional. The token-normalized result and per-call metrics account for that difference. model-call time is client-observed request time, not vLLM engine-only execution time.

The optimized native result also closely matched the retained optimized Dynamo aggregate result: 3.1943 versus 3.1986 seconds per call, and 77.26 versus 77.16 generated tokens per model-call second.

vLLM 0.29.0 check

The optimization mirrors vLLM's chat preprocessing, so it was re-checked against v0.29.0:

  • OnlineRenderer.preprocess_chat has the same signature. Its only new branch reads prompt ids from kv_transfer_params, which NeMo-RL does not send.
  • Rendering still rewrites tool_calls[].function.arguments in place. 0.29 now turns malformed JSON into {} instead of raising. The rewrite is idempotent, so rendering the prefix from the shallow copy gives the same result as a deep copy (checked on CPU with 0.29.0).
  • Request validation keeps message token fields (extra="allow") and needs no validation context.
  • vLLM's VLLM_USE_FASTOKENS hook is unchanged, so the early Fastokens patch still covers the config-only setting.

Validation

After the rebase, CPU only:

  • 311 passed:
    • CPU tests in test_vllm_generation.py: the PR's tests, the newest-assistant fallback tests, int-key serialization, and main's HTTP 400 handler tests adapted to the raw-request route.
    • CPU tests in test_nemo_gym.py (including the new setup_nemo_gym_config flag tests), test_nemo_gym_utils.py, test_nemo_gym_shards.py, test_vllm_chat_template_wiring.py and test_fastokens.py.
  • 98 passed with --nemo-gym-only: test_nemo_gym_token_capture.py (with a new token-capture spinup test), test_captured_media.py, test_nemo_gym.py, test_nemo_gym_utils.py.
  • 44 passed with --vllm-only: test_vllm_import_targets.py against vLLM 0.29.0.
  • 10 passed: the new vllm_model tests from perf(vllm): derive required prefix token IDs in Gym Gym#2836 at the pinned SHA.
  • pre-commit (ruff, ruff-format, taplo, pyrefly) passed on changed files.
  • GPU tests such as test_vllm_http_server and test_nemo_gym_sanity are left to CI.

Before the rebase, on vLLM 0.26:

  • A real Nano V3.5 TP4 smoke passed first-turn and multi-turn HTTP requests with exact token metadata, Fastokens, Gym prefix ownership and orjson responses.
  • The full native vLLM 0.26 trainer exited successfully with four steps, exactly 144 trajectories per step and weight version 4. It had no /tokenize recovery, no prefix fallback, and no token-ID or log-probability mismatch.

Scope

  • No new NeMo-RL configuration option; setup_nemo_gym_config sets the Gym flag.
  • orjson becomes a direct dependency (it was already in the lock).
  • Gym submodule bump to the perf(vllm): derive required prefix token IDs in Gym Gym#2836 head.
  • No thread, process, retry or streaming-response changes.
  • No Dynamo changes.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Aug 28, 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.

@jthomson04

Copy link
Copy Markdown
Contributor Author

/ok to test 0d4404d

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 0d4404d (PR #3892 from perf/native-vllm-http-path)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@jthomson04
jthomson04 force-pushed the perf/native-vllm-http-path branch from 0d4404d to dc2ed1c Compare August 31, 2026 17:29
@jthomson04

Copy link
Copy Markdown
Contributor Author

/ok to test dc2ed1c

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: dc2ed1c (PR #3892 from perf/native-vllm-http-path)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@jthomson04 jthomson04 added the CI:L1 Run doctests, unit tests, and functional tests label Aug 31, 2026
@jthomson04
jthomson04 marked this pull request as ready for review August 31, 2026 17:33
@jthomson04
jthomson04 requested review from a team as code owners August 31, 2026 17:33
@copy-pr-bot

copy-pr-bot Bot commented Aug 31, 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.

@jthomson04
jthomson04 force-pushed the perf/native-vllm-http-path branch from dc2ed1c to f118f06 Compare September 8, 2026 17:15
@jthomson04

Copy link
Copy Markdown
Contributor Author

/ok to test f118f06

@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: f118f06 (PR #3892 from perf/native-vllm-http-path)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@jthomson04

Copy link
Copy Markdown
Contributor Author

/ok to test c14cedc

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: c14cedc (PR #3892 from perf/native-vllm-http-path)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@jthomson04

Copy link
Copy Markdown
Contributor Author

/ok to test a416788

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Oct 12, 2026
@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: a416788 (PR #3892 from perf/native-vllm-http-path)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

jthomson04 and others added 5 commits October 13, 2026 09:24
Pin 3rdparty/Gym-workspace/Gym to 9691c00178df (NVIDIA-NeMo/Gym#2836,
two commits on Gym main 75bb53e6d4). That PR adds the opt-in
VLLMModelConfig.derive_prefix_token_ids_from_messages flag, which sends
the newest assistant turn's exact prompt + generation tokens as
required_prefix_token_ids.

Relocked with uv 0.11.28, the version CI installs. Every lock change
comes from Gym's own pyproject: aiohttp>=3.14.4 (sglang keeps 3.14.3,
so aiohttp forks), anyio>=4.15.1, PyJWT>=2.15.1, jinja2, jsonschema, and
the dropped mlflow/mlflow-skinny dependencies.

Signed-off-by: jthomson04 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
nemo_rl.models.generation.vllm.vllm_worker_async imports orjson at module
top, and nemo_rl.models.generation.vllm imports that module, so every
import of nemo_rl.models.generation needs orjson in the base venv.

orjson was only a constraint, never a requirement. Under the previous
base, nothing in the base venv pulled it in, so the earlier CI run of
this PR failed test collection in nearly every L0 unit job with
"ModuleNotFoundError: No module named 'orjson'". On current main it
arrives only transitively through swanlab 0.10.0, which would break
again if swanlab dropped it. Declare it directly with the existing
CVE floor.

Relocking also lets uv resolve a single aiohttp (3.14.5) instead of the
3.14.3/3.14.5 fork from the previous commit.

Signed-off-by: jthomson04 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Main's test_vllm_generation_selects_worker_extension pins the exact
RayWorkerBuilder kwargs, and this PR adds use_fastokens to the async
builder call. Pass use_fastokens=True and expect it in the kwargs, so the
test also checks that VllmGeneration forwards the flag to async actors.

Signed-off-by: jthomson04 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
vLLM 0.29's ChatCompletionResponse.prompt_logprobs is
list[dict[int, Logprob] | None]. JSONResponse (json.dumps) writes int
keys as strings, but orjson.dumps raises JSONEncodeError on them, so a
request that sets prompt_logprobs would turn into a 500 on the orjson
path. Pass OPT_NON_STR_KEYS to match json.dumps. On a 20k-token response
payload it costs 0.4 us per call (103.9 us vs 104.3 us).

Signed-off-by: jthomson04 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
jthomson04 and others added 7 commits October 13, 2026 09:24
NVIDIA-NeMo/Gym#2836 makes Gym's message-derived required_prefix_token_ids
opt-in through VLLMModelConfig.derive_prefix_token_ids_from_messages
(default false). NeMo-RL's native vLLM HTTP server implements that field,
so setup_nemo_gym_config now turns the flag on in the env.nemo_gym
policy_model overlay when the generation backend is vllm. Dynamo is left
to its own PR, and megatron is unchanged.

- An explicit derive_prefix_token_ids_from_messages in the overlay wins.
- The flag stays off when the overlay sets supply_prefix_token_ids, which
  owns the same field and which Gym rejects alongside it.
- A sharded job without a policy_model overlay gets the flag through
  common_overrides. A new top-level overlay would have no shard owner and
  fail the shard plan.
- Token capture turns off return_token_id_information on the actor, and
  Gym rejects derivation without it, so the actor now turns the flag off
  there too. External staging supplies the prefix from the ledger.

Signed-off-by: jthomson04 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
When a Gym request has no required_prefix_token_ids, the native server
scanned back for any message carrying prompt_token_ids. If the newest
assistant message had no tokens (it was injected, edited, or
regenerated), the scan used an older turn's tokens, which are no longer a
prefix of the rendered prompt. NVIDIA-NeMo/Gym#2836 fixed the same bug in
Gym's derivation.

Match Gym's rule: look only at the newest assistant message, and send no
prefix when it has no token information. The rule lives in
_message_prefix_token_ids so it can be tested without the vLLM request
classes.

Signed-off-by: jthomson04 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Only GRPO passed policy.tokenizer.use_fastokens to VllmGeneration, so the
single-controller, distillation and PPO paths silently ignored it for the
async vLLM HTTP tokenizer. Pass it at every construction site and make it a
required keyword-only argument so a new caller cannot drop it again. Eval
and the research template forward their tokenizer config; the refit
verifier passes False because its inline config has no such key and it
runs the sync engine.

Signed-off-by: jthomson04 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Type the message-copy, orjson request and orjson response helpers, with
_parse_orjson_request generic over the pydantic request class it returns.

The message-copy docstring said vLLM normalizes the copied containers in
place, which is not what vLLM 0.29 does: it renders from conversation dicts
it builds itself, and its only in-place write to request messages is the
idempotent parse of tool_calls[].function.arguments. Say that instead.

Signed-off-by: jthomson04 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Move the shard-aware lookup of the Gym policy model's vllm_model overlay
into _gym_policy_model_overlay, byte-identical to the copy that NVIDIA-NeMo#3856 and
NVIDIA-NeMo#3763 add, so the three PRs merge onto one helper.
_enable_gym_prefix_derivation now only decides the flag.

The helper treats a null overlay level as empty and rejects a non-mapping
one with a ValueError. Before, an unsharded policy_model: null (or a null
nested level) failed with an AttributeError.

Signed-off-by: jthomson04 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The dynamo case asserted that setup_nemo_gym_config leaves env.nemo_gym
untouched. The Dynamo setup in NVIDIA-NeMo#3856 and NVIDIA-NeMo#3763 writes its own policy model
overlay there, and NVIDIA-NeMo#3763 sets derive_prefix_token_ids_from_messages for
Dynamo too, so neither that assertion nor a narrower one on the flag would
survive those PRs. Pin only megatron, whose Gym overlay nothing touches.

Signed-off-by: jthomson04 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
GRPO's init_vllm reads policy.tokenizer.use_fastokens since this PR started
forwarding it, and this test's mock policy config had no tokenizer block,
so its two non-error cases failed with KeyError: 'tokenizer'.

Signed-off-by: jthomson04 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@jthomson04
jthomson04 force-pushed the perf/native-vllm-http-path branch from a416788 to 2318cba Compare October 13, 2026 16:43
@jthomson04

Copy link
Copy Markdown
Contributor Author

/ok to test 2318cba

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 2318cba (PR #3892 from perf/native-vllm-http-path)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@terrykong terrykong removed the Documentation Improvements or additions to documentation label Nov 28, 2026

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:L1 Run doctests, unit tests, and functional tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants