Skip to content

perf(model): drop repeated dumps and validation in chat conversion - #5934

Merged
ananthsub merged 2 commits into
mainfrom
ananthsub/converter-skip-revalidation
Nov 10, 2026
Merged

ananthsub merged 2 commits into
mainfrom
ananthsub/converter-skip-revalidation

Conversation

@ananthsub

@ananthsub ananthsub commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

The Responses ↔ Chat Completions converter repeated the same work several times on every model call, as #3042 describes. Most of the repeats were in token metadata, but several also ran on calls that carry none. Every chat message was also validated against all six chat message types, because the message union had no discriminator. This PR removes that repeated work and keeps every validation boundary.

  • Chat message validation. The chat message union now picks one member from the message role. An assistant message that carries token metadata goes to the training variant. Messages are still fully validated. This also speeds up requests arriving at /v1/chat/completions.
  • Request token metadata. The converter reads token metadata from the validated input items. Before, it dumped the items, validated the token fields again, and dumped them a second time. The request dump excludes token fields only when an item carries them, because the exclusion slows the dump down on its own.
  • Reply conversion. The reply token lists are copied once into the training variant of the last output item. The lifted output items go straight into the response instead of being dumped and rebuilt. Every field on those items stays marked as set, as before, so request replay and exclude_unset dumps carry the same null fields.
  • Smaller repeats.
    • The litellm cleanup validator no longer copies the message list when no message needs cleaning.
    • The per-request converter state is now a plain dataclass, so updating its buffers no longer goes through validated assignment.
  • Benchmark script. scripts/benchmark_chat_completions_conversion.py measures request conversion, reply conversion and the CPU cost of one model-server hop on synthetic conversations. The conversations include tools, images, reasoning, custom tool calls and outputs, and optional token metadata. --dump-outputs writes the outputs with generated IDs replaced and key order kept, so two checkouts can be diffed.

The final validation of the built chat request stays. It is the only check on messages the converter itself builds, for example a developer message that ends up with an image part.

Closes #3042.

Results

Minimum CPU time over three runs, alternating between a main process and a branch process, each pinned to one core. The machine was shared and busy (load average about 30), so single runs varied by up to 2x. An earlier run on a different load gave the same picture.

Conversation Request conversion Reply conversion Full model-server hop
1 turn, no token metadata 0.083 → 0.061 ms about 0.21 ms, unchanged 0.72 → 0.65 ms
32 turns, no token metadata 1.48 → 0.87 ms about 0.35 ms, unchanged 3.73 → 2.94 ms
512 turns, no token metadata 15.1 → 7.8 ms about 0.22 ms, unchanged 28.9 → 19.2 ms
1 turn, token metadata 0.14 → 0.12 ms 0.49 → 0.36 ms 1.47 → 1.19 ms
32 turns, token metadata 6.6 → 3.3 ms 0.91 → 0.42 ms 24.7 → 18.0 ms
512 turns, token metadata 605 → 181 ms 3.5 → 0.65 ms 1400 → 1224 ms

The hop includes parsing the request, dumping the chat request, validating the backend reply and serializing the response, which this PR does not change. Peak memory for request conversion at 512 turns with token metadata dropped from about 180 MB to about 60 MB.

Compatibility

  • Converted output matches main field for field and in key order for every benchmark conversation, with and without token metadata, including exclude_unset dumps.
  • Conversion still does not mutate its sources or share token lists with them.
  • A chat message with a missing or unknown role now fails with one error of type chat_message_role that names the valid roles. Before, the error listed one failure for each message type, and error locations named the member class. They now name the role, for example messages.0.assistant.content.
  • A chat message validated on its own, outside a request, with an assistant role and malformed token metadata is now rejected. Before, it fell back to the plain assistant message and the token fields were dropped. Inside a request both versions reject it, because extra fields are forbidden there.
  • ChatCompletionsConverterState is now a dataclass. Code that assigns invalid values to its fields is no longer rejected at assignment; the final chat request validation still catches invalid messages.
  • postprocess_chat_response lifts a reply that carries token metadata without calling postprocess_assistant_message_dict, so an override of that method sees only replies without token metadata. Nothing in Gym or NeMo RL overrides it.

Validation

  • The output comparison is the main check for the performance-only changes: the discriminator, the conditional token exclusion, the litellm early return and the skipped rebuild. PYTHONPATH=<checkout> python scripts/benchmark_chat_completions_conversion.py --dump-outputs out.json on this branch and on main gives identical files at 1, 32 and 512 turns.
  • An independent review compared this branch against main on about 40,000 randomly generated requests and replies, plus hand-picked edge cases, across all dump modes and the replay round trip, and found no output differences. Chat message validation accepted and rejected the same messages as on main.
  • New and updated tests guard against regressions. They check that:
    • request token metadata comes from the validated items, including extra fields on custom tool call outputs; null extras count as absent, and a raw dict with null token fields is rejected as before;
    • the chat request and the response do not share token lists with their sources, and the sources are unchanged;
    • reply output items keep every field marked as set, use the training variant when token metadata is present, and drop it when it was not requested;
    • the message union picks the right type, rejects unknown or missing roles, user messages with token fields, partial token metadata and developer messages with images, and names the roles in its error;
    • the existing invariant that every item the converter can attach tokens to has a training variant still finds those items, and fails if it finds none.
  • Each of these changes makes a test fail: removing the fields-set marking, removing the extra-field token lookup, attaching tokens when they were not requested, dropping null token fields from raw dicts, keeping null extras, and pointing the invariant at the wrong function.
  • pytest tests/unit_tests/models/test_chat_completions_converter.py passes.
  • pytest -n 16 tests/unit_tests/ on this branch and on main in the same local venv fails on the same environment-dependent tests (missing optional dependencies). Two process tests failed on one side only under load and pass when run alone.
  • Differential check: PYTHONPATH=<checkout> python scripts/benchmark_chat_completions_conversion.py --dump-outputs out.json on both checkouts gives identical files.
  • pre-commit run --files on the changed files passes.
  • Model-server suites (vLLM, inference provider, compaction, GenRM) need their own server venvs and are left to CI.

Rollout evidence

N/A. This is a core-library performance change with byte-identical converted output on the differential corpus, so a model rollout would not show a difference.

The Responses to Chat Completions converter dumped and revalidated the
same data several times per request. Every chat message was also
validated against all six message types, because the union had no
discriminator.

- Discriminate the chat message union by role, and by token metadata
  for the assistant training variant. Messages are still fully
  validated, including the final check on converter-built messages.
- Read request token metadata from the validated input items instead
  of dumping, revalidating and dumping it again. Exclude token fields
  from the request dump only when an item carries them.
- Attach reply token metadata with a single copy, and pass the lifted
  output items to the response directly instead of dumping and
  rebuilding them. Items keep every field marked as set, so replay
  dumps are unchanged.
- Skip the message copy in the litellm cleanup validator when no
  message needs cleaning.
- Make the per-request converter state a plain dataclass.

Converted output is byte-identical to the previous implementation on
the new benchmark script's corpus, with and without token metadata.

Closes #3042

Signed-off-by: Ananth Subramaniam <[email protected]>
@ananthsub ananthsub added area:model Model servers, inference providers, and model adapters area:core Shared APIs, servers, telemetry, health, and registries labels Nov 10, 2026
@copy-pr-bot

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

@ananthsub
ananthsub requested a review from snivertynv November 10, 2026 14:44
- Point the training-variant invariant test at _lift_assistant_message,
  where the output items are now appended, and fail when it finds none.
  It passed without checking anything after the lift moved.
- Validate a raw dict input item whole, null token fields included, as
  the request dump did before. Null token extras on a model still count
  as absent.
- Name the roles in the error for a chat message with no known role,
  instead of the discriminator's generic tag error.
- Correct comments and docstrings that named the old call path, the
  mapping types the atomic token check covers, and where token lists
  are copied.
- Test that token metadata is dropped when it was not requested.
- Benchmark: keep key order in the differential dumps, add custom tool
  call items, and report min and max instead of p99 and a block count.

Signed-off-by: Ananth Subramaniam <[email protected]>
@ananthsub
ananthsub marked this pull request as ready for review November 10, 2026 16:09
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 10, 2026 16:10
@github-actions

Copy link
Copy Markdown
Contributor

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

SHIP — LGTM — no concerns found.

I reviewed all five changed files and traced the affected request validation, token metadata handling, reply conversion, serialization, and replay paths. I found no qualifying correctness or compatibility issues.

This was a static review. I didn't execute tests or the differential benchmark.

Note: formal approval is not available for this request, so this review is posted as a comment only.

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

@snivertynv

Copy link
Copy Markdown
Contributor

The changes proposed here look good to me. Some performance testing results on a microbenchmark that models a real Gym server under load show good CPU performance improvements, especially for token-in harnesses.

Server-level check: a multi-worker vllm_model (8 workers on 8 CPUs) in front of mock engines, driven by closed-loop 20-turn Responses-API rollouts that replay the returned output items; base = parent commit, 3 interleaved reps, medians.

Traffic Load Calls/s Server CPU per call
No token metadata saturated +5% 4.24 → 4.02 ms (−5%)
Token metadata in history saturated 162 → 220 (+36%) 49.4 → 36.4 ms (−26%)
Token metadata in history below saturation unchanged 46.7 → 36.3 ms (−22%)

p99 latency at saturation with token metadata fell 7.8 → 5.9 s. No errors; routing by rollout id unchanged.


class ChatCompletionsConverterState(BaseModel):
@dataclass
class ChatCompletionsConverterState:

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.

Nit for the compatibility section:

ChatCompletionsConverterState is now a dataclass: construction and assignment are no longer validated or coerced, and Pydantic methods such as model_dump and model_copy are gone. The final chat request validation still catches invalid messages.

@ananthsub
ananthsub added this pull request to the merge queue Nov 10, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42915699403

Merged via the queue into main with commit c014949 Nov 10, 2026
69 checks passed
@ananthsub
ananthsub deleted the ananthsub/converter-skip-revalidation branch November 10, 2026 22:45

This branch was previously deployed

1 inactive deployment
public — 2cdc46c7 Deployed Nov 10, 2026 by copy-pr-bot[bot] via release / finalize / notify #11455
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core Shared APIs, servers, telemetry, health, and registries area:model Model servers, inference providers, and model adapters

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Remove duplicate validation and dumps in model API dialect conversion

3 participants