Skip to content

perf(vllm): batch BF16 TRTLLM expert layout conversion - #3669

Open
seonjinn wants to merge 103 commits into
NVIDIA-NeMo:mainfrom
seonjinn:sna/bf16-trtllm-two-gather-refit
Open

seonjinn wants to merge 103 commits into
NVIDIA-NeMo:mainfrom
seonjinn:sna/bf16-trtllm-two-gather-refit

Conversation

@seonjinn

@seonjinn seonjinn commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Convert all BF16 W13 experts with one indexed gather and all W2 experts with a second gather, instead of running two gathers per expert.
  • Limit the batched converter to the vLLM reload lifecycle; output layout and runtime parameter addresses remain unchanged.

Validation

Matched GB200/vLLM 0.29 A/B runs used BF16 training + BF16 rollout, FlashInfer TRTLLM MoE, disaggregated Async-1off, and refit_transport=nccl_reshard. Each run completed 20/20 steps. Values are means of steps 2-20; lower time is better.

Model Refit bubble, base -> PR E2E step, base -> PR Mean generation KL, base / PR W&B runs
Qwen3-30B-A3B 4.18 -> 3.68 s (-12.1%) 207.86 -> 205.58 s (-1.1%) 0.00189 / 0.00188 base / PR
Qwen3.5-35B-A3B 3.62 -> 3.29 s (-9.0%) 213.20 -> 210.66 s (-1.2%) 0.00103 / 0.00099 base / PR
Nemotron3 Super 4.88 -> 4.55 s (-6.8%) 46.89 -> 45.60 s (-2.7%) 0.00294 / 0.00309 base / PR

These are single matched run pairs, not statistically significant E2E or numerical-parity claims. No generation-KL NaN or refit failure was observed in these runs. The image lacked nccl.m2n.reshard, so both arms used the xferdtensor_python exact-transfer fallback despite the nccl_reshard setting; this A/B measures the BF16 TRTLLM conversion, not optimized NCCL M-to-N transfer.

Builds on #3659 (merged).

seonjinn added 24 commits August 7, 2026 02:01
Signed-off-by: seonjinn <[email protected]>
(cherry picked from commit 707968a)
Signed-off-by: seonjinn <[email protected]>
(cherry picked from commit cbd4138)
Signed-off-by: seonjinn <[email protected]>
(cherry picked from commit bda8858)
Signed-off-by: seonjinn <[email protected]>
(cherry picked from commit 2aa1570)
Signed-off-by: seonjinn <[email protected]>
(cherry picked from commit 4aece4b)
Signed-off-by: seonjinn <[email protected]>
(cherry picked from commit 1292dbe)
Signed-off-by: seonjinn <[email protected]>
(cherry picked from commit 56e27a8)
Signed-off-by: seonjinn <[email protected]>
(cherry picked from commit 0c33c30)
@copy-pr-bot

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

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 1dc3cf1

@seonjinn
seonjinn marked this pull request as ready for review August 16, 2026 21:29
@seonjinn
seonjinn requested review from a team as code owners August 16, 2026 21:29
@seonjinn
seonjinn marked this pull request as ready for review September 9, 2026 19:47
@seonjinn
seonjinn requested review from a team as code owners September 9, 2026 19:47
@seonjinn

seonjinn commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test d24868e

@seonjinn
seonjinn requested a review from guyueh1 September 10, 2026 19:44
@guyueh1

guyueh1 commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

@seonjinn this code applies a runtime patch to the vllm vllm.model_executor.layers.fused_moe.oracle module; there are multiple ways in nemo-rl to patch vllm (offline or runtime), is this context based way used anywhere else? should we follow the way in fp8.py, or patches.py?

I think this change is fine, but just wondering about if this is best practice for patching vllm

@seonjinn

Copy link
Copy Markdown
Contributor Author

The scoped context is intentional here. fp8.py installs process-lifetime model/loading patches, while patches.py rewrites or installs compatibility patches before worker initialization. This optimization is only valid during TRTLLM BF16 layerwise-reload initialization/finalization, so making it global would also affect normal model loading and unrelated calls. The context manager serializes mutation with an RLock, uses a ContextVar so another thread falls back to the original converter, and restores the exact original function on success or exception. I therefore kept it local to the reload lifecycle rather than adding another process-wide vLLM patch. The focused test covers activation, cross-thread fallback, and restoration.

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test 419742d

Signed-off-by: seonjinn <[email protected]>
@seonjinn seonjinn added CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) and removed CI:L1 Run doctests, unit tests, and functional tests labels Sep 17, 2026

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

Re-review via review-pr-team. No correctness blocker.

The batched converter matches vLLM 0.29.0's per-expert convert_moe_weights_to_flashinfer_trtllm_block_layout (same gate/up swap, same shape-keyed flashinfer permute-index cache, same output size); a numpy simulation of the index math came out byte-identical. The patch is scoped to the reload lifecycle with a correct finally restore, and the ContextVar keeps other threads on the original converter. Parameter addresses stay stable through vLLM's own replace_parameter(prefer_copy=...) plus the layerwise copy_, independent of this change.

Four low-severity items inline: (1) vacuous finalize assertion + untested exception-path restore, (2) bf16 arange + assert_close tolerance cannot catch an intra-row shift, (3) context also entered on DSV4 FP8 refits, (4) record the vLLM call-site dependency in the docstring.

FYI, no action: the inner context at :1340 is redundant at all current finalize() call sites, and the RLock is held across the whole transfer, which is fine since nothing else enters it.

Tests were not executed locally (no GPU environment; Linux-only lockfile). Local gate: compileall, ruff (I/check/format) clean.

)

def finalize_layerwise_reload(_model, _model_config):
assert unquantized.convert_moe_weights_to_flashinfer_trtllm_block_layout

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.

2 action items. Test gap in test_batched_bf16_trtllm_layout_is_scoped_to_reload_finalize.

AI-1. This asserts a function object is truthy, which always holds, so it never checks which converter finalize() sees. Since every caller runs finalize() inside the outer context at vllm_backend.py:1355, the inner with at :1340 is also unobservable from this test. Action: either drop the stub assertion (and optionally the redundant inner with), or make it real:

Suggested change
assert unquantized.convert_moe_weights_to_flashinfer_trtllm_block_layout
assert (
unquantized.convert_moe_weights_to_flashinfer_trtllm_block_layout(
{}, object(), object()
)
== batched_result
)

with batched_converter.call_count == 2 at line 421.

AI-2. Restore is only asserted on normal exit (lines 417-420); the finally at vllm_backend.py:283-287 is untested. Action: add a case that raises inside with vllm_backend._use_batched_bf16_trtllm_layout_conversion(): and asserts the converter is original and _BF16_TRTLLM_LAYOUT_PATCH_ACTIVE.get() is False afterwards.

Not executed locally (no GPU environment).

Comment on lines +311 to +316
w13 = torch.arange(num_experts * w13_rows * cols, dtype=torch.bfloat16).view(
num_experts, w13_rows, cols
)
w2 = torch.arange(num_experts * w2_rows * cols, dtype=torch.bfloat16).view(
num_experts, w2_rows, cols
)

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.

1 action item. The equivalence oracle is weaker than it looks.

torch.arange(..., dtype=torch.bfloat16) rounds above 256 (577 distinct values out of 1536; rows 8-11 hold 17 distinct values each), and torch.testing.assert_close uses rtol 1.6e-2 for bf16, so neighbours like 512 and 516 compare equal. An element shift inside a row would pass. The conversion is a pure permutation, so exact equality on random data is the right check. Action:

Suggested change
w13 = torch.arange(num_experts * w13_rows * cols, dtype=torch.bfloat16).view(
num_experts, w13_rows, cols
)
w2 = torch.arange(num_experts * w2_rows * cols, dtype=torch.bfloat16).view(
num_experts, w2_rows, cols
)
generator = torch.Generator().manual_seed(0)
w13 = torch.randn(
num_experts, w13_rows, cols, generator=generator
).to(torch.bfloat16)
w2 = torch.randn(num_experts, w2_rows, cols, generator=generator).to(
torch.bfloat16
)

and replace the two assert_close calls at lines 346-347 with torch.equal. Not executed locally (no GPU environment).

initialize_layerwise_reload(reload_target)
self._nrl_layerwise_reload_active = True
yield finalize
with _use_batched_bf16_trtllm_layout_conversion():

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.

1 action item. Low severity.

The context is entered for every native layerwise refit, so a DeepSeek-V4 FP8 refit (use_deepseek_v4_fp8, :1311) also runs the unguarded from vllm.model_executor.layers.fused_moe.oracle import unquantized at :254 and rebinds a converter it never calls. The sibling _unquantized_flashinfer_trtllm_modules (:127) tolerates the oracle being absent; here an ImportError/AttributeError after a vLLM bump lands in the try at :1353, sets _nrl_layerwise_reload_failure, and leaves the worker unusable for a path that never needed the patch. Action: enter it only on the BF16 branch, e.g. layout_patch = nullcontext if use_deepseek_v4_fp8 else _use_batched_bf16_trtllm_layout_conversion and with layout_patch(): at :1340 and :1355.


@contextmanager
def _use_batched_bf16_trtllm_layout_conversion() -> Iterator[None]:
"""Use the batched converter only while vLLM rebuilds TRTLLM MoE state."""

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.

1 action item. Documents a fragile coupling.

Following up on @guyueh1's question: a scoped context patch has precedent in modelopt_moe_amax_aliases, whose docstring records the verified vLLM version and the loader it hooks. This helper depends on a similar detail: it works only because oracle/unquantized.py resolves the converter through module globals. If vLLM moves that import inside the function, the patch becomes a silent perf no-op that neither new test catches. Action:

Suggested change
"""Use the batched converter only while vLLM rebuilds TRTLLM MoE state."""
"""Use the batched converter only while vLLM rebuilds TRTLLM MoE state.
Verified against vLLM 0.29.0: ``fused_moe/oracle/unquantized.py`` resolves
the converter through module globals, so rebinding the attribute reaches
it. Conversion runs from the layerwise ``online_process_loader`` during
``load_weights`` and again in ``finalize_layerwise_reload``.
"""

@seonjinn

Copy link
Copy Markdown
Contributor Author

/ok to test c4d2887

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

LGTM

@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:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants