Skip to content

[WS1][CUDA][Qwen3-Next] MoE route/combine contract with a batch-invariant grouped expert GEMM (RFC #428 stack 5/11) - #503

Merged
Flink-ddd merged 18 commits into
RL-Align:test-qwennextfrom
fusheng-ji:feat/ws1-qwen3-next-moe-route-combine
Nov 19, 2026
Merged

Flink-ddd merged 18 commits into
RL-Align:test-qwennextfrom
fusheng-ji:feat/ws1-qwen3-next-moe-route-combine

Conversation

@fusheng-ji

@fusheng-ji fusheng-ji commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack: #466 (merged) → #467 → #468 → #469 → this PR → #507 → #543 → #544 → #549 → #557 → benchmarks (#551), base test-qwennext; merges after #469. This PR's own diff. RFC #428 row moe_route_combine_contract, CUDA.

What

The routed-MoE contract for Qwen3-Next-80B-A3B (512 experts, top-10), per stage (full table in docs/operators/qwen3-next-moe-route-combine.md):

Stage Order and dtype Atomics
router BF16 x, W upcast; one pinned vLLM batch-invariant GEMM, IEEE FP32 none
selection argsort(logits, descending, stable)[:, :10]: score descending, ties to the lower expert id none
weights fixed-order softmax and renormalisation over a fixed pairwise tree, FP32 none
experts per (token, route) row: gate_up GEMM → SwiGLU in FP32 → BF16 → down GEMM; no routed weight in the kernel, no sum over routes none, one writer per row
combine e0·w0, then + e_k·w_k for k = 1..9 in route order, FP32; one BF16 cast none
backward per expert in ascending id; dW slices written once; dx summed per token in ascending expert order; route-weight gradient: the sum over H goes through fixed_order_row_sum (custom autograd function in combine_routes) none
  • rl_engine/models/qwen3_next/qwen3_next_forward.py: shared_linear, shared_router, stable_top10_routes, combine_routes, grouped_route_linear, shared_moe. Fails closed on CPU or ROCm tensors, on any vLLM other than 0.30.0, on VLLM_TRITON_USE_TD and on TF32 Triton dots.
  • rl_engine/models/qwen3_next/qwen3_next_tp_blocks.py: TP4MoE with the HF load/export of all 512 experts, a replicated router and shared-expert gate, and MCore TP attributes.
  • rl_engine/models/qwen3_next/qwen3_next_tp.py: Megatron-style copy/reduce autograd boundaries through RL-Kernel's fixed-order collective.
  • rl_engine/validation/common/tensor_identity.py: raw-bit identity (signed zero distinct, NaN/Inf rejected, dtype must match).
  • tools/validation/models/qwen3_next/qwen3_next_tp_moe_check.py: the TP4 gate on real layer-0 weights (torchrun, 4 GPUs).
  • combine_routes has a custom autograd function: the stock autograd backward summed grad * expert_output over H with torch.sum, whose reduction order depends on the batch shape, so the route-weight gradient (and dx through the router) stopped being batch-invariant from 16 rows up on H100 and B200. The function sums H with fixed_order_row_sum. New test: first 8 rows alone vs the same rows inside larger batches.
  • Layout as reviewed on [WS1][CUDA][Qwen3-Next] TP distributed logprob parity: fixed reduction order, selected-token logprob exact across NCCL settings (RFC #428 stack 9/11) #549: the prior-art runner and plot live in the benchmark PR ([WS1][CUDA][Qwen3-Next] Comparison benchmarks and plots for the Qwen3-Next stack: MoE, attention, logprob, EP (RFC #428 stack 11/11) #551), raw evidence is a release ZIP with a summary in reports/experiments/qwen3_next/.

Prior art & reuse decision

Decision: reuse vLLM's batch-invariant GEMM (router, backward) and its fused_moe Triton kernel (expert GEMMs); implement the FP32 routing, tie rule, combine, backward and TP4 boundaries. No surveyed implementation is batch-invariant and has a batch-invariant backward. The batch-invariant ones (vLLM BI=1, SGLang deterministic) are inference-only and route in BF16, which picks a different expert set than FP64 routing for 11 of 256 tokens; Megatron-core + TE, VIME's training path, routes in FP32 but changes routing, output, dx and dW with batch size.

Library Implementation (version / file) Forward BI Backward BI Tokens routed unlike FP64 Verdict
CUTLASS via FlashInfer cutlass_fused_moe (grouped GEMM) no (≥ 256 tokens) no backward 11 / 256 not BI; inference only
FlashInfer 0.6.18.post1 fused_moe.cutlass_fused_moe no (≥ 256) no backward 11 / 256 not BI
FlashAttention — — — — N/A: attention library, no MoE
vLLM 0.30.0 fused_topk + fused_experts, VLLM_BATCH_INVARIANT=0 no (≥ 256) no backward 11 / 256 not BI
vLLM 0.30.0 same, VLLM_BATCH_INVARIANT=1 yes no backward 11 / 256 BI, inference only → expert GEMM kernel reused
SGLang 0.5.21 Triton fused_moe, default / deterministic inference no / yes no backward 11 / 256 BI only in deterministic mode, inference only
Miles (radixark/miles@23d3d38) miles/kernels/moe/fused_experts.py (SGLang forward) + fused_experts_bwd.py, imported unmodified output equal over 20 launches, dx of probe rows 0 / 10 batch cells no, measured: over 20 identical launches dx, dW gate/up and dW down equal the first in 1 / 20 (BF16 tl.atomic_add); route-weight gradient 20 / 20 not measured backward not reproducible; 10 ms vs our 158 ms fwd+bwd (summary)
verl (volcengine/verl@e5a627c) no MoE kernel (searched verl/); trains through Megatron-core, HF/FSDP or VeOmni, rolls out through vLLM/SGLang — — — covered by those rows
Vime 0.3.2 Megatron-core MoELayer (no MoE kernel of its own) see Megatron row covered by Megatron row
Megatron-core 0.16 + TE 2.16 MoELayer, TE grouped GEMM, FP32 router, all-to-all (VIME's Qwen3-Next config) no (routes ≥ 256, output 1024) no (1024) 0 / 256 not BI
transformers 5.17.0 Qwen3NextExperts eager (verl FSDP path) yes no (1024) 11 / 256 backward not BI
RL-Kernel (this PR) shared_moe / TP4MoE yes yes 0 / 256

Batch invariance: 8 probe tokens alone vs first and last in 16-1024-token batches, forward (routes, output) and backward (dx, dW), bitwise. Miles was measured by importing its own kernels at the pinned commit (20 identical launches on the real layer-0 weights, bit for bit against the first; its forward uses SGLang's kernel with SGLang's deterministic tile).

Results (B200, H = 2048, 512 experts, top-10, width 512, BF16)

Qwen3-Next routed MoE prior art

RL-Kernel Megatron + TE vLLM BI=1 SGLang det. vLLM BI=0 SGLang default FlashInfer HF eager
max abs vs FP64 2.1e-3 2.2e-3 1.1e-1 1.1e-1 1.1e-1 1.1e-1 1.1e-1 1.1e-1
rel. L2 vs FP64 3.9e-3 4.6e-3 7.0e-2 7.0e-2 7.0e-2 7.0e-2 7.0e-2 7.0e-2
forward, 1 / 64 / 1024 / 4096 tokens (ms) 1.39 / 1.69 / 2.04 / 3.05 3.8 / 9.7 / 11.7 / 12.1 0.39 / 0.66 / 0.87 / 1.05 0.35 / 0.66 / 0.84 / 1.37 0.38 / 0.66 / 0.87 / 1.06 0.34 / 0.61 / 0.83 / 1.35 0.37 / 0.72 / 0.90 / 1.12 2.1 / 62 / 89 / 87
forward + backward, 64 / 1024 tokens (ms) 114 / 169 45 / 51 – – – – – 877 / 1284
  • The accuracy gap is routing: with BF16 router logits, 11 of 256 tokens select a different expert set than FP64 routing; with an FP32 router (this PR, Megatron-core) none do.
  • TP4, real layer-0 weights: all 12 cases pass on 4 ranks (HF round trip of all 512 experts, identical routes on every rank, full == chunked and reversed-order batches at 8/64/256/1024 tokens, training forward == no-grad forward, identical replicated router and shared-gate gradients).

Summary, tested commits and commands: reports/experiments/qwen3_next/qwen3-next-moe-route-b200.md; raw reports ZIP (SHA-256 9fcc7042…58cb0). Prior art measured at c58816b, TP4 gate at 2e950f3 (identical MoE code).

Status

  • Head 8e33c453, on top of [WS1][CUDA][Qwen3-Next] C6: GDN decode-step goldens and recurrent/conv state contract (RFC #428 stack 4/4) #469 and e514d42f (the route-weight gradient fix above). The last commit answers OpenCodeReview: the empty-input bias gradient is gated on needs_input_grad, and the shared_moe docstring now states the host synchronisation of the router-logit finiteness check; no result changes. CI is green on this head: lint, unit-tests, docs, DCO and the bot review pass; provider and ws1-gtest skip because no self-hosted runner is attached.
  • Ready for review. No known acceptance failure.
  • Known: slower than vLLM's non-strict MoE forward (2.04 vs 0.87 ms at 1024 tokens); about 0.5 ms is the FP32 IEEE router GEMM the contract requires. The backward is a per-expert loop (169 ms forward + backward at 1024 tokens vs 51 ms for Megatron + TE, which is not batch-invariant); it is the next thing to speed up.
  • Rerun after aligning the stack with the reviewed layout (clean clone of the stack top 90c09164, 4 × B200): the standalone TP4 MoE gate passed 12/12 on all four ranks, and the layers stages of the EP1 and EP4 chains passed with it. (before the route-weight fix; B200 rerun on e514d42f below, see History)

History

  • 2026-10-26 (review): two OpenCodeReview rounds on the stack (the bot re-reviews every PR's whole diff after each push); every finding of these two rounds is answered in its own thread or comment, most as repeats of earlier answers or as not applicable with the code reference. Fixes in this PR: d53ac95e triggers the provider job on rl_engine/validation/common/**. The fixes of the PRs below it are merged in; new head 9800e1a4. Kernel arithmetic is unchanged, so the measured results stand.
  • 2026-10-26: merged test-qwennext after [WS1][CUDA][Qwen3-Next] C1: zero-centred RMSNorm references and CUDA kernel (RFC #428 stack 2/4) #467 landed (c382dd4b), through [WS1][CUDA][Qwen3-Next] C6: GDN decode-step goldens and recurrent/conv state contract (RFC #428 stack 4/4) #469's new head 27212b65, in 68240ec3. One conflict, in the provider workflow's pytest step: [WS1][CUDA][Qwen3-Next] C6: GDN decode-step goldens and recurrent/conv state contract (RFC #428 stack 4/4) #469's fail-closed skip check now also runs this PR's check modules.
  • 2026-11-14 (finding and fix, H100 and B200): on H100 the stock combine_routes backward gave a route-weight gradient that was not batch-invariant at 16, 32, 64, 128, 256 and 1024 rows (equal at 8 and 9). e514d42f fixes it with a fixed-order row sum. H100 A/B on 4 × H100: previous head d5253a5c 322 passed, probe unequal at T ≥ 16; tree ce3f499d (= e514d42f) 323 passed (the extra one is the new regression test), probe equal at every T, TP4 MoE gate 4/4 ranks on both. Output and expert gradients were equal on both. Same on B200 (4 × B200, same A/B and probe): d5253a5c 322 passed, probe unequal at T ≥ 16; e514d42f 323 passed, new test passed, probe equal at every T; TP4 MoE gate 12/12 cases on 4/4 ranks on both. So the break is not Hopper-specific, and the fix holds on both architectures. Raw data: hopper-qwen3-next/pr503/b200-e514d42f (TP4 gate on the index plus the single layer-0 shard of revision 9c7f2fbe, which is all the gate reads).
  • 2026-11-18 (review): OpenCodeReview round on e514d42f: seven findings, each answered in its own comment. Two fixed in 8e33c453 (empty-input bias gradient now None when the bias does not require grad; docstring states the finiteness-check sync), five answered without a change. On 4 × B200 at 8e33c453: the qwen3_next suites 323 passed, 0 failed, 0 skipped, and an empty input leaves bias.grad as None for a bias without requires_grad. Raw data: hopper-qwen3-next/pr503/b200-8e33c453.

Tests

python setup.py build_ext --inplace
python -m pytest -q tests/validation/common/test_tensor_identity.py tests/models/qwen3_next/test_qwen3_next_forward_contract.py tests/models/qwen3_next/test_qwen3_next_tp_blocks.py
TRITON_F32_DEFAULT=ieee python -m pytest -q tests/models/qwen3_next/check_qwen3_next_forward.py      # needs vLLM 0.30.0
TRITON_F32_DEFAULT=ieee torchrun --nproc-per-node 4 tools/validation/models/qwen3_next/qwen3_next_tp_moe_check.py \
    --checkpoint <Qwen3-Next-80B-A3B-Instruct> --output <dir>
Check Result
CPU: tensor identity, forward contract, TP blocks 39 passed
layout check, pre-commit on all files, mkdocs build --strict clean
check_qwen3_next_forward.py (GEMM batch/chunk/reorder, route ties, combine order, MoE VJP vs FP64, route and output BI, grouped == per-expert bitwise) 23 passed
TP4 gate, 4 × B200 12 / 12 cases, 4 ranks
check_qwen3_next_forward.py -k combine_gradients (new: route-weight gradient, 8 rows alone vs inside larger batches), H100 and B200 1 passed on each
tests/models/qwen3_next/test_*.py + check_*.py, 4 × H100, tree ce3f499d (= e514d42f) 323 passed, 0 failed, 0 skipped
tests/models/qwen3_next/test_*.py + check_*.py, 4 × B200, e514d42f 323 passed, 0 failed, 0 skipped
TP4 gate, 4 × B200, e514d42f 12 / 12 cases, 4 ranks
tests/models/qwen3_next/test_*.py + check_*.py, 4 × B200, 8e33c453 323 passed, 0 failed, 0 skipped
empty input to shared_linear, bias with and without requires_grad, B200, 8e33c453 zero bias.grad / bias.grad is None

CI: the CPU tests are in ci.yml; check_qwen3_next_forward.py imports vLLM and runs in the self-hosted Qwen3-Next-provider-GPU workflow with TRITON_F32_DEFAULT=ieee, which now also triggers on rl_engine/validation/models/qwen3_next/** and tools/validation/models/qwen3_next/**.

Scope

CUDA, TP4 × EP1 (all 512 experts on every rank). EP4 is in #557; ROCm and other TP sizes are separate claims. Model-level parity uses this block but belongs to full_model_chain (#543).

Results (H100 / Hopper, H = 2048, 512 experts, top-10, width 512, BF16)

Run at tree ce3f499d (= head e514d42f). 4 × NVIDIA H100, driver 580.173.02, CUDA 13.0, torch 2.13.0+cu130, triton 3.7.1, vLLM 0.30.0, transformers 5.17.0, VLLM_BATCH_INVARIANT=0. Fresh worktrees, fresh builds, clean tree before and after. Baseline run at the previous head d5253a5c. Raw data and report: hopper-qwen3-next/pr503/b960f8ce.

Check d5253a5c (before) e514d42f tree ce3f499d
tests/models/qwen3_next/test_*.py + check_*.py 322 passed 323 passed
TP4 MoE gate (4 ranks, real layer-0 weights) 4/4 passed 4/4 passed
route-weight gradient equal across batch size, T = 8 / 9 yes yes
route-weight gradient equal across batch size, T = 16, 32, 64, 128, 256, 1024 no yes
output and expert gradients equal across batch size yes yes

Qwen3-Next routed MoE prior art on H100

RL-Kernel Megatron + TE vLLM BI=1 vLLM BI=0 HF eager FlashInfer
forward batch invariant (routes, output) yes no yes yes yes yes
backward dW batch invariant yes no no backward no backward yes –
backward dx batch invariant yes no no backward no backward yes –
tokens routed unlike FP64 0 / 256 0 / 256 11 / 256 11 / 256 11 / 256 11 / 256
max abs vs FP64 1.7e-3 2.1e-3 9.6e-2 9.6e-2 9.6e-2 9.6e-2
forward 1 / 64 / 1024 / 4096 tokens (ms) 1.77 / 2.70 / 3.79 / 5.58 5.8 / 14.9 / 18.3 / 18.4 0.50 / 1.80 / 2.61 / 3.06 0.50 / 1.51 / 2.14 / 2.43 3.7 / 125 / 177 / 178 0.50 / 4.0 / 5.1 / 4.7
forward + backward 64 / 1024 tokens (ms) 231 / 353 70 / 82 – – 2188 / 3183 –

The prior-art figure and table above were measured before e514d42f (the RL-Kernel row records f9caee24) and were not rerun at e514d42f. FlashInfer sm90a JIT needed libnvrtc.so on LD_LIBRARY_PATH (symlink to libnvrtc.so.13). Non-RL-Kernel rows use the #551 runner at 77d59a59. Diagnostics for the original torch.sum behaviour: hopper-qwen3-next/pr503/diagnostics.

…rouped expert GEMM

RFC RL-Align#428 moe_route_combine_contract (CUDA).

- Routing: FP32 router through the pinned vLLM batch-invariant GEMM, a
  fixed-order softmax, stable descending argsort (ties go to the lower
  expert id) and FP32 renormalisation of the ten selected weights.
- Experts: per-route gate_up and down projections through vLLM 0.30.0's
  fused_moe Triton kernel with the batch-invariant tile passed explicitly
  (BLOCK 64/64/32, SPLIT_K=1); no routed-weight multiply and no sum inside
  the kernel, so every (token, route) row has one writer. Bitwise equal to
  the previous per-expert GEMM loop at TP4 and TP1 widths; fails closed if
  VLLM_TRITON_USE_TD is enabled.
- Combine: ten ordered FP32 multiply-adds and one BF16 cast; no atomics.
- Backward: per-expert pinned GEMMs into one dense gradient buffer; dx is
  summed in ascending expert order.
- TP4 block: HF load/export for all 512 experts, replicated router and
  shared-expert gate, Megatron-style copy/reduce autograd boundaries moved
  into qwen3_next_tp.py.
- Prior-art runner and plot comparing HF transformers, vLLM fused_moe
  (BI=0/1) and FlashInfer cutlass_fused_moe; TP4 real-weight gate script.

Signed-off-by: Wenbo Ji <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 11ff8695-e780-4b7f-84a3-5f9928006136

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

…r-art runner

- Megatron-core 0.16 MoELayer with Transformer Engine grouped GEMM and fused
  permute, configured as VIME runs Qwen3-Next (FP32 softmax router, top-10,
  all-to-all dispatcher), including its backward.
- SGLang 0.5.21 Triton fused_moe in default and deterministic-inference mode.
  sgl_kernel cannot load next to torch 2.13, so its two kernels on this path
  are replaced by SGLang's own Triton moe_sum_reduce and JIT
  moe_align_block_size; any other sgl_kernel call fails loudly.
- --only and --merge combine reports from different Python environments.

Signed-off-by: Wenbo Ji <[email protected]>
…ured (B200, c58816b)

Every library in the reuse table is now measured: Megatron-core 0.16 + TE 2.16 as VIME configures Qwen3-Next, and SGLang 0.5.21 in default and deterministic-inference mode. The TP4 gate evidence is unchanged (2e950f3, identical MoE code).

Signed-off-by: Wenbo Ji <[email protected]>
…p as E402-exempt

The gate scripts insert the repo root into sys.path before importing
rl_engine and tools, which flake8 reports as E402. Mark those imports
with noqa, as the other tools/ scripts do.

Signed-off-by: Wenbo Ji <[email protected]>
Annotate the latency samples and accept the default-argument lambdas used as
timed calls. No behaviour change.

Signed-off-by: Wenbo Ji <[email protected]>
The tree is unchanged: RL-Align#469's refactor merge carries nothing this
branch lacks; this only makes the current RL-Align#469 tip an ancestor.

Signed-off-by: Wenbo Ji <[email protected]>
Per the layout review on RL-Align#549:
- the TP4 MoE gate moves to tools/validation/models/qwen3_next/;
- the prior-art runner and its plot move to the Qwen3-Next benchmark PR
  (benchmarks/models/qwen3_next/);
- the committed evidence directory becomes a ZIP release attachment with
  a short summary in reports/experiments/qwen3_next/ (download link,
  SHA-256, tested commits, commands); the bytes are unchanged.
The GPU workflow now also triggers on files under the qwen3_next/
validation directories.

Signed-off-by: Wenbo Ji <[email protected]>
@fusheng-ji fusheng-ji changed the title [WS1][CUDA][Qwen3-Next] MoE route/combine contract with a batch-invariant grouped expert GEMM (RFC #428 stack 5/8) [WS1][CUDA][Qwen3-Next] MoE route/combine contract with a batch-invariant grouped expert GEMM (RFC #428 stack 5/11) Oct 15, 2026
The raw results (JSON, figures, audit files) now live on the fork's pr_assets branch;
the documents link to them at a fixed commit.

Signed-off-by: Wenbo Ji <[email protected]>
@fusheng-ji
fusheng-ji force-pushed the feat/ws1-qwen3-next-moe-route-combine branch from f9caee2 to 8943c14 Compare October 23, 2026 21:44
fusheng-ji added a commit to fusheng-ji/RL-Kernel that referenced this pull request Nov 14, 2026
…note

The empty-token branch of _SharedLinear.backward returned a zero bias
gradient whenever a bias was present; gate it on needs_input_grad[2] like
the non-empty branch. The shared_moe docstring said the forward has no host
synchronisation, but stable_top10_routes checks the router logits for
finite values on the host; say so.

Signed-off-by: Wenbo Ji <[email protected]>
@fusheng-ji

Copy link
Copy Markdown
Contributor Author

OpenCodeReview · .github/workflows/qwen3-next-provider-gpu.yml (L28): the rl_engine/integrations/engines/train/vllm/qwen3_next* trigger path matches no tracked file, so the filter is dead.

Not changed. This workflow file is shared by the whole Qwen3-Next stack, and the next PR, #507, adds the files this entry covers: rl_engine/integrations/engines/train/vllm/qwen3_next_conv.py, qwen3_next_gdn.py and qwen3_next_provider.py. In this PR alone the entry matches nothing; once #507 lands it triggers the GPU job for those adapters. Dropping it here would only mean adding it back in #507.

@fusheng-ji

Copy link
Copy Markdown
Contributor Author

OpenCodeReview · tests/models/qwen3_next/check_qwen3_next_forward.py (L70): the empty-token sub-check relies on weight.grad/bias.grad being allocated; a provider that short-circuits zero-row inputs would leave them None, and torch.count_nonzero(None) raises TypeError instead of asserting the zero-gradient contract.

Not changed. For an empty input the backward returns torch.zeros_like(weight) and a zero bias gradient for every operand that requires grad (_SharedLinear.backward, empty branch), so both gradients exist and the check asserts they are zero. If a provider ever left them None, torch.count_nonzero(None) would raise and the test would fail; it cannot pass silently, so the check does tell a missing gradient apart from a correct one.

@fusheng-ji

Copy link
Copy Markdown
Contributor Author

OpenCodeReview · tests/models/qwen3_next/test_qwen3_next_forward_contract.py (L43): comparing fixed_order_row_sum with an FP64 sum at rtol=1e-5, atol=1e-4 looks flaky for a plain FP32 sequential reduction at width 512.

Not changed. fixed_order_row_sum is a pairwise tree of elementwise adds, not a sequential chain, so its rounding error grows with log2(width), and the inputs come from a seeded CPU generator, so every run sums the same values in the same order and gets the same bits. On this test's own inputs, the largest error is 1.5e-5 at width 512 against a tolerance of at least 3.4e-4. The worst error-to-tolerance ratio over all five widths is 0.018, and 20 repeated calls are bitwise identical. The reference is the double-precision sum rounded to FP32.

@fusheng-ji

Copy link
Copy Markdown
Contributor Author

OpenCodeReview · tests/models/qwen3_next/check_qwen3_next_forward.py (L143): the inactive-expert gradient assertion does not validate sparse dispatch, since a dense implementation that multiplies by a zero routing weight would pass too.

Not changed. This assertion checks the gradient contract, not compute sparsity: an expert that no token selects must get an exactly zero dW, so nothing leaks into unused expert slices (a stray write, or a 0 * inf from a dense path). This PR does not claim sparse compute as a contract. The dispatch itself is checked bit for bit against per-expert GEMMs by test_grouped_experts_are_bitwise_the_per_expert_gemms and test_grouped_projection_is_bitwise_the_per_expert_gemm.

@fusheng-ji

Copy link
Copy Markdown
Contributor Author

OpenCodeReview · tests/models/qwen3_next/check_qwen3_next_forward.py (L99): the reference upstream gradient comes from the BF16 actual output (2 * actual.float()); building it from the double expected would make the reference VJP exact.

Not changed. The check compares vector-Jacobian products, so both sides must use the same upstream vector. combine_routes' backward receives g = 2 * actual (the gradient of actual.float().square().sum()), and the double reference is evaluated at that same g. The comparison therefore measures only the backward's error. With 2 * expected, the reference would use a different g from the one the provider received, and the difference would then include the forward rounding.

@KJLdefeated KJLdefeated left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Overall looks good, just some questions before approve:

  1. Is TP invariance supported? Is Tp4 == Tp1? If this RFC does not require TP invariance, that's ok ignore my questions.
  2. Non-blocking: to make best performance, consider using MegaMoE to overlap communication and computation? And I believe MegaMoE can also reach BI by some configuration. (Maybe it is not this PR's scope, you can ignore me.)
  3. This query on RFC (Non-blocking): Is Qwen3-Next really needs TP4? Normally MoE only use EP, TP4 would cause more overhead. I just want to check if TP4 is really worth to do.

fusheng-ji added a commit to fusheng-ji/RL-Kernel that referenced this pull request Nov 17, 2026
…, EP4 router/combine gate) into RL-Align#551

Signed-off-by: Wenbo Ji <[email protected]>
@fusheng-ji

Copy link
Copy Markdown
Contributor Author

OpenCodeReview · rl_engine/models/qwen3_next/qwen3_next_forward.py (L221-L222): the finite check torch.isfinite(router_logits).all() forces a device-to-host synchronization on every forward, although the shared_moe docstring says the forward has no host synchronisation.

Fixed in 8e33c45: the shared_moe docstring now says the forward synchronises with the host for the fail-closed finiteness check on the router logits. The check stays: non-finite router logits must raise instead of being routed, and test_stable_route_tie_boundary_and_router_gradient asserts the ValueError.

@fusheng-ji

Copy link
Copy Markdown
Contributor Author

OpenCodeReview · rl_engine/models/qwen3_next/qwen3_next_forward.py (L127): in the empty-token branch the bias gradient is returned whenever ctx.has_bias, while the other returns gate on ctx.needs_input_grad.

Fixed in 8e33c45: the empty-input branch now returns the bias gradient only when ctx.has_bias and ctx.needs_input_grad[2], as the non-empty branch does. Autograd already discarded a gradient returned for an input that does not require grad, so results do not change. Checked on B200 at 8e33c453: tests/models/qwen3_next/test_*.py + check_*.py 323 passed, 0 failed, 0 skipped (4 GPUs, same count as e514d42f); check_qwen3_next_forward.py + test_qwen3_next_forward_contract.py 36 passed (1 GPU); and a direct check on an empty input gives a zero (64,) bias.grad when the bias requires grad and bias.grad is None when it does not.

@fusheng-ji

Copy link
Copy Markdown
Contributor Author

OpenCodeReview · rl_engine/validation/common/tensor_identity.py (L26): zero-element tensors are reported as identical, so an acceptance check can pass vacuously when both sides are empty.

Not changed. Two empty tensors of the same shape and dtype are identical, and the shape check already fails when a broken path drops tokens while the reference does not (for example (0, 2048) against (4, 2048)). Returning False for empty inputs would make the predicate fail on valid empty batches: the empty-input path of shared_linear is a tested contract, and the helper is the comparison for every bitwise check up the Qwen3-Next stack. Coverage, meaning that something was actually compared, is asserted by the callers through their fixed shapes and case counts (the TP4 gate checks 12 cases on 4 ranks, for example), not by the equality predicate. The torch.empty(0) case in test_logical_identity_does_not_require_matching_strides records that behaviour on purpose.

@fusheng-ji

Copy link
Copy Markdown
Contributor Author

OpenCodeReview · rl_engine/models/qwen3_next/qwen3_next_tp_blocks.py (L24): a production model module imports a helper from rl_engine.validation.common.

Not changed in this PR. rl_engine/validation is part of the installed package ([tool.setuptools.packages.find] include = ["rl_engine*"]), so the import cannot fail in an install. The contributor guide puts shared validation mechanics in validation/common/ and keeps rl_engine/utils/ for when no domain-specific owner fits; it has no rule against models importing it, and upstream already has such imports (rl_engine/models/qwen3/reference.py, rl_engine/config/workload.py, rl_engine/integrations/engines/train/). The replica drift check uses the same raw-bit definition (finite, same dtype, signed zero) as the acceptance checks; a local copy would let the two drift apart. Later PRs in this stack import the same helper from four more production modules, so moving it would be a stack-wide refactor, not a change to this one.

@fusheng-ji

Copy link
Copy Markdown
Contributor Author

@KJLdefeated, replying to your review.

Thanks for the review. I measured both points before answering. Everything below is on the official checkpoint's layer-0 MoE weights, 4 × B200, torch 2.13 + vLLM 0.30.0, 1024 tokens unless stated.

1. TP invariance (TP4 == TP1). Not bitwise as the PR stands, and the PR does not claim it. TP4MoE keeps all 512 experts on every rank but shards each expert's intermediate dimension (128 of 512 per rank); every rank's down GEMM reduces over its own 128 columns, and the four BF16 partials are summed by RL-Kernel's fixed-tree all-reduce, (r0 + r1) + (r2 + r3). A single GPU reducing all 512 columns in one GEMM rounds differently. Measured on #503 head 8e33c453:

TP1 variant vs TP4 output input grad router / shared-gate grad expert + shared-expert weight grads
plain TP1 (one 512-wide GEMM) differs: 58 % of elements, max abs 4.9e-4 differs (69 %) differs equal
canonical TP1 (four 128-wide shards in sequence on one GPU, BF16 partials summed (p0 + p1) + (p2 + p3), the same for every gradient TP4 all-reduces) bitwise equal bitwise equal bitwise equal bitwise equal

Forward at 8 / 256 / 1024 tokens, forward + backward at 256 / 1024. So TP1 == TP4 is reachable by construction, because the collective was built for it: its fixed tree gives the same result at TP 1, 2, 4 and 8 as long as each rank's input is the matching subtree of one canonical reduction. The price in this direct form is 3.2× the forward and 3.8× the forward + backward of plain TP1 (6.5 vs 2.0 ms and 656 vs 171 ms; TP4 is 1.9 / 170 ms per rank), since the four shards run one after another.

What the PR does hold at TP4: identical routes on every rank, full == chunked == reordered batches at 8 to 1024 tokens, training forward == no-grad forward, identical replicated router and shared-gate gradients (the TP4 gate, 12 / 12), and forward and backward batch invariance. As I read RFC #428, the parity target is the same topology on both sides, vLLM rollout and VIME replay at TP4 (the full_model_chain claim in #543, 16 / 16 raw-bit at L2). The canonical TP1 path above covers the MoE block only; a full-model TP1 == TP4 would need the same treatment for every row-parallel layer (attention o_proj, GDN out_proj), so it is a follow-up I can open if the RFC wants mixed-topology training (for example TP4 rollout with TP1 training).

2. DeepGEMM MegaMoE. Thanks for the pointer; it was not in the survey, so I measured it. vLLM 0.30.0 vendors it (vllm/third_party/deep_gemm/mega) and uses it for DeepSeek-V4 and Kimi-K3, not Qwen3-Next. I ran bf16_mega_moe in #551's EP comparison harness (the one behind #557's prior-art table), with RL-Kernel's FP32 router and top-10 routes fed in, so only the expert compute and combine differ. MegaMoE is token-parallel, so each EP rank gets 1/4 of the tokens and the outputs are re-replicated with an all-gather (counted in the latency).

repeat batch grid (8 probe rows in 8–1024-token batches) EP4 == EP1 max abs vs FP64 EP4 / EP1 forward backward
MegaMoE BF16, fast_math on (default) / off yes yes yes 1.5e-5 1.16 / 1.43 ms none
RL-Kernel qwen3_next_ep (#557) yes yes yes 1.8e-5 2.25 / 1.91 ms yes, 51 ms at EP4, batch-invariant, EP4 == EP1
vLLM fused_experts, VLLM_BATCH_INVARIANT=1 yes yes no 8.7e-4 0.51 / 0.79 ms none

So MegaMoE's forward is deterministic, batch-invariant on this grid, EP-invariant, and about 2× faster than RL-Kernel's at EP4. It does not give the same bits as RL-Kernel's forward (max difference 3.1e-5; fast_math on and off also differ by 7.6e-6 from each other), and it has no backward. It could only be used if both rollout and replay ran it as the forward, with a separate deterministic backward that recomputes the expert activations, because the fused kernel does not expose them. That belongs to the EP4 path in #557, not this TP4 × EP1 block.

3. Is TP4 worth it for Qwen3-Next? Agreed that EP is the natural layout for the routed experts, and the same run shows it: RL-Kernel's MoE forward + backward is 170 ms per rank at TP4 × EP1 (this PR) and 53 ms (2.25 + 51) at EP4 (#557), and EP4 equals EP1 bit for bit, forward and backward. TP4 × EP1 came first because it is what the pinned vLLM 0.30.0 rollout runs by default: with --tensor-parallel-size 4 and no --enable-expert-parallel (off by default), vLLM shards each expert's intermediate dimension across the TP ranks instead of distributing experts, so replay has to reproduce that layout to match rollout bits. The attention and GDN layers need tensor parallelism either way. #557 covers EP4 for the MoE; the dense layers stay TP4 in both.

fusheng-ji added a commit to fusheng-ji/RL-Kernel that referenced this pull request Nov 18, 2026
…e33c45 and the run order

The five Qwen3-Next stack heads were pushed on 2026-11-17 and are the PR heads. Optional step 4 reruns RL-Align#503's suites at 8e33c45; the EP4 gate does not start vLLM and can run before step 0 is solved.

Signed-off-by: Wenbo Ji <[email protected]>
fusheng-ji added a commit to fusheng-ji/RL-Kernel that referenced this pull request Nov 18, 2026
…in the provider job, RL-Align#503 bias grad gate) into RL-Align#551

Signed-off-by: Wenbo Ji <[email protected]>
@Flink-ddd
Flink-ddd merged commit f2b5594 into RL-Align:test-qwennext Nov 19, 2026
9 checks passed
Flink-ddd pushed a commit that referenced this pull request Nov 19, 2026
Flink-ddd pushed a commit that referenced this pull request Nov 19, 2026
Flink-ddd pushed a commit that referenced this pull request Nov 19, 2026
Flink-ddd pushed a commit that referenced this pull request Nov 19, 2026
…rovider job, #503 bias grad gate) into #544

Signed-off-by: Wenbo Ji <[email protected]>
Flink-ddd pushed a commit that referenced this pull request Nov 19, 2026
Flink-ddd pushed a commit that referenced this pull request Nov 19, 2026
…rovider job, #503 bias grad gate) into #549

Signed-off-by: Wenbo Ji <[email protected]>
Flink-ddd pushed a commit that referenced this pull request Nov 19, 2026
Flink-ddd pushed a commit that referenced this pull request Nov 19, 2026
…rovider job, #503 bias grad gate) into #557

check_qwen3_next_vllm_model_contract.py stays only in this PR's four-GPU step, which already runs it.

Signed-off-by: Wenbo Ji <[email protected]>
fusheng-ji added a commit to fusheng-ji/RL-Kernel that referenced this pull request Nov 28, 2026
…th the combine_routes patch

Signed-off-by: Wenbo Ji <[email protected]>
fusheng-ji added a commit to fusheng-ji/RL-Kernel that referenced this pull request Nov 28, 2026
fusheng-ji added a commit to fusheng-ji/RL-Kernel that referenced this pull request Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

new-model platform: cuda Specific optimizations or bugs in NVIDIA graphics cards (such as FlashInfer, TMA optimizations) qwen WS1

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants