Skip to content

feat(trtllm): TRT-LLM prefill/decode disaggregation for GRPO rollouts - #4095

Merged
yuki-97 merged 25 commits into
mainfrom
shuyix/trtllm_disagg
Oct 15, 2026
Merged

yuki-97 merged 25 commits into
mainfrom
shuyix/trtllm_disagg

Conversation

@shuyixiong

@shuyixiong shuyixiong commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

Adds experimental TRT-LLM prefill/decode (PD) disaggregation for GRPO rollouts on the NeMo-Gym path: each rollout replica becomes M prefill + K decode engines behind F TRT-LLM OpenAIDisaggServer frontends.

Design doc: docs/design-docs/pd-disaggregation-rollout.md

Changes

Config

  • policy.generation.disaggregation (DisaggConfig in generation/interfaces.py): a backend-agnostic layout covering num_prefill_engines, num_decode_engines, num_frontend_workers, frontend_tokenize and frontend_base_port.
  • trtllm_cfg.prefill_engine / decode_engine: per-role overrides limited to TP, the MoE split, memory, batch/token limits and trtllm_kwargs.
  • trtllm_cfg.disagg_server: passed through to TRT-LLM's DisaggServerConfig (routers, gen_tokids_ctxbytes, …).
  • config.py: resolve_disagg_layout, role_tensor_parallel_size and replica_width.
  • grpo.setup() refuses to start when disaggregation.enabled is set with a non-TRT-LLM backend.

Engine layout and placement

  • TrtllmGeneration._plan_engines() lays engines out replica by replica, prefill engines before decode engines. The replica count is derived from the size of the inference cluster: inference_GPUs / replica_width.
  • RayVirtualCluster.get_topology_sorted_pg_indices() orders per-node placement groups by NVLink domain, so a replica that spans several nodes stays inside one domain where the allocation allows it.
  • GRPO's NVLink-domain alignment uses the whole replica width as its unit under disaggregation, rather than the width of a single engine.
  • worker_groups.py: the DP-leader worker-index check is shared.

Frontends (trtllm_disagg_server.py, new)

  • DisaggServerActor is a CPU-only Ray actor that wraps OpenAIDisaggServer. It starts serving in __init__, so a restarted actor comes back on the same URL.
  • Each frontend gets a hard node pin and a deterministic port: base + replica_idx * F + frontend_idx.
  • Each frontend gets a distinct node_id, so request-id snowflakes don't collide; N*F <= 256 is asserted.
  • Strips Gym-only request fields before relaying.
  • With frontend_tokenize, the frontend renders the chat template and tokenizes, then sends ids to prefill as prompt_token_ids_b64.
  • dp_openai_server_base_urls reports all N×F frontend URLs, so Gym's existing per-session affinity keeps each trajectory on one replica.

Engine HTTP server and worker

  • trtllm_http_server.py:
    • parses the incoming disaggregated_params into TRT-LLM's LLM-level DisaggregatedParams;
    • accepts prompt ids supplied by the frontend;
    • forwards the conversation id so attention-DP routing can keep a conversation on one rank. This affects performance only.
  • trtllm_worker_async.py: disaggregated engines default to cache_transceiver_config: {backend: DEFAULT}. Without it, TRT-LLM builds no transceiver and context legs return no disaggregated_params.
  • Refit, sleep/wake, prefix-cache reset and profiling still drive the engines directly; only the request path goes through the frontends.

NeMo-Gym

  • trtllm is now an allowed generation backend for NeMo-Gym. For this backend, the setup forces async_engine and expose_http_server on.

Known limitations

  • Colocated generation is not supported yet; colocated.enabled must be false.
  • A request that is decoding while an in-flight weight update lands keeps its old KV and is not re-prefilled (TODO in the design doc). The next turn re-prefills, because reset_prefix_cache() runs on every engine.
  • Conversation affinity for attention-DP needs feat(vllm-model): forward gym session id as backend conversation id Gym#3582, which makes Gym send conversation_params. Without it, everything is still correct but slower.

Issues

Depends on NVIDIA-NeMo/Gym#3582 for conversation affinity under attention-DP (performance only).

Usage

policy:
  generation:
    backend: trtllm
    colocated:
      enabled: false
    disaggregation:
      enabled: true
      num_prefill_engines: 1
      num_decode_engines: 1
      num_frontend_workers: 1
    trtllm_cfg:
      tensor_parallel_size: 1
      expose_http_server: true
      disagg_server:
        ctx_router: conversation
        gen_router: load_balancing

End-to-end recipe, added to tests/test_suites/nightly_gb200.txt:

bash tests/test_suites/llm/grpo-qwen3-1.7b-2n4g-megatron-trtllm-disagg-swe1.sh
# config: examples/configs/recipes/llm/grpo-qwen3-1.7b-2n4g-megatron-trtllm-disagg-swe1.yaml

Convergence test
grpo-qwen3-1.7b-2n4g-megatron-vllm-async-swe1 vs grpo-qwen3-1.7b-2n4g-megatron-trtllm-disagg-swe1
image
image
image

Before your PR is "Ready for review"

Pre checks:

  • Make sure you read and followed Contributor guidelines
  • Did you write any new necessary tests?
    • New: test_trtllm_disagg_server.py.
    • Extended: test_trtllm_generation.py, test_trtllm_http_server.py, test_trtllm_worker_async.py, test_topology_placement.py, test_worker_groups.py and test_nemo_gym_utils.py.
  • Did you run the unit tests and functional tests locally? Visit our Testing Guide for how to run tests
    • TRT-LLM unit tests pass in the container (85 passed), and so does the GRPO unit test subset.
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Sep 11, 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.

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

Team review: PD disaggregation for GRPO rollouts

Reviewed by a team of 5 agents (RL-codebase, bug-finder, test, design, devil's-advocate) over the full diff, with every upstream claim verified against the pinned TensorRT-LLM commit rather than main. 11 comments below.

First — this is high-quality work. The comments explain why rather than what, which is rare and made the review much faster, and several seams are worth calling out as deliberately good:

  • _run_on_engines as the single per-engine fan-out, with _engine_owner_indices derived from the same bundle split handed to the worker group and an assert that the two can't drift. Refusing to overload the DP axis to mean "engines" was the right call — bending NamedSharding to model ragged engine widths would have leaked into every backend.
  • DisaggServerActorImpl split from the @ray.remote actor, mirroring TrtllmAsyncGenerationWorkerImpl. This is the only reason any of the new server code is testable at all.
  • build_spliced_prompt_ids as one tokenization source of truth shared by frontend and engine adapter, plus sampled shadow validation — the right shape for a correctness-critical duplication that can't be eliminated.
  • dp_leader_worker_indices as a generic validated parameter on RayWorkerGroup rather than a TRT-LLM special case.

The main themes in the comments: the disagg path needs a TensorRT-LLM ref newer than the one pinned here; a replica-indexing bug in the frontend port that fails silently; the new test file isn't collected by any CI shard; and pre-commit is currently failing.

Two further items are deliberately not filed as comments, for the author's awareness: _plan_engines and get_topology_sorted_pg_indices both have zero test coverage (the latter's domain_rank sort key — the entire point of the function — is unasserted, and all five fallback paths are silent). We have candidate tests for both but haven't executed them, so we'd rather flag the gap than paste unverified code.

Generated by Claude Code

Comment thread tools/build-custom-trtllm.sh Resolved
@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Sep 22, 2026
@shuyixiong
shuyixiong force-pushed the shuyix/trtllm_disagg branch 2 times, most recently from f56d673 to af1599f Compare October 9, 2026 14:29

@shuyixiong shuyixiong left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Self-review of the current head (d59fa895e) by an agent team (RL expert, TRT-LLM API expert checked against the pinned f94eeb37, bug finder, test agent, design reviewer, comment reviewer, devil's advocate).

Top items, all PR-introduced and reproduced on CPU:

  1. grpo.py:1170: AttributeError on DisaggConfig.get when cluster.segment_size is set.
  2. trtllm_worker_async.py:270: the DEFAULT cache-transceiver fallback is dead.
  3. trtllm_http_server.py:181: gen_tokids_ctxbytes is a no-op.

Also: pre-commit (ruff / ruff-format / pyrefly / minimize-check) fails at head, and the PR description is still the empty template. The perf-evidence request in the earlier review is still open.

Checked and fine: refit and prefix-cache reset reach both prefill and decode engines; _engine_owner_indices / collective ranks under topology-sorted PGs; per-(replica, frontend) ports and the 256 node_id cap; ASGI body replay and Content-Length rewrite. The PR's 118 CPU unit tests pass (5 skipped without tensorrt_llm).

Generated by Claude Code

Comment thread nemo_rl/algorithms/grpo.py Resolved
@shuyixiong
shuyixiong marked this pull request as ready for review October 12, 2026 02:09
@shuyixiong
shuyixiong force-pushed the shuyix/trtllm_disagg branch from 2d05d2f to d54a494 Compare October 12, 2026 02:18
@shuyixiong shuyixiong added the CI:L1 Run doctests, unit tests, and functional tests label Oct 12, 2026
@hchings
hchings requested a review from yuki-97 October 12, 2026 18:40
@shuyixiong shuyixiong self-assigned this Oct 13, 2026
@shuyixiong
shuyixiong requested a review from RayenTian October 13, 2026 02:23

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

Thanks for supporting disagg serving! Partly reviewed.

Comment thread nemo_rl/algorithms/grpo.py Resolved
@RayenTian

RayenTian commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for this — it's a substantial and well-documented piece of infra. Would it be possible to share a convergence/reward curve from the new nightly recipe? A comparison curve from the aggregated path would also be great, so we can see parity between the disagg and aggregated paths.

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

One more low-priority item on the disagg engine placement.

Generated by Claude Code

@shuyixiong

Copy link
Copy Markdown
Contributor Author

@RayenTian Thanks for the review! I also ran a 100-step convergence comparison of TRT-LLM disagg against a matching vLLM baseline and added the results to the PR description.

shuyixiong and others added 12 commits October 13, 2026 08:46
Brings up PD-disaggregated generation end-to-end on GB200: a replica's
inference GPUs are split into context (prefill) and generation (decode)
engines fronted by one OpenAI-compatible disagg server, which is the single
URL NeMo Gym talks to.

Engine plumbing. TrtllmGeneration plans engines per replica from
trtllm_cfg.disaggregation (engine counts, per-role TP/EP overrides, routers,
cache transceiver backend) and hands each worker its role. DisaggServerActor
wraps TRT-LLM's OpenAIDisaggServer; trtllm_disagg_server.py adapts it to the
NeMo Gym request shape. config.py gains the disaggregation schema, and
build-custom-trtllm.sh plus the Dockerfile pick up UCX and NIXL so the cache
transceiver is actually compiled in -- without them an engine aborts on the
first KV transfer.

Six bring-up fixes, each of which silently broke the path rather than
failing loudly:

- DisaggServerActor ran in the driver's environment and died with
  ModuleNotFoundError: tensorrt_llm. Give it the engine workers'
  interpreter, which RayWorkerGroup now exposes as py_executable.
- OpenAIDisaggServer builds a prometheus MultiProcessCollector in
  register_routes(), which raises unless PROMETHEUS_MULTIPROC_DIR is set.
  TRT-LLM's own entrypoint calls set_prometheus_multiproc_dir() first; we
  construct the server directly, so call it too.
- The middleware stripping NeMo Gym's vLLM-only request fields was a
  Starlette BaseHTTPMiddleware, which hands the downstream app its own
  captured receive channel, so reassigning request._receive never reached
  FastAPI's validation and every request 400'd on extra_forbidden.
  Rewritten as raw ASGI.
- Aggregated serving lost its rollout fields: they moved off the message
  onto declared response fields for the disagg path, but with no disagg
  server to re-attach them NeMo Gym silently dropped every assistant turn.
  Attach them on the message when no disaggregation is in play.
- Under disaggregation the unit that must stay inside one NVLink domain is
  the replica -- its context and generation engines exchange KV every turn
  -- not the engine. Sizing gpus_per_instance by the engine yielded
  nodes_per_instance=1 and skipped domain pinning entirely.
- Per-node placement groups were consumed in creation order, so two adjacent
  pg_idx values could sit in different NVLink domains and split a replica
  across the fabric. Consume them in topology order instead.

The engine HTTP server also moves from asyncio.to_thread(llm.generate) to
llm.generate_async: the blocking API parks a worker thread per in-flight
request, capping concurrency at the default executor size rather than at the
engine's scheduler.

Error fidelity. OpenAIDisaggServer._handle_exception only re-raises
HTTPException, so a 4xx from an engine arrives as an
aiohttp.ClientResponseError, falls into the catch-all, and reaches the
caller as 500. The aggregated server returns it as a 4xx, and Gym accounts
for the two classes differently -- which would make masking statistics
incomparable between the aggregated and disaggregated paths, the exact
comparison this work exists to support. Re-raise 400-499 with the original
status; 5xx still goes to super().

Empty rollouts. A Gym rollout can return without a single assistant turn
(the agent stalls before its first completion and Gym's wall-clock timeout
kills it). That raised ValueError, taking the run down over one sample and
losing the step's other 127 rollouts. NRL_SKIP_FAILING_EMPTY_ROLLOUT gates
it: the default "0" keeps the raise, since the usual causes are
misconfigurations worth surfacing; "1" stands the sample up as prompt-only
and masks it out of the loss, reported as
train/num_masked_seqs_by_empty_rollout. That count overlaps
num_mask_sample_filtered by design and must not be summed with it --
num_valid_samples stays authoritative. Note there is no circuit breaker on
a sustained rate.

Profiling. Under disaggregation every engine runs the same worker class, so
nsys reports differed only by %p pid and matching a trace to the context or
generation side meant grepping the driver log. The -o filename now carries
the role and an ordinal (_context0, _context1, _generation0), appended
rather than prefixed so the report names documented in docs/nsys-profiling.md
stay prefix-matchable.

Also bumps TRT-LLM to 1.3.0rc24.

Signed-off-by: shuyixiong <[email protected]>
(cherry picked from commit a8f1ad3)
Three CacheTransceiverConfig knobs the recipe could not reach, each
forwarded only when set so TRT-LLM's own defaults hold otherwise:

- cache_transceiver_runtime: "auto" silently resolves to the C++
  transceiver whenever it cannot confirm the model's preference, and a
  hybrid Mamba model under disaggregation needs the Python (v2)
  transceiver for its recurrent-state handoff -- so the recipe must be
  able to force it.
- kv_cache_bounce_size_mb: coalesces a request's scattered per-block KV
  into one contiguous fabric-VMM buffer and a single multi-rail NIXL
  write, sidestepping per-block registration failures.
- kv_transfer_timeout_ms: TRT-LLM's 60 s default is tuned for short
  prompts at low concurrency; at high rollout concurrency bulk ctx-side
  timeouts feed a cancel/retry churn that stresses the transceiver, so
  large multi-turn workloads want a much larger value.

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit 407f383)
Signed-off-by: Zongfei Jing <[email protected]>
At high rollout concurrency the single DisaggServerActor (one uvicorn
process) saturates around 17 turns/s and becomes the replica's ceiling:
conversations pile up ahead of the engines while GPUs idle. This makes
the frontend horizontally scalable and, since the same investigation
needed to see where pre-generation time actually goes, adds permanent
end-to-end timing stamps.

Frontend sharding (num_frontend_workers, default 1 = old behavior):
- trtllm_generation: replica x frontend actor fan-out; NeMo-Gym receives
  every frontend URL and its per-session client selection pins each
  conversation to one frontend (sticky routing is per-process state, so
  stickiness only holds within a frontend -- pinning sessions is what
  makes N processes correct).
- Deterministic ports (frontend_base_port + idx on the pinned node) and
  serve-from-constructor: a Ray-restarted actor re-binds the same port,
  so the URL Gym holds stays valid across crashes.
- Snowflake node_id = replica_idx * num_frontends + frontend_idx keeps
  ctx_request_id unique across frontends (process_id is hardwired 0
  in-process and time.monotonic shares an origin per node).

Per-request work moved off the hot single processes:
- gen_tokids_ctxbytes / gen_strip_message_history: the gen leg carries
  b64 int32 token ids instead of a 30k-int JSON array plus the full
  message history it never reads.
- frontend_tokenize: frontends render the chat template and tokenize
  via build_spliced_prompt_ids -- the exact pipeline the adapters use,
  now hoisted to module level as the single source of truth -- and
  attach prompt_token_ids_b64 to the ctx leg. Inbound payloads are
  normalized through ChatCompletionRequest.model_dump(exclude_unset)
  first: the raw Gym payload orders tool-JSON keys differently than the
  pydantic-normalized form the adapters see, and the chat template is
  sensitive to that order (turn-1 only; the splice covers later turns).
  Guarded by ctx-side shadow validation
  (NRL_TRTLLM_TOKENIZE_SHADOW_RATE) which re-tokenizes a sample on the
  adapter and logs any divergence with a decoded token window.
- The supplied-ids short-circuit in the adapter route is hoisted before
  template rendering, so the gen leg no longer renders a template whose
  output it discards.

Full-path timeline stamps (all gated NRL_TRTLLM_EMIT_TIMELINE_FIELDS):
- Frontend ASGI middleware stamps receive/forward times as headers;
  the response wrapper surfaces them as nemo_fe_recv/fwd_ts_us.
- The ctx adapter emits nemo_ctx_{arrival,queued,first_scheduled,
  done}_ts_us on the context leg; the disagg service relays them onto
  the final response (tekit carries the relay change), decomposing the
  previously-opaque pre-generation leg into frontend / ctx submit /
  ctx queue / prefill / KV-handoff segments per model call.

Validated end to end at conc-512 (2048 rollouts, 30-turn agentic
workload, 61k model calls): stamps present on 100% of calls, sub-leg
sum identical to the parent leg, tokenize shadow divergence zero.
Sharding the frontend (N=8) plus frontend tokenize took the equal-GPU
disagg configuration from well behind the aggregated baseline to ahead
of it.

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit 769aab4)
Signed-off-by: Zongfei Jing <[email protected]>
…compute diagnostics

The conversation-affine ADP router (kv_cache_routing_conversation_affinity)
pins a conversation's turns to the rank that holds its prefix, but it only
sees the id when the request carries ConversationParams. The HTTP adapter
never forwarded one, so under attention-DP every turn landed on an
effectively random rank: measured at 2P-DEP8 / conc 512 only 17-26% of turns
found the previous turn's KV on the serving rank (about 1/DEP) and the ctx
engine re-prefilled most of the history every turn.

Read the id from the body's conversation_params (the Gym model proxy sends its
session id there; one session per rollout) or, failing that, from the id the
disagg service stamps onto disaggregated_params for its ctx/gen legs, and pass
ConversationParams(conversation_id) to llm.generate_async. No id means no
affinity, i.e. the previous behaviour. With the id: 96-97% of turns on the
rank holding their prefix, ctx prefill tokens -66% to -88%.

Also surface the context leg's compute accounting on the ctx response and
relay it with the other ctx stamps (nemo_ctx_computed_tokens,
nemo_ctx_first_begin, nemo_ctx_num_chunks): the engine's cached_tokens
overshoots the real reuse point by a few blocks, so computed tokens and the
first chunk's begin position are what the reuse analysis needs. These live on
the RequestOutput (the per-choice CompletionOutput only forwards
cached_tokens), hence the extra request_output argument.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
(cherry picked from commit 14690fb)
Signed-off-by: Zongfei Jing <[email protected]>
…ontend middleware

The MLPerf warmup sends required_prefix_token_ids (the vLLM server's prefix
override extension) with every synthetic request. TRT-LLM's OpenAIDisaggServer
validates bodies against extra="forbid" models, so the field turned each
warmup request into a 400 and the warmup exception then took the driver down
before run_start. The TRT-LLM engine adapter derives the on-policy prefix from
the assistant messages and ignores the top-level field, so dropping it in the
disagg frontend (like the Dynamo wrapper does) keeps both paths identical.

(cherry picked from commit 46cd1a1)
Signed-off-by: Zongfei Jing <[email protected]>
The disagg base commit bundled a second, independent change:
NRL_SKIP_FAILING_EMPTY_ROLLOUT, which turns "NeMo Gym returned a rollout with
no assistant turn" from a hard failure into a prompt-only sample masked out of
the loss. That is an error-handling policy change, not part of prefill/decode
disaggregation, and it changes behaviour for every backend. Take it out and
restore the original raise.

Removed:
- nemo_rl/environments/nemo_gym.py -- restored verbatim; its entire delta over
  the branch point was this feature. An empty rollout raises ValueError again,
  with the original message (no NRL_SKIP_FAILING_EMPTY_ROLLOUT hint).
- nemo_rl/experience/rollouts.py -- restored verbatim; likewise, the only
  delta was carrying the `empty_rollout` flag onto the batch.
- nemo_rl/algorithms/grpo.py -- _apply_empty_rollout_filter and its two call
  sites (grpo_train, async_grpo_train) plus the
  train/num_masked_seqs_by_empty_rollout metric.

Kept in grpo.py: the disagg-aware gpus_per_instance sizing, which is the part
of that commit's grpo.py delta that does belong to disaggregation -- under PD
the NVLink-domain unit is the replica, not the engine, and sizing by the
engine skipped domain pinning entirely.

Verified: no empty_rollout / NRL_SKIP_FAILING_EMPTY_ROLLOUT /
num_masked_seqs_by_empty references remain, and the three modules compile.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
…ntract

Review fixes for the PD disaggregation PR, scoped to nemo_rl/ and tests/.
The build script, Dockerfile, docs, exemplar YAML and pyrefly.toml changes
are left for a separate commit.

The one behaviour change is the frontend port. `base_port + fe_idx` carried
no replica term while the node pin (`addrs[base + fe_idx % per_replica]`)
did, so with num_frontend_workers=1 every replica sharing a node asked for
17300. Nothing surfaced the collision: start_server computes base_url before
binding and returns it unconditionally, uvicorn's bind failure calls
sys.exit(1) which only unwinds the daemon thread, and wait_ready's /health
GET is then answered 200 by the winner bound on 0.0.0.0. The losers
advertised the winner's URL and their engines idled with no exception and no
timeout -- at the exemplar's defaults on one 8-GPU node that is 4 replicas
on one port and 6 of 8 GPUs idle for the whole run. Now
`base_port + replica_idx * n_fe + fe_idx`, still deterministic per
(replica, frontend) so a restarted actor re-binds the same port, plus a
thread-liveness assert after wait_ready so a future bind failure cannot pass
silently again.

TrtllmDisaggArgs becomes TrtllmDisaggConfig(BaseModel, extra="allow"), per
the config conventions: all 14 fields carry their default on the schema
rather than at call sites (num_frontend_workers, frontend_base_port,
gen_tokids_ctxbytes, gen_strip_message_history and frontend_tokenize each
had one). The routers and cache_transceiver_backend become Literal --
ctx_router was typed str, so "round_robin" parsed fine and silently
discarded the prefix affinity the context engines depend on.
resolve_trtllm_disagg_config mirrors resolve_vllm_video_config.

DisaggServerActorImpl.start() drops its parameters. Serving is the
constructor's job -- Ray replays __init__ on actor restart but never method
calls -- so the `if self._base_url is None` branch was unreachable, and also
less capable than the real path: no frontend_tokenize, no model_name, and
routers hardcoded over the configured values. Asserted instead of kept as a
fallback that could only come up misconfigured.

generation_token_ids and attach_rollout_fields move to module level so the
disagg-vs-aggregated rollout-field contract is testable without importing
tensorrt_llm; the adaptor keeps only the JSONResponse re-wrap. A miss there
drops a turn's training data silently (nemo_gym.py skips a message with no
generation_token_ids), so it should not be the one half that no test can
reach.

trtllm_http_server stops emitting choices[].token_ids unconditionally: on a
build whose ChatCompletionResponseChoice does not declare the field, the
write 400s at the disagg server's extra="forbid" re-validation -- which is
exactly where the token_id:N logprobs fallback is meant to take over. Gated
on a cached capability probe so the read and the write agree.

Tests: test_trtllm_disagg_server.py had no pytest.mark.trtllm, so no L0
shard collected it and deleting required_prefix_token_ids from the strip
list would have left CI green; test_trtllm_http_server.py had the same
pre-existing gap. Adds middleware coverage for the tokenizer-failure
fallback, the disaggregated_params guard, chunked body reassembly and
non-JSON passthrough, plus rollout-field, disagg-config and _plan_engines
cases.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
Nine of TrtllmDisaggConfig's fields appeared in no example config, so the
only way to discover num_frontend_workers, frontend_base_port,
gen_tokids_ctxbytes, gen_strip_message_history, frontend_tokenize,
cache_transceiver_runtime, kv_cache_bounce_size_mb, max_tokens_in_buffer or
kv_transfer_timeout_ms was to read the schema.

Every value written here is the schema default, so the exemplar documents
without becoming a second source of truth that can go stale against the
BaseModel. The four Optional knobs are null, which is what "don't forward,
let TRT-LLM keep its own default" actually looks like -- not the illustrative
values a reader would otherwise mistake for defaults.

ctx_trtllm_kwargs/gen_trtllm_kwargs become explicit empty dicts, and the
comment now says a key set there WINS over trtllm_cfg: pinning
tensor_parallel_size in the per-role block makes
trtllm_cfg.tensor_parallel_size a silent no-op for the disagg layout, which
is not obvious from the merge order.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
trtllm_http_server reads a conversation id that nothing populates today. Gym
is the only component that knows the rollout identity and no released Gym
sends it -- conversation_params appears nowhere in the tree, including upstream
main. It arrives with NVIDIA-NeMo/Gym#3582 ("forward gym session id as backend
conversation id"), still open, after which the Gym submodule pin has to be
bumped for this branch to see an id at all.

Until then a turn lands on an effectively random attention-DP rank and the
context engine re-prefills most of its history: 17-26% of turns find their
prefix on the serving rank versus 96-97% once the id flows, measured at
2P-DEP8 / conc 512. Nothing fails, so the note also says not to treat such a
run as a disaggregation baseline.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
pyrefly checks an explicit allow-list, and the new module was missing from it
while its three siblings in the same package were listed -- so its 654 lines
reported zero errors because nothing looked at them. It is clean once added.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
Covers what the schema and the exemplar cannot: that NeMo RL owns the replica
and the refit safety while delegating the KV handshake and the intra-replica
routing to OpenAIDisaggServer, and that the replica count is derived from the
inference cluster size rather than configured.

A replica is fronted by num_frontend_workers disagg servers, not one, so the
topology section is written in terms of the N*F URLs that reach
dp_openai_server_base_urls and the three levels at which a trajectory acquires
affinity: Gym's sticky sha256(session_id) picks the frontend, that frontend's
in-process ctx_router picks the context engine, and the relayed
conversation_id picks the attention-DP rank. Only the first is NeMo RL's to
control, and the stickiness is a correctness requirement rather than
load-spreading -- two frontends of one replica share no view of which context
engine holds a conversation's prefix.

Also records why the frontend's port carries both indices, why serving starts
in the constructor (Ray replays __init__ on actor restart but never method
calls), and that frontends are CPU-only so num_frontend_workers never enters
the GPU budget.

Listed in docs/index.md under Design Docs so Sphinx does not treat it as an
orphan page.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
Running the TRT-LLM backend with prefill/decode disaggregation under
NeMo-Gym failed at three separate points, each hidden behind the previous
one. All three are invisible to CI: no nightly runs TRT-LLM behind
NeMo-Gym, because every SWE/Gym job uses vllm, dynamo or megatron
generation and every TRT-LLM job runs a math task with Gym off.

1. setup_nemo_gym_config() handled vllm, dynamo and megatron and raised on
   anything else, while should_use_nemo_gym() already routed trtllm off
   trtllm_cfg.expose_http_server. Both run_grpo_nemo_gym.py and
   run_grpo_single_controller.py call the former unconditionally, so every
   trtllm + Gym run died at startup. Set the same two flags the vllm branch
   sets.

2. TRT-LLM's ChatCompletionRequest declares tools and tool_choice and stops
   there, and its models are extra="forbid", so the OpenAI-standard
   parallel_tool_calls field 400s. A tool-use dataset carries it in
   responses_create_params and Gym's vllm_model proxy forwards it verbatim,
   so every rollout request failed and the run died in rollout collection.
   Add it to the fields the frontend strips.

3. The disagg orchestrator encodes the forwarded worker request with
   msgspec msgpack and flags it with X-TRTLLM-Msgpack, deliberately leaving
   Content-Type as application/json so FastAPI still routes the body
   (tensorrt_llm/serve/openai_client.py: MSGPACK_HEADERS). The engine HTTP
   adapter called request.json() unconditionally and died on the first byte
   with "can't decode byte 0x8e" -- a msgpack fixmap header. This is the
   frontend-to-engine leg, so it failed for every rollout. Only the request
   leg is encoded this way; responses stay ordinary JSON.

Close the coverage gap with a nightly that pairs TRT-LLM disaggregation
with NeMo-Gym. It uses the SWE pivot single-step tool-use environment
rather than the agentic SWE-bench rollout, so it needs no Apptainer and no
per-instance SIFs and runs on ordinary CI nodes. It inherits the vLLM
sibling (grpo-qwen3-1.7b-1n8g-megatron-super-swe1) and reads the same swe1
split, so only the generation backend, the topology and async differ.
2 nodes x 4 GPUs: 4 training GPUs on Megatron CP4, and 4 rollout GPUs
holding one replica of 1 context engine (TP2) plus 1 generation engine
(TP2) behind 2 disagg frontends. gen_tokids_ctxbytes,
gen_strip_message_history and frontend_tokenize are on because they are
the paths most likely to perturb token-level agreement between the sampler
and the trainer, which is what the driver's token_mult_prob_error gate
measures.

Verified on 2 GB200 nodes: 5/5 steps, token_mult_prob_error 1.009-1.018
against the gate of 1.1, gen_kl_error 0.0006-0.0014 against 0.02.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
shuyixiong and others added 9 commits October 13, 2026 08:46
TrtllmDisaggServerConfig inherited DisaggConfig, which made its declared type
wider than its meaning: trtllm_cfg.disagg_server could name engine counts and
frontend settings that nothing in that block reads, and the resolver then
rejected them at runtime. Type and check disagreed.

Drop the inheritance. The class now carries exactly the four fields
build_config forwards to DisaggServerConfig, and the one resolver becomes two:

  resolve_disagg_layout()         generation.disaggregation -> DisaggConfig
  resolve_disagg_server_config()  trtllm_cfg.disagg_server  -> this class

The call sites split cleanly along the same line: every layout read is engine
planning, and the only mechanics reads are the four kwargs handed to
DisaggServerActor. A layout key under disagg_server is now rejected by name
rather than by overlap, since extra="allow" would otherwise swallow it.

Also in this change:

- Two error messages still told the user to set
  trtllm_cfg.disaggregation.enabled=false, a key that moved to
  generation.disaggregation one commit ago. Nothing reads the old path and
  TrtllmSpecificArgs is not extra="forbid", so following that advice would
  have been silently ineffective.
- trtllm_http_server picks the prompt ids up with a single
  `prompt_token_ids or prompt_token_ids_b64`, decoding by type. The old
  `is None` guard meant an empty int list shadowed a present b64 and forced a
  full re-render.
- grpo drops the pipeline_parallel_size factor from the TRT-LLM GPU budget;
  the backend asserts pp == 1, so it was a call-site default for a dimension
  that cannot vary.
- Restores the design doc's Prerequisites section, which the previous commit
  deleted by accident, and trims the comments across these schemas.

Verified on 2x GB200 with grpo-qwen3-1.7b-2n4g-megatron-trtllm-disagg-swe1:
5/5 steps, median token_mult_prob_error 1.01856 and step-5 1.01479 (gate
< 1.1), mean gen_kl_error 0.00146 (gate < 0.02).

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
The shard had drifted badly: at the previous commit it was 16 failed / 8
passed, and nothing caught it because the tests had not been run since the
disaggregation work began. They now pass 26/26.

Three separate drifts:

- The _config() helper put `disaggregation` inside trtllm_cfg, but the code
  reads it on generation. Every disagg test silently resolved to defaults, so
  the two that assert on an enabled layout were passing vacuously and the
  tiling test never raised.
- _bare_generation() built a TrtllmGeneration via __new__ without _disagg,
  _engine_tps or _engine_owner_indices, all of which __init__ derives and the
  dispatch paths read.
- Dispatch moved from worker_group.get_dp_leader_worker_idx /
  run_all_workers_single_data to per-engine run_single_worker_single_data
  keyed by _engine_owner_indices (the sharding grid cannot model engines of
  differing width, and DP leaders are one worker per replica). The lifecycle
  and refit tests still asserted the old API; they now assert one call per
  engine addressed to that engine's owner, plus that the old path is not
  taken.

New coverage for the config split: the layout and server schemas carry
disjoint keys, and a layout key under trtllm_cfg.disagg_server is rejected.

Running this shard needs the MPI launch context scrubbed first --
`import tensorrt_llm` calls MPI_Init, and under srun OMPI tries SLURM PMI and
aborts:

  for v in $(env | awk -F= '/^(PMI|PMIX|MPI|OMPI|SLURM)_/{print $1}'); do
    unset "$v"
  done

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
Bugs:
- grpo: setup() called .get() on the DisaggConfig that MasterConfig
  produces, so a disaggregated trtllm run crashed with AttributeError.
  Size the NVLink-domain instance via resolve_disagg_layout(), which
  accepts both the dict and the model.
- trtllm_worker_async: the CacheTransceiverConfig(backend="DEFAULT")
  fallback keyed off a trtllm_cfg.disaggregation block that no longer
  exists, so disagg engines started without a KV transceiver. Key it off
  the _disagg_role the driver stamps instead.
- trtllm_http_server: return_prompt_token_ids_b64 was read off the
  LLM-level DisaggregatedParams, which drops it, so gen_tokids_ctxbytes
  never took effect. Read it from the wire model before converting.

Review follow-ups:
- Fix ruff F821 (Request) and the pyrefly errors in the disagg files;
  drop recipe keys equal to their defaults.
- Explain why the disagg server's 4xx override is needed (it keeps the
  engine's "context length exceeded" text) and test it.
- Update stale comments that said ChatCompletionResponseChoice.token_ids
  does not exist upstream; it is declared at the pinned f94eeb37.
- Drop the unreachable disaggregated_params.conversation_id fallback.
- Drop the design doc's stale Prerequisites section and note that
  colocated generation is not supported yet.
- Extract and test the disagg backend guard and the DP-leader check;
  add tests for get_topology_sorted_pg_indices.
- Docstring/comment nits in config.py, trtllm_generation.py and the
  disagg-swe1 recipe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
…ests

- Add replica_width() and role_tensor_parallel_size() to the trtllm
  config module. TrtllmGeneration._plan_engines and grpo's NVLink-domain
  sizing both use them, instead of each keeping its own copy of the
  prefill/decode width formula. The copy in grpo is the one that drifted
  and crashed on a DisaggConfig.
- Inline the non-trtllm disaggregation guard back into grpo.setup() and
  drop the grpo-side helpers and their tests. replica_width is tested
  next to _plan_engines.
- test_trtllm_http_server: parse_chat_messages_coroutines returns four
  values at the pinned TRT-LLM, so unpack with *_ like the server does.
  These tests never ran on main: the file was unmarked, and every unit
  shard skips unmarked tests under models/generation/trtllm/.
- test_trtllm_worker_async: configure_worker now also returns
  bundle_pg_idx.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
The executor loop's NCCL collectives deadlock against the blocking
ncclCommInitRank in init_collective (seen as a 600 s watchdog kill).
Wrap it in control_action_decorator, as PR #4122 does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
…htly

They were copied from the vLLM super-swe1 sibling; the TRT-LLM backend
does not need them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
The parametrized enables_http_server test already covers trtllm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
- grpo.setup(): fail fast when disaggregation is enabled without NeMo-Gym,
  instead of building the whole fleet and failing at the first rollout.
- TrtllmDisaggServerConfig: extra="forbid". build_config forwards only the
  declared fields, so any other DisaggServerConfig key validated and then
  silently did nothing.
- Placement error: say that replica-by-replica placement rejects some
  mixed-TP layouts that a different packing would fit.
- Fix stale symbol names and the recipe's MoE-split comment.
- The prefill adapter is a thread in the engine's worker process, not its
  own process.
- Design doc: drop the removed disaggregated_params conversation-id
  fallback, and fix hard line breaks, blank-line runs and list wrapping.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
…er disagg

Two disagg-only bugs that made rollouts diverge from the vLLM baseline:

- History tool calls were dropped from the prompt. NeMo-Gym sends assistant
  messages with both `reasoning` and `reasoning_content`; TRT-LLM's
  ChatCompletionMessageParam union serializes those with `tool_calls: []`.
  The disagg route and the frontend tokenizer both dumped such requests, so
  the engines rendered the conversation without any of its tool calls.
  Materialize tool_calls right after validation in a shared
  ChatCompletionRequest subclass. With it, prompts match vLLM token for
  token.
- Enabling partial KV reuse under disaggregation currently causes
  convergence issues (~15% of sequences diverged from the trainer's
  logprobs). The recipe turns it off for now; full-block reuse is kept.

