Repository navigation
feat(trtllm): shard-to-shard (nccl_reshard) refit for the TRT-LLM backend - #4861
Conversation
679ed5d to
c53ae9a
Compare
|
/ok to test c53ae9a |
shuyixiong
left a comment
There was a problem hiding this comment.
Adds shard-to-shard (nccl_reshard) refit for the TRT-LLM backend: the Megatron trainer sends routed MoE experts straight into each engine's EP slots, and everything else rides the misc broadcast.
What works well
TrtllmGeneration.get_nccl_reshard_layouts(): the generation backend reports its own destination meshes. C8 asks to give the other backends the same call shape, not to remove this.build_local_expert_lookupreads TRT-LLM's owninitial_local_expert_idsinstead of recomputing the EP slot math, refuses under EPLB, and the reshard path raises on a slot mismatch (_build_expert_local_param_map).convert_expert_projection_stackis shared by the collective and reshard paths, and_reload_bucket/_finish_refitremove the duplicated refit bracket.- The destination reuses
LocalParamSpec/HFToLocalParamMapinstead of a TRT-LLM-only type.
CI status: only the bot checks (DCO, copyright, semantic title) ran on this head; lint and unit tests have not. Running the lint hooks locally gives the failures in C3, C4 and C6, and a static trace of an existing unit test gives C1 and C2.
Fix in this PR
- (C1) An existing Megatron unit test fails in all 15 cases: the new
_refit_is_trtllm_nccl_reshard()readsself.cfg, which the test never sets. - (C2) The same test's
postcases also fail, becausespec.postnow runs after the whole layer is sent. - (C3) ruff import-sort error in
test_trtllm_fp8.py. - (C4) The new recipe fails
configs-minimize-check; its header also says ETP=1 is needed rather than tested. - (C5) Trainer ETP>1 with a TRT-LLM destination passes the setup check; the "until tested" guard covers vLLM only.
- (C6) Five of the ten pyrefly errors, with a diff that fixes them (the other five belong to C8).
Suggestions
7. (C7) The default-on direct expert load never matches a module on the shipped Qwen3.5 VLM recipe, so every flush falls back to model_loader.reload.
8. (C8) TRT-LLM's reshard methods take different arguments from vLLM / Megatron, and the synchronizer guesses the call shape from a dict key.
9. (C9) The disaggregated two-layout path has no unit test and no run.
10. (C10) No test for the TRT-LLM reshard refit lifecycle or its prepare step; also drop queued stacks on failure (nit).
11. (C11) The single-layout send now keeps a whole layer of buffers alive, which contradicts "exactly as before".
12. (C12) A malformed refit env var hangs the job instead of failing at setup.
13. (C13) Docs and the exemplar comment still say TRT-LLM is not supported; the new knobs are undocumented.
14. (C14) _local_shard_slices is copied from the vLLM backend.
15. (C15) Dead state_dict_info write and unreachable branches in prepare_nccl_reshard_refit_info.
16. (C16) Stale "timing counters" comment.
17. (C17) PR body: refit-time and memory numbers against the collective sibling recipe.
Follow-up (not asked in this PR): _recv_bulk_params is the third copy of the "group by PP stage, rotate streams, wait on events" receive loop (vLLM vllm_backend.py#L2577-L2612, Megatron megatron_worker.py#L2147-L2173). A shared helper in nccl_reshard_utils.py would let one fix reach all three; worth a tracking issue.
The traces in C1, C2 and C12 and the suggested tests in C9 and C10 were not run: there is no GPU environment in this review.
Generated by Claude Code
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
Reviewed all 16 changed files across controller/layout setup, trainer transfers, and TRT-LLM receiving/quantization, including their directly affected callers and tests.
Two test regressions need correction before merge:
- C1: the new test module imports an optional dependency before non-TRT lanes can deselect it.
- C2: the trainer changes invalidate an existing refit regression fixture and assertion.
Lower-severity suggestions cover exception propagation (C3), an unnecessary full-stack allocation (C4), outdated transport documentation (C5), missing performance evidence (C6), and comment maintenance (C7).
The separation between routed-expert transfers and the existing misc broadcast is worth preserving. The inspected aggregated/disaggregated rank layouts are consistent with the destination mesh construction.
This was a source-only review: no tests, linters, or benchmarks were executed. The mounted TensorRT-LLM workspace contains its build wrapper, not the upstream loader implementation, so upstream loader behavior could not be independently verified.
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.
d70e8fd to
ad3a4b6
Compare
aef8c01 to
24618e5
Compare
yuki-97
left a comment
There was a problem hiding this comment.
@hchings @shikicloud could you help review trtllm related part?
@RayenTian could you help review other part?
RayenTian
left a comment
There was a problem hiding this comment.
Thanks for the unusually thorough self-review. I verified the ad3a4b64a fixes landed correctly (ran ruff, pyrefly reports 0 errors, minimize-check passes), traced the new offload_policy_before_refit relaxation and it is safe — offload_before_refit frees only non-parameter state (grads/optimizer/caches) while the reshard reads only parameters — and the new bitwise test_trtllm_direct_expert_load.py is a genuinely valuable drift guard.
Two net-new items the self-review missed:
- (C1) The default-on direct expert load passes
allow_partial_loading=Truetopreprocess_weights, a keyword only the Qwen3.5 mapper accepts; aqwen3_moeengine (also inSUPPORTED_MODEL_TYPES) crashes on its first refit. Verified against the pinnedv1.3.0rc28source. Includes the fix and the test that would have caught it. - (C2) The HEAD commit now allows
offload_policy_before_refitfor TRT-LLM +nccl_reshard, but the PR body and the still-open self-comment C13-AI2 say it is not.
Nothing blocking beyond C1. The rest LGTM.
87f4b11 to
5a57b33
Compare
|
/ok to test 5a57b33 |
5a57b33 to
a9bc489
Compare
RayenTian
left a comment
There was a problem hiding this comment.
LGTM at a9bc4894. Four low-priority validation/helper cleanup suggestions and one non-blocking request to track generation-side ETP support.
The full pre-commit suite passed. CPU probes covered shard geometry, per-layout scheduling, and the repaired Qwen3 preprocessing branch; async wrapper tests passed.
Missing backend dependencies or CUDA prevented completion of some tests. All eight GPU direct-load equivalence cases were skipped. GPU/NCCL and disaggregated end-to-end execution were not verified in this review; performance results in the PR are author-reported.
Generated by OpenAI Codex
yuki-97
left a comment
There was a problem hiding this comment.
Merge blockers — please rebase on main; the PR is 50 commits behind and the "Check if PR branch is up to date" job allows at most 10.
Thanks for adding shard-to-shard routed-expert refit for TensorRT-LLM.
The posted A/B timings make the refit improvement clear, and the reported 100-step run adds longer-run evidence for the earlier generic-loader path. Thanks also for the extensive self-review.
Scope: Full PR reviewed at 3ed2f62; this refresh rechecks the seven pending comments.
Checked:
- Generation layouts — prefill and decode receive separate bulk groups and plans.
nccl_reshard_weight_synchronizer.py:335–433 - Transfer ordering — source tensors are materialized once per layer across layouts, and bulk streams finish before the misc broadcast.
megatron_policy_worker.py:4599–4623,megatron_policy_worker.py:4526–4545 - Direct loading — wrapper-aware owner lookup and signature-gated preprocessing follow the pinned loader contract.
trtllm_backend.py:613–706 - Support guards — each engine role requires pure EP and generation PP 1; dense MLP bulk parameters are rejected before dispatch.
nccl_reshard_utils.py:874–908,nccl_reshard_utils.py:603–628
Static inspection only; GPU, NCCL and training tests were not run here. This head has no training-test CI results.
Remaining comments are on:
- TRT-LLM transport configuration and setup diagnostics.
- Consolidating communicator and source-plan state to avoid maintaining two fields for each.
- Whether
finallyis needed to clear the local layer cache on errors.
nit
- Updating refit documentation for per-layout plans and TRT-LLM precision support.
- Shortening the four function-body comment blocks.
- A second nightly combining BF16, in-flight updates and PD disaggregation for
nccl_reshard.
Generated by Codex (#4999 version)
…with local-expert quantization and a reshard-aware trainer offload (#4217) (cherry picked from commit 8a9efdc, adapted to main: TRT-LLM WorkerExtension refit lifecycle, prefill/decode disagg roles, spec.materialize(), no refit_payload_mode / sync_params, generation.disaggregation + trtllm_cfg.{prefill,decode}_engine in the nccl_reshard support check.) Signed-off-by: Zongfei Jing <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: shuyixiong <[email protected]>
…; add GB200 recipe - Reject TRT-LLM nccl_reshard plans with non-expert bulk params (dense MLP layers) on the controller, before the plan reaches the engines. - Keep offload_before_refit unchanged; only the TRT-LLM reshard refit skips the post-bulk torch.cuda.empty_cache(). vLLM/Megatron behaviour is as on main. - Gate the new per-refit timing prints behind NRL_REFIT_TIMING_LOG. - Declare refit state on the worker/extension classes instead of probing with getattr; hoist stdlib imports; drop the unused _load_received_experts. - Fix ruff lint/format in the files this PR touches. - Add grpo-qwen3.5-35ba3b-4n4g-megatron-trtllm-mxfp8-noncolocated-reshard to the GB200 nightly. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: shuyixiong <[email protected]>
Remove the NRL_REFIT_TIMING_LOG switch and every [refit-timing] / per-phase timing print it gated: the controller offload/transfer split, the trainer's per-layout bulk-send events and misc-produce timer, and the TRT-LLM engine's phase and convert/reload stats. The per-bucket stream syncs that existed only to time convert vs. reload go too. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: shuyixiong <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: shuyixiong <[email protected]>
- Give rebuild_nccl_reshard_comm_group / prepare_nccl_reshard_refit_info one call shape on vLLM, Megatron and TRT-LLM (layout_index=0, list of plans); drop the synchronizer's multi_layout guess and _gen_parallelism. - Single-layout bulk send frees each source right after its send again; only several layouts cache a layer's materializations. - Reject trainer ETP>1 for TRT-LLM until tested; drop the recipe's redundant ETP override (configs-minimize-check). - TRT-LLM receiver: match MoE weight owners to expert prefixes as a dotted suffix (the Qwen3.5 VLM nests its decoder under llm.), fail loudly on a missing or ambiguous owner, parse refit env knobs at prepare time, drop queued stacks on failure, remove dead misc-meta branches, share local_shard_slices with vLLM. - nccl_reshard_refit_async raises the worker exception like its siblings; fp8 conversion skips the gather when every expert is local. - Tests: two-layout send/synchronizer, refit lifecycle, prepare step, owner naming, malformed knobs, async errors, full-local conversion; defer the tensorrt_llm import so non-TRT lanes can collect the module. - Docs: TRT-LLM support, limits and knobs in the design doc, refit guide and grpo_math_1B.yaml; shorten in-function comments; pyrefly fixes. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: shuyixiong <[email protected]>
validate_offload_policy_before_refit limited TensorRT-LLM generation to the default collective transport, so a TRT-LLM nccl_reshard run could not release trainer gradient buffers / optimizer state before refit. NcclReshardWeightSynchronizer already runs policy.offload_before_refit() ahead of the transfer independent of the generation backend, and the reshard moves only parameters, so the gate was the only thing missing. Accept (None, "nccl_reshard") for TensorRT-LLM, same as vLLM; mcore stays Megatron-generation only. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: shuyixiong <[email protected]>
…twise The direct expert load replays a copy of TRT-LLM's _load_weights_impl_v2 MoE branch, so a TRT-LLM bump could make it load different bytes than the loader without any test noticing. Build one EP rank of a real one-layer Qwen3.5-MoE VLM (decoder under the wrapper's llm., mapper still bound to the wrapper as before the first reload), load the same received expert stacks both ways, and compare every expert parameter byte for byte. Covers EP2 rank 0 and rank 1, loading all projections at once or one call per projection. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: shuyixiong <[email protected]>
Direct expert load called preprocess_weights(..., allow_partial_loading=True) on every mapper, but only Qwen3.5's accepts the keyword; Qwen3 MoE inherits the base no-op (returns None, never called by its loader) and raised TypeError on its first refit. Call it only when the mapper takes the keyword, and run the bitwise direct-load test for qwen3_moe as well. Also drop TrtllmGeneration._refit_membership, which was written but never read. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: shuyixiong <[email protected]>
- Remove the tp % ep and expert-TP checks from the TRT-LLM layout and synchronizer paths; check_nccl_reshard_refit_support already rejects non-pure-EP layouts at setup. - Remove the same-role TP-width check; _plan_engines gives every engine of a role the same TP. - Receive into expert buffers via LocalParamSpec.materialize(), declaring the metadata dtype as wire_dtype. - Have _run_on_engines delegate to _run_on_engine_subset. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: shuyixiong <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: shuyixiong <[email protected]>
Declare TRT-LLM refit transport choices, keep one communicator and source-plan map per worker, and simplify layer-cache cleanup. Update per-layout refit documentation and add BF16 in-flight PD nightly coverage. Validation: Ruff and Pyrefly; 716 unit/config checks; five-step BF16 in-flight PD recipe with all numerical gates passing (W&B kschhrcf). Signed-off-by: shuyixiong <[email protected]>
3ed2f62 to
6b66193
Compare
|
@yuki-97 Rebased on main ( Local container validation: Ruff and Pyrefly passed; 22 affected Megatron refit tests, 459 weight-sync/interface tests, 205 TRT-LLM tests, and 30 recipe/config checks passed (716 total). TRT-LLM unit tests ran with launcher MPI variables stripped and The new BF16 in-flight PD nightly also passed all five steps and numerical gates: W&B, mean generation KL 0.00160, median token probability error 1.02679, and median weight sync 0.422 s. These are local validation results; CI for the new head has not been triggered here. |
|
/ok to test 6b66193 |
One conflict, in megatron_policy_worker.py: main (#4861) builds the nccl_reshard refit info in a local refit_info instead of self.nccl_reshard_refit_info. The source_uses_real_reshard_op flag this branch adds now goes into that local dict. Signed-off-by: Terry Kong <[email protected]>
What does this PR do ?
Adds shard-to-shard (
policy.generation.refit_transport: nccl_reshard) refit for the TRT-LLM generation backend: the Megatron trainer reshards the routed MoE experts straight into each TRT-LLM engine's EP-local slots withxferdtensor, and every other parameter rides the existing misc packed broadcast.Important
Scope of this version: MoE routed experts only, pure expert parallelism only (no expert TP).
*.mlp.experts.{gate,up,down}_proj) take the shard-to-shard path. Attention, norms, embeddings, router, shared experts and MTP go through the misc broadcast, as before.moe_expert_parallel_size == tensor_parallel_size(somoe_tensor_parallel_size == 1) andpipeline_parallel_size == 1. Expert-TP or mixed EP×TP layouts are rejected at startup bycheck_nccl_reshard_refit_support.gate/up/down_projwould need TP-sharded writes, which TRT-LLM's loader does not accept (it shards full tensors itself).check_trtllm_nccl_reshard_bulk_paramsrejects such a plan during setup, before it reaches the engines; use the collective refit (refit_transport: null) for those models.[model.][language_model.]layers.N.mlp.experts, plusmtp.layers.N.mlp.experts), i.e. Qwen3 / Qwen3.5 MoE.Why pure EP: the TRT-LLM destination hands the received tensors to TRT-LLM's own MoE loader, which expects each local expert's full tensor and applies its internal layout (fused
w3_w1, FP8/MXFP8 scale padding/swizzle) itself. Under pure EP the received[E_local, out, in]stack is exactly that; under expert TP the transfer would deliver only a1/tpslice per expert.How it works
TrtllmGeneration.get_nccl_reshard_layouts()groups engines by role. Aggregated serving is one layout; prefill/decode disaggregation is two (the roles may differ in TP/EP), each with its own per-PP-stage bulk communicator and refit plan. The trainer sends both layouts on separate streams so the transfers overlap.NcclExtensionbuilds oneLocalParamSpecper grouped expert projection: a[E_local, out, in]bf16 staging buffer, then FP8/MXFP8 conversion of just those experts (bf16 engines load the views directly) and a batched load into the MoE modules. The EP slice is checked against TRT-LLM'sinitial_local_expert_ids; a mismatch is an error, never a partial update. The refit is bracketed byWorkerExtension'sbegin/finalize/finish_weight_update, withdrain/recompute_kvfollowingin_flight_weight_updatesas in the collective path.fp8.build_local_expert_lookupreadsinitial_local_expert_ids, so the collective refit of FP8/MXFP8 engines only converts the experts each rank stores (e.g. 32 of 512 at EP16) instead of the whole stack.offload_policy_before_refitis now allowed with TRT-LLM +nccl_reshard(main rejected it): the reshard reads only parameters, so freeing gradient buffers, optimizer state and caches before the transfer is safe, asdocs/guides/refit.mdnow says. A 5-step offload run (W&B) dropped the trainer from 76 to 18 GB per rank before each refit. Separately, the TRT-LLM reshard refit skips the trainer'storch.cuda.empty_cache()between the bulk transfer and the misc broadcast (seconds of refit bubble; the misc buffers come from the caching allocator anyway). vLLM / Megatron generation keep the existing behaviour.Debug knobs (env vars)
NRL_TRTLLM_REFIT_RELOAD_BATCH_BYTESNRL_TRTLLM_REFIT_DIRECT_EXPERT_LOAD1NRL_REFIT_NUM_STREAMS2Tests
tests/unit/models/generation/trtllm/test_trtllm_nccl_reshard.py(layouts, local slot specs, local quantization, pure-EP and dense-MLP checks, disaggregated roles),test_trtllm_fp8.py(local-expert lookup), plus the existingweight_sync/ recipe suites.grpo-qwen3.5-35ba3b-4n4g-megatron-trtllm-mxfp8-noncolocated-reshard— the existing...-trtllm-mxfp8-noncolocatedrecipe (Megatron TP2/EP4/ETP1, TRT-LLM TP4/EP4 MXFP8) withrefit_transport: nccl_reshard, same metric gates.GB200 run: 100 steps
W&B run
f30lxn6d:grpo-qwen3.5-35ba3b-4n4g-megatron-trtllm-mxfp8-noncolocated-reshardwithgrpo.max_num_steps=100, 4×GB200 nodes (2 train + 2 generation),nemo-rl-nightly-20261026image, branch at56ed511fb. Completed all 100 steps, exit 0.train/gen_kl_errortransfer_and_update_weightstrain/rewardBulk (routed experts, xferdtensor) moves 60.0 GiB per refit and the misc broadcast moves 5.4 GiB; the misc broadcast takes about 0.3 s on the trainer side.
The 100-step run above predates the direct-expert-load owner fix, so its expert loads went through the generic
model_loader.reloadfallback (refit about 1.36 s). The A/B below runs the fixed code.A/B: collective vs nccl_reshard refit
Same config for both: 4×GB200 nodes (Megatron TP2/EP4/ETP1 on 2 nodes, TRT-LLM TP4/EP4 MXFP8 on 2 nodes), Qwen3.5-35B-A3B, 5 steps, checkpointing off,
nemo-rl-nightly-20261026image, branch atad3a4b64a,NRL_TRTLLM_REFIT_RELOAD_BATCH_BYTESandNRL_TRTLLM_REFIT_DIRECT_EXPERT_LOADat their defaults. Step 1 includes warm-up and is left out of the medians.refit_transport: null)ibjg5fpv7lvzlilntransfer_and_update_weights, median of steps 2–5train/gen_kl_error, mean of 5 stepsray/node.N.gpu.M.mem_gb, caching-allocator reservations included), peak over the whole run rather than over the refit window alone. Trainer and TRT-LLM nodes are told apart by their memory curves: the trainer nodes load Megatron first, and the TRT-LLM nodes hold a flat KV-cache reservation.Follow-ups (not in this PR)
gate/up/down_projto the misc broadcast for TRT-LLM, lifting the dense-layer restriction.Issues
N/A
Usage
Before your PR is "Ready for review"
Pre checks:
🤖 Generated with Claude Code