Over 100 swe1 steps the disagg run now tracks vLLM: 368/1600 vs 339/1600
correct, 1 vs 2 masked sequences, median token_mult_prob_error 1.017 for
both.

Also stop forcing enable_thinking=True in the engine adapter; like the vLLM
server, only the configured default_chat_template_kwargs are applied.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
@shuyixiong
shuyixiong force-pushed the shuyix/trtllm_disagg branch from 3861818 to 5ccbb92 Compare October 13, 2026 15:48
@shuyixiong
shuyixiong requested a review from RayenTian October 13, 2026 15:55
RayenTian
RayenTian previously approved these changes Oct 14, 2026
@RayenTian

Copy link
Copy Markdown
Contributor

LGTM. Approved.

The engine's HTTP server rendered Gym's raw request, while the disagg route
renders what TRT-LLM's ChatCompletionRequest dumps. Chat templates serialize
each tool verbatim (`tool | tojson`), and Gym sends tools as
{"function": ..., "type": "function"} (the OpenAI SDK TypedDict's field
order), whereas validation reorders them to {"type": "function",
"function": ...} -- the canonical form in Qwen's function-calling docs, HF's
get_json_schema, and what vLLM renders. So every aggregated TRT-LLM prompt
differed from disagg and vLLM in its tools block (swe1 and the qwen35_397b
mlperf CI runs: 0 identical first-turn prompts vs vLLM).

Add normalize_chat_inputs() next to build_spliced_prompt_ids and use it in
both the engine route and the disagg frontend tokenizer, so every renderer
normalizes the same way. The request model moves with it.

swe1, steps 1-3: aggregated and disagg first-turn prompts are now
token-identical to the vLLM baseline (6/6 each).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>

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

Excellent work on this one: it brings prefill/decode disaggregation to TRT-LLM GRPO rollouts end to end, from engine layout and placement to per-replica frontends that keep each Gym trajectory on one replica, and it ships with a design doc and tests that go red when the placement fallbacks are mutated.

Great to see the 100-step convergence comparison against the matching vLLM baseline posted in the description; the TRT-LLM disagg run can be read directly against it.

Scope: the full diff at 89817a8 (engine layout and placement, disagg frontends, engine HTTP server and worker, grpo and cluster glue, recipe, nightly, design doc), with extra attention to the newest commits b84791f, 5ccbb92 and 89817a8.

Checked:

  • Non-disagg paths — every new grpo.py guard short-circuits on disaggregation.enabled, and the vLLM, SGLang and Megatron NVLink sizing is unchanged; the only reordering is topology-sorted PGs on the TRT-LLM per-node path, which does not affect colocated IPC pairing.
  • Frontend identity — the N*F <= 256 assert matches TRT-LLM's request-id bound at the pinned commit, and ports are unique across replicas and frontends.
  • Refit — parking the executor loop around NCCL group creation is exception-safe, since TRT-LLM's control_action releases in a finally.
  • Topology sort — each fallback (CPU-only, single PG, unknown domains, missing node) returns identity, and each has a test that goes red when the fallback is mutated.

Remaining comments are on folding the role-override handling into one resolver (including how role-level trtllm_kwargs are merged), the exemplar's pinned role TP, the frontend port default, the design doc's placement example and wording, an unused helper, a docstring wording, and a naming question on the disagg config field.

Comment thread examples/configs/grpo_math_1B.yaml Resolved
- Resolve prefill/decode role overrides once, in resolve_role_overrides()
  (called from configure_generation_config). Each role block becomes that
  role's whole engine config, and its trtllm_kwargs are deep-merged over
  generation.trtllm_kwargs. Previously the merge was one level deep, so a
  role's kv_cache_config replaced the shared one and dropped, e.g., the
  recipe's enable_partial_reuse: false. The five separate merges
  (_role_overrides, _role_kwargs, the per-engine override map, the worker
  merge, the trtllm_kwargs merge) are gone; the driver now only stamps each
  engine's role.
- grpo_math_1B_trtllm: interpolate the role TPs from the shared TP instead
  of pinning them to 1, so an inheriting recipe that raises TP and enables
  disaggregation keeps that TP.
- Move frontend_base_port from 17300 (inside the 9000-65000 ephemeral range
  on GB200) to 8300, in a band of its own, [8300, 8556), in the port tables.
- Design doc: an engine that fits in a node is never split across nodes;
  replace the config example with a layout that tiles 4- and 8-GPU nodes.
- Drop the unused _tokenizer_backend_name, store _disagg_cfg and
  _disagg_server_cfg directly, and reword _assert_direct_dispatch_allowed.

swe1, 3 steps: disagg and aggregated first-turn prompts still match the
vLLM baseline token for token (6/6 each), with no masked sequences.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: shuyixiong <[email protected]>
@shuyixiong
shuyixiong requested a review from yuki-97 October 14, 2026 12:36
@yuki-97
yuki-97 enabled auto-merge (squash) October 15, 2026 04:34
@yuki-97

yuki-97 commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

/ok to test 5d85225

@yuki-97
yuki-97 merged commit 339fad1 into main Oct 15, 2026
117 checks passed
@yuki-97
yuki-97 deleted the shuyix/trtllm_disagg branch October 15, 2026 09:56
shuyixiong added a commit that referenced this pull request Oct 16, 2026
…#4095)

Signed-off-by: shuyixiong <[email protected]>
Signed-off-by: Zongfei Jing <[email protected]>
Co-authored-by: Zongfei Jing <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
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 Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants