Skip to content

[Fix] moe: Map expert ids for layers whose runner needs local ids under EP - #44480

Merged
ch-wan merged 4 commits into
sgl-project:mainfrom
adi-suresh01:fix/ep-dispatcher-follow-layer-runner
Oct 20, 2026
Merged

ch-wan merged 4 commits into
sgl-project:mainfrom
adi-suresh01:fix/ep-dispatcher-follow-layer-runner

Conversation

@adi-suresh01

@adi-suresh01 adi-suresh01 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

This PR was part of a stack (oldest at bottom):

Motivation

Branch update: rebased onto main at 553836c1647b3bfbeb266b49d76ec2c9df012425. Current head: aba4640fc85fa75d0dfb85cd0756a7cc6e3bd422. The original fix and author are preserved; this PR keeps its bounded one-way local-ID mapping rule. The three dependent PRs extend the per-layer contract separately. Post-rebase CPU results are listed below; original model/benchmark measurements were not rerun.

Fp8MoEMethod.create_moe_runner runs fp8 experts on triton when --moe-runner-backend is flashinfer_cutlass or flashinfer_cutedsl, since Fp8MoEMethod has no path on either. NVFP4 checkpoints pin flashinfer_cutlass on sm120, and nvidia/Qwen3.8-Flash-Next-NVFP4 keeps its MTP experts in FP8 block-scaled form, so the NEXTN draft layer ends up on triton. StandardDispatcher only looks at the global backend when it decides whether to translate expert ids. It sees flashinfer_cutlass, sets skip_local_expert_mapping, and the triton runner gets global ids. With --ep-size 2 each rank holds 256 of the 512 experts, so on both ranks ids 256 to 511 index past the local weights, and on rank 1 ids 0 to 255 run the wrong experts.

This is the EP2 crash in #44291 (attempts 2 and 3), and it is what the Qwen3.8-Flash-Next cookbook means when it says these experts "fault on the triton fp8 path under EP". MoeRunner.__init__ already guards the same hazard for hpc_ops (it fails at startup when a quant method falls back to another runner); the flashinfer_cutlass fallback has no guard, so it runs and faults.

Reproduced on 2x RTX PRO 6000 Blackwell Server Edition (sm_120, PCIe only, GPU0-GPU1 SYS), driver 595.91.07, lmsysorg/sglang:dev-cu13 at a6a8c56 (torch 2.14.1+cu130, flashinfer 0.7.1, triton 3.8.0), nvidia/Qwen3.8-Flash-Next-NVFP4 @ fc694b54, --tp-size 2 --ep-size 2 --moe-runner-backend flashinfer_cutlass --ple-offload-embedding --disable-custom-all-reduce, NEXTN 3/1/4:

Run Result
no speculation, CUDA graphs serves
NEXTN, CUDA graphs CUDA error: an illegal memory access during draft prefill graph capture
NEXTN, --disable-cuda-graph, CUDA_LAUNCH_BLOCKING=1 Triton Error [CUDA]: an illegal memory access in fused_moe_kernel, called from Fp8MoEMethod.apply in _draft_extend_for_prefill
NEXTN + #40172 same crash as NEXTN with graphs: #40172 changes the mapping branch, which this layer skips
NEXTN + this PR serves with CUDA graphs, GSM8K 0.975, accept length 2.94

Modifications

  • python/sglang/srt/layers/moe/fused_moe_triton/layer.py: create_moe_dispatcher passes the backend of the runner the quant method built (quant_method.runner.runner_backend). The layer calls create_moe_runner before it builds the dispatcher, so that runner is already known. Methods with no runner of their own, including wrappers that build one on an inner scheme (compressed-tensors, Quark, AWQ/GPTQ), pass None and keep today's behavior.
  • python/sglang/srt/layers/moe/token_dispatcher/standard.py: StandardDispatcher takes an optional runner_backend. Every flag still comes from --moe-runner-backend. The runner can only turn local-id mapping on: when the global backend keeps global ids (_keeps_global_expert_ids, the list that used to be inline) and the layer's runner does not. Under auto, AITER, or any layer whose runner keeps global ids, nothing changes. With LoRA and EP on a remapped layer it raises at startup, because the LoRA pool keys experts by the global backend's convention and would read the wrong adapters.
  • test/registered/unit/layers/moe/test_standard_dispatcher_runner_backend.py (new, CPU): under a flashinfer_cutlass pin with EP2, a dispatcher built for a triton runner maps global ids to local ones and turns the other rank's experts into -1; Fp8MoEMethod's triton fallback reaches the dispatcher through create_moe_dispatcher; a runner never turns mapping off (auto + flashinfer_trtllm); the AITER flag still follows the global backend; LoRA + EP on a remapped layer is rejected.
  • test/registered/unit/lora/test_mem_pool_ep_unit.py: that test execs the dispatcher's __init__ from source in a hand-built namespace, so it now also loads _keeps_global_expert_ids and provides Optional and MoeRunnerBackendLike for the new signature.

Not changed here: should_use_flashinfer_cutlass_moe_fp4_allgather() still reads the global backend (DP-attention fp4 all-gather only). Wrapper methods keep the global layout, so a wrapper whose inner scheme runs triton under a flashinfer_cutlass pin (Quark W8A8 FP8 per-tensor, for example) is still affected; I left that out because I could not test it.

Validation after rebase

Head: aba4640fc85fa75d0dfb85cd0756a7cc6e3bd422. Rebased onto main 553836c1647b3bfbeb266b49d76ec2c9df012425; base main is 553836c1647b3bfbeb266b49d76ec2c9df012425.

GPU, full-model accuracy/throughput and full CI were not rerun for this rebase. Prior hardware measurements below remain evidence for their named earlier revisions; checked CUTLASS/Marlin/GGUF consumer sources are unchanged, which is source evidence rather than a new GPU run.

Earlier accuracy tests (before rebase)

  • New test: without this PR 6 failed, 1 passed (the Fp8MoEMethod case fails on assert not dispatcher.skip_local_expert_mapping), with it 7 passed.
  • With this PR, the new test, test_hpc_ops_runner_guard.py, test_flashinfer_dispatcher.py, test_moe_runner_config_placement.py and test_mem_pool_ep_unit.py: 80 passed.
  • Server, EP2 + NEXTN + CUDA graphs + this PR: python -m sglang.test.run_eval --eval-name gsm8k --num-examples 200 --max-tokens 16384 scores 0.975, per-request accept length 2.94 (min 2.36, max 3.33).
  • That server run used the first revision of this fix, which took every dispatcher flag from the runner. A review pointed out that it would change ROCm AITER BF16 MoE under EP, so I narrowed it to the version here; for this layer the two dispatch identically. The final revision was rechecked on the same pod: boots with graphs, GSM8K 50 scores 0.980, accept length 2.95.
  • Without speculation, EP2 already served on main; TP2 + NEXTN with [Fix] quantization: Load block-FP8 MoE TP shards that split checkpoint blocks #42566 and both EP2/TP2 with the RadixArk BF16 draft also serve, so the only EP2 + NEXTN blocker on this checkpoint was this dispatcher path.

Earlier speed tests and profiling (before rebase)

sglang.bench_serving, random 1024 in / 512 out, EP2 + NEXTN + CUDA graphs + this PR:

Concurrency Output tok/s Median TPOT Median TTFT Accept length
1 181.0 5.21 ms 120 ms 2.99
16 950.1 15.41 ms 173 ms 2.95
64 1362.6 27.23 ms 9500 ms 2.90

There is no "before" column because main does not start in this configuration. The c=64 TTFT is queueing: the mamba state cache caps max_running_requests at 39 here.

Checklist

Refs #44291


CI States

Latest PR Test (Base): ❌ Run #39374968778
Latest PR Test (Extra): ❌ Run #39374968717
Latest PR Test (AMD ROCm 10): ❌ Run #39374968773

@adi-suresh01

Copy link
Copy Markdown
Contributor Author

@ch-wan could you take a look when you get a chance? This is the EP2 crash from #44291: the fp8 MTP experts fall back to triton under the flashinfer_cutlass pin, but the dispatcher still hands them global expert ids. With this, EP2 + NEXTN serves on 2x RTX PRO 6000 (GSM8K 0.980, accept length 2.95). It also needs the run-ci label for CI to start.

@ch-wan ch-wan self-assigned this Oct 18, 2026
@ch-wan
ch-wan force-pushed the fix/ep-dispatcher-follow-layer-runner branch from d6cbec4 to 478dd70 Compare October 18, 2026 23:54
@ch-wan

ch-wan commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator

@adi-suresh01 Thank you for your contribution. I'm coincidentally fixing a broader issue (#44993) and my agent found this related one. I will stack my PRs over yours. You can ping me on slack as I do not regularly check github inbox.

@adi-suresh01

Copy link
Copy Markdown
Contributor Author

Thanks @ch-wan, makes sense for it to sit under the layer contract work. I'll leave the branch as you rebased it and reach out on Slack.

detain added a commit to detain/sglang that referenced this pull request Oct 19, 2026
…ds local ids under EP (NVFP4+flashinfer_cutlass with triton-fallback FP8 draft experts)
detain added a commit to detain/sglang that referenced this pull request Oct 19, 2026
…31503 input-scale EP slice, sgl-project#44480 local expert ids for triton-fallback runners) + header sync
detain pushed a commit to detain/sglang that referenced this pull request Oct 19, 2026
…ect#40498)

Cherry-pick of 4e0609e.

Conflict resolution (union, as instructed): `standard.py` — upstream
inserts `_map_topk_ids_to_local_experts()` exactly where our entry-206
(sgl-project#44480) helper `_keeps_global_expert_ids()` sits, so the block is kept
with BOTH functions; the entry-206 gates around the mapping
(`self.skip_local_expert_mapping = _keeps_global_expert_ids(backend)`,
the build-mapping guard and the `local_expert_mapping is not None and
not self.skip_local_expert_mapping` dispatch guard) are untouched. The
call site now reads:

    topk_ids_local = _map_topk_ids_to_local_experts(
        topk_output.topk_ids, self.local_expert_mapping
    )

instead of `self.local_expert_mapping[topk_output.topk_ids]`, which
aliased the router's `-1` drop sentinel onto the mapping table's last
entry (a dropped token could be resurrected onto the highest-ID expert
of the last shard). Our fork's DP-pad masking stays AFTER the
translation, on the mapped tensor; the PR's rewrite of the masking
comment was dropped in favour of our longer in-tree rationale comment,
which states the same ordering. `dp_attention.py` takes the PR's
docstring-only removal of the now-obsolete "must be applied AFTER the
gather" caveat.

Test: `test/registered/unit/layers/moe/test_standard_dispatcher.py`
(CPU, register_cpu_ci). Proven red at 73a335b and green here:
[[-1, 3], [2, 0]] maps to [[-1, 1], [0, -1]] rather than resurrecting
expert 0's owner.

(cherry picked from commit 4e0609e)
(cherry picked from commit 0e184975fea60fa2b6622ccad059007366118497)
adi-suresh01 and others added 4 commits October 19, 2026 22:13
…er EP

Fp8MoEMethod runs fp8 experts on triton when --moe-runner-backend is
flashinfer_cutlass or flashinfer_cutedsl. StandardDispatcher only read the
global backend, so it kept global expert ids for those layers. Under EP the
triton kernel then indexed experts the rank does not hold, which faults on
the fp8 MTP draft of nvidia/Qwen3.8-Flash-Next-NVFP4 at --tp 2 --ep 2.

create_moe_dispatcher passes the runner the quant method built. The
dispatcher still takes every flag from the global backend; the runner can
only turn local-id mapping on, when the global backend keeps global ids and
the layer's runner does not. LoRA with EP on such a layer is rejected at
startup, since the LoRA pool keys experts by the global convention.
@ch-wan
ch-wan force-pushed the fix/ep-dispatcher-follow-layer-runner branch from c89e20f to aba4640 Compare October 20, 2026 05:27
detain added a commit to detain/sglang that referenced this pull request Oct 20, 2026
…/deferred/avoid map

- 3A [24-35]: NVFP4 MoE boot sgl-project#39807/sgl-project#40173, block-FP8 TP refine sgl-project#42566, k-pool indexer split sgl-project#43619,
  SM120 skinny GEMM sgl-project#42865/sgl-project#42867, DeepGEMM warmup guards sgl-project#32686/sgl-project#43712, autotune sgl-project#43363/sgl-project#40420,
  mHC overlap sgl-project#42985, FP8-einsum precompile sgl-project#42821.
- 3B [36-43]: PCIe CustomAllreduce VMM sgl-project#44448, EP local expert ids sgl-project#44480, shm TP broadcast sgl-project#44202,
  PCIe-IPC all-gather sgl-project#42863 + multicast guard sgl-project#41888, TP-sampling consistency sgl-project#41916/sgl-project#38565,
  draft embed/lm_head VRAM sgl-project#37155.
- sgl-project#39807 toolchain commit verified safe against our CUDA_HOME=12.9 pin (cu13 fallback needs CUDA_HOME unset AND glibc>=2.41; we are 2.39).
- stack_want.txt: execution-status banner. Branch tip 5dd6ec7.
detain pushed a commit to detain/sglang that referenced this pull request Oct 20, 2026
…PU regression)

Item 8 of the apply-r batch. Upstream PR sgl-project#44480 (our entry 206, landed as
213138c from the then-head c96e4103b6) gained three commits. This takes the
meaningful delta on top of what we already carry:

  a127510 [Chore] moe: Clarify fallback dispatcher ownership
  1ae7f6e [Test] moe: Add dispatcher regression script entrypoint
  aba4640 [Test] moe: Keep dispatcher mapping regression on CPU

Method: the PR head is based on an older upstream tree, so `git diff
HEAD..pr-head` is dominated by our own newer content appearing as removals
(_weight_layout_method / supports_routed_deferred_finalize / paged-experts
etc. are OURS and were NOT touched). Applied the three real deltas by hand
instead of a squashed net diff:

 1. layers/moe/fused_moe_triton/layer.py::_built_runner_backend now reads
    `quant_method.runner` directly (getattr fallback dropped). Verified safe in
    our fork, including for the many methods that never assign a runner:
    FusedMoEMethodBase declares the class-level default
    `runner: MoeRunner | None = None` (quantization/base_config.py:98), and
    W4AFp8MoEMethod:297, BitsAndBytesMoEMethod:472,
    ExpertPackMethod.create_moe_runner:133 and KTEPWrapperMethod:260 (which
    delegates to gpu_method) all rely on exactly that default, so both spellings
    return None for them. create_moe_dispatcher has a single production caller
    (FusedMoE.__init__:570) passing self.quant_method right after
    quant_method.create_moe_runner(...), so nothing outside the base class can
    reach it.
 2. token_dispatcher/standard.py: adopted the head's module-level ordering
    (_map_topk_ids_to_local_experts at :95 before _keeps_global_expert_ids). The
    swap is OUR fork artifact — entry 225's union resolution placed _map after
    _keeps; the PR's original commit already had _map first and added _keeps
    below it. The move is semantic-free (two independent module functions) and
    keeps us aligned with upstream for future picks. DECLINED the
    other half of a127510: upstream's 2-line rewrite of the ownership comment
    is strictly less informative than our in-tree version (it drops the
    Fp8MoEMethod-under-cutlass-pin example and the "runner only ever turns the
    mapping on" invariant). Kept our text, folding in upstream's ownership
    framing in one parenthetical.
 3. test/registered/unit/layers/moe/test_standard_dispatcher_runner_backend.py
    is now byte-identical to aba4640. The CPU fix matters to us: the fixture
    patches standard.get_device -> "cpu" (StandardDispatcher.dispatch calls
    get_device() at standard.py:232) and the tensor is built on "cpu", so the
    end-to-end mapping assertion runs without a GPU. We had been carrying this
    test as skipUnless(torch.cuda.is_available()) (main commit 99694ad, after
    it failed as `NotImplementedError: no platform` under CUDA_VISIBLE_DEVICES=9);
    that gate and its now-unused `import unittest` / `get_device` imports are
    removed. Also takes 1ae7f6e's sanctioned `if __name__ == "__main__":
    sys.exit(pytest.main([__file__, "-v"]))` block (181 in-tree precedents;
    scripts/lint/check_no_bare_pytest_main.py rc=0).

Preserved fork behaviour (entry 225/sgl-project#40498 + entry 206): _map_topk_ids_to_local_experts
still maps with `torch.where(topk_ids < 0, -1, mapping[topk_ids.clamp_min(0)])`
so the -1 drop sentinel survives translation, and _MASK_DP_PAD_MOE is still
applied AFTER the local-id translation in dispatch(); test_runner_never_turns_mapping_off
still pins the one-directional rescue.

Tests (CVD=9, per-file, .venv2 + PYTHONPATH=worktree/python):
  test_standard_dispatcher_runner_backend.py  6P/1S -> 7P  (deliberate delta)
  test/registered/unit/lora/test_mem_pool_ep_unit.py  49P/4sub (baseline)
  test_moe_runner_config_placement.py 5P + test_moe_runner_extensions.py 8P (=13P baseline)
  test_mega_moe_deepgemm_api.py  1F/13P/13sub — 1F
    (test_mxf4_weight_transform_uses_matching_mma_type) PROVEN pre-existing, byte
    identical in a throwaway worktree at 3251fbd.
ruff repo ruleset (F401,F821,F823,UP037) + ruff format clean on all 3 files;
check_registered_tests.py and check_no_bare_pytest_main.py rc=0.

(cherry picked from commit a127510)
(cherry picked from commit 1ae7f6e)
(cherry picked from commit aba4640)
detain added a commit to detain/sglang that referenced this pull request Oct 20, 2026
…SM110/SM120

Own fork patch (not an upstream port). Fixes a silent wrong-output class that
the NVFP4 trial would have hit on its first `auto` boot with EP > 1.

THE BUG (code trace, reproduced on this tree by probe):
The nvidia Qwen3.8-Flash-Next-NVFP4 checkpoint declares MIXED_PRECISION with
NVFP4 experts, so ModelConfig derives quantization "modelopt_mixed"
(configs/model_config.py:1746-1756). With no --quantization flag the CLI value
is None, so `_moe_runner_backend_quant_constraints` (arg_groups/overrides.py)
published `auto` unchanged -- its SM110/SM120 branch tested only
`view.quantization == "modelopt_fp4"`, i.e. the declared value, never the
checkpoint-derived one. Meanwhile ModelOptNvFp4FusedMoEMethod.create_moe_runner
resolves auto + is_sm120 to FLASHINFER_CUTLASS per layer (modelopt_quant.py
:3192, with its own comment that the trtllm NVFP4 MoE path is SM100-only).
StandardDispatcher decides the expert-id space from the PUBLISHED global
(standard.py:147 skip_local_expert_mapping = _keeps_global_expert_ids(backend)),
and the sgl-project#44480 rescue added as entry 206 can only turn local-id mapping ON,
never off (:154-170). So under auto the dispatcher remapped ids to the rank
range while the cutlass runner computes start_expert from the global id
(num_experts_per_node * ep_rank; flashinfer cutlass_fused_moe_kernels.cuh
:4254-4261, mirrored by our runner passing ep_rank at flashinfer_cutlass.py
:539/:748). Rank 0 is accidentally correct, ranks 1..N-1 route nothing, no
exception: a silently missing (ep_size-1)/ep_size of the FFN.

THE FIX (a): extend that branch to (i) accept "modelopt_mixed" as well, and
(ii) fall back to the checkpoint-derived quantization when the CLI/declared
value is absent, via a new `_checkpoint_quantization_or_none(view)` helper that
reads `model_config_of(view).quantization` (the idiom this hook family already
uses -- 10 other post-process hooks call model_config_of, and
arg_groups/model_overrides/nemotron_h.py:31-55,79-101 is the precedent for
taking quantization from the config rather than the CLI). Fail-safe by
construction: any error determining the quantization yields None and the
resolution is exactly what it was before.

Why it cannot fire for a pure-FP8 checkpoint: "modelopt_mixed" is returned only
when at least one layer reports quant_algo NVFP4/W4A16_NVFP4
(model_config.py:1746-1756 -- MIXED_PRECISION without such a layer is
"w4afp8"), so publishing cutlass always matches some layer; a plain FP8 export
resolves to "fp8" or "modelopt_fp8" (:1759-1760) and stays out of the branch,
and the branch is still gated on `moe_runner_backend == "auto"` plus
is_sm110/is_sm120.

(b) TESTS: extended the existing hook harness
test/registered/unit/test_model_overrides.py::test_moe_runner_quant_constraint_pass
(no new file, no duplicate harness) with modelopt_mixed, the flagless
config-derived case, declared-value-wins, the explicit-pin guard, a
subTest loop over the non-firing quantizations (fp8 / modelopt_fp8 / w4afp8 /
None), the fail-safe path, and the SM100 negative; and
test/registered/unit/layers/moe/test_standard_dispatcher_runner_backend.py with
the end-to-end invariant (hook output -> resolve_moe_runner_backend ->
_keeps_global_expert_ids -> dispatcher keeps GLOBAL ids and dispatch leaves
[[0,5],[3,7]] untouched), the triton-pin case, the warning (fires once per
pair, names the fix), the two agreeing-id-spaces negatives and the EP==1
silence. Red/green: without the source changes the 5 new dispatcher tests plus
the hook test fail (4 failed / 8 passed in the dispatcher file); with them,
12 passed and 111 passed / 1 skipped / 179 subtests in test_model_overrides.py
(baseline 111/1/175: +4 subtests are the new loop).

(c) DEFENSIVE CHECK: one-time logger.warning in StandardDispatcher.__init__ for
the mirror-image combination (EP > 1, built runner keeps global ids, published
backend does not). A raise was rejected deliberately: the inputs are per-layer
quant-method decisions this host cannot enumerate, and the same shape is already
reachable in a config that ships today -- --quantization modelopt_fp4 with auto
on SM100, where create_moe_runner resolves FLASHINFER_TRTLLM (also listed as
global-keeping) while the global stays auto, i.e. a raise would break boots this
patch cannot test. The warning is keyed per (published, built) pair so a 78-layer
model logs one line, and it names the backend that would resolve the conflict.

(d) RESOLUTION TABLE, (published global, built runner) -> skip_local_expert_mapping:
      before                          after
  (auto, cutlass)      False -> misroute  -> the hook now publishes cutlass, so
                                  the pair no longer occurs on SM110/SM120
                                  modelopt fp4/mixed; where it still occurs
                                  elsewhere: False + warning
  (cutlass, cutlass)   True               -> True            (unchanged)
  (cutlass, triton)    False (entry-206 rescue) -> unchanged
  (auto, triton)       False              -> False           (unchanged; triton
                                  wants local ids -- the prod case)
  (triton, triton)     False              -> False           (unchanged)

PROD fp8 ARM PROVABLY UNAFFECTED: /root/run_sglang_qwenflashnext9.sh:244 boots
`--moe-runner-backend triton`, so `moe_runner_backend == "auto"` is False and
the branch is never entered -- and independently the prod checkpoint is
blockwise FP8, whose quantization is not in ("modelopt_fp4", "modelopt_mixed").
Both guards are pinned by tests: test_explicit_triton_pin_is_left_alone feeds a
modelopt_mixed config plus an explicit triton and asserts `{}` (nothing
republished, layer stays on local ids), and the non-firing subTest loop pins the
fp8/modelopt_fp8 quantization gate. The dispatcher's own mapping behaviour for
triton is unchanged, so the Xid43-driven pin documented in the run script keeps
resolving to triton rather than deep_gemm.

Files: python/sglang/srt/arg_groups/overrides.py,
       python/sglang/srt/layers/moe/token_dispatcher/standard.py,
       test/registered/unit/test_model_overrides.py,
       test/registered/unit/layers/moe/test_standard_dispatcher_runner_backend.py
Tests CVD=9 per-file: dispatcher 12P, test_model_overrides 111P/1S/179sub,
test_mxfp8_moe_runner_backend 5P/5sub (baseline), test_mem_pool_ep_unit 49P/4sub,
moe placement+extensions 13P. Ruff repo ruleset + format clean on all 4.
@ch-wan
ch-wan merged commit e2e1a97 into sgl-project:main Oct 20, 2026
108 of 124 checks passed
ihciah pushed a commit to ihciah/sglang that referenced this pull request Nov 25, 2026
…gl-project#45544)

Layer 5 of the Kimi-K3 release line on upstream main 586355a (base branch
kimi-k3-nightly-586355a8, the nightly-dev-cu13-20261028-586355a8 image).
Written as layer 4 of the 27 Oct line on upstream main 5884e4f, where the
checks below ran; the patch applies to this base unchanged.

Under expert parallelism each rank's trtllm-gen routed MoE computes only its
own experts (112 of 896 at EP8), but FlashInfer picks its routing kernel from
num_experts. K3's 896 experts select the Tier<896, 16> specialisation, which
is above the dyn-block kernel's 512-expert limit, so decode steps of 5 to 16
tokens run routingIndicesClusterKernel, about 11 to 12.6 us per MoE layer on
8x B300 (once per MoE layer, so about 1 ms per decode step).

The fused route+quant launch (route_quant_fused, decode batches up to 64
tokens) already writes the packed (id << 16 | bf16 weight) ids the routed MoE
consumes. When the model stages the rank's expert range, its pack epilogue now
writes the rank's experts as 0..count-1 and any other expert in top-k slot k
as count + k (unique per row), and the runner passes
num_experts = round_up(count + top_k, 4) with local_expert_offset 0 (128 at
EP8: Tier<256, 16>, dyn-block kernel up to 16 tokens, a smaller cluster kernel
above). The global ids (out_i, which TopKOutput carries on) are unchanged, and
the same (token, local expert, weight) entries reach the expert GEMMs in the
same order, so the MoE output is bitwise unchanged for the same GEMM tactic.

Plumbing:
- route_radix.cuh / route_quant_fused.cuh / moe_route_quant_fused.py: optional
  (local_expert_offset, num_local_experts) for the packed output only; 0
  keeps the global ids. MAX_TOKENS (the fused launch's token cap) is public.
- route_quant_handoff.py: stage(x, local_experts) takes the rank's range;
  rank_local_num_experts() decides whether it applies (a proper sub-range that
  shrinks the routing problem); the range is recorded with the packed tensor
  and read back once with take_local_experts(routing), keyed by that tensor.
- kimi_k3.py: stages the range Mxfp4MoEMethod hands the runner, read per
  forward because bind_full_expert_weights can change it after construction.
- flashinfer_trtllm.py: passes the rank-local num_experts and offset 0 for
  such packed ids, after asserting the range equals quant_info's.

Autotune coverage: FlashInfer's MoE tuner key includes num_experts. When the
decode-shaped autotune forward runs above the fused route's 64-token cap
(decode CUDA graphs past 64 rows), it takes the unfused routing and would only
tune the global key, leaving every rank-local decode call on FlashInfer's
untuned default tactic. During tuning, when the runner sees unfused routing
and rank-local ids apply, it also runs FlashInfer on up to 64 of that
forward's routes, relabelled as the fused route would, so the decode key is
tuned from real routes. Serving paths are unchanged.

Measured on 8x B300, Kimi-K3 TP8 DCP8 EP8, one node: routing kernel per MoE
layer 11.1 / 12.2 / 12.6 us -> 4.3 / 4.8 / 7.1 us at 8 / 16 / 24 decode
rows; decode output throughput (bench_one_batch_server, 8192 in / 512 out)
+6.1 / +4.2 / +1.0 % at batch 8 / 16 / 32 with the expert-GEMM tactics held
at main's fresh picks, and +6.3 / +10.7 / -5.0 % with a fresh autotune per
arm (the tuner picks different GEMM tactics for the new key).

Tests: the kernel's rank-local ids against a torch oracle (EP 2/8/16, first,
middle and last rank, 1 to 64 tokens) with everything else it writes
unchanged; the handoff bookkeeping (keyed, consumed once, global ids when the
range does not apply); and FlashInfer's routed MXFP4 MoE output bitwise equal
between global and rank-local ids (EP 2/4/8/16, 1 to 64 tokens, SM100).

Source: e251e3d on the kimi-k3-nightly-3c560089 line (fork PR sgl-project#20), a mirror
of upstream sgl-project#45544 (head fc02c94). One conflict, in
moe_route_quant_fused.covered(): upstream sgl-project#44690 dropped the
x.shape[0] == scores.shape[0] check (a mismatch is a caller bug the launcher
reports); kept that, and took the PR's public MAX_TOKENS rename. Checked
against sgl-project#44480 (merged 20 Oct, StandardDispatcher maps expert ids for runners
that need local ids under EP): flashinfer_trtllm and flashinfer_mxfp4 stay in
its keep-global-ids list, so nothing else remaps for this runner and the packed
ids are made rank-local once, in the fused route epilogue. The range the model
stages (moe_ep_rank * num_local_experts, num_local_experts) is the one the MXFP4
quant methods hand the runner at 5884e4f (mxfp4.py,
mxfp4_flashinfer_trtllm_moe.py), and the runner asserts the two are equal. The
runner function this changes is untouched by upstream since 3c56008.

Tests: GPU only (test_rank_local_routed_moe.py, test_route_quant_prerequisites.py
launch the JIT kernels; on a CPU host the new file does not import on the parent
and skips or fails for want of CUDA here, as the existing cases in
test_route_quant_prerequisites.py do on the base). On one B300 GPU on the 3c56008
line: test_rank_local_routed_moe.py 1/1 at this layer (2/2 on 23 Oct counted
layer 6's padded-row case) and test_route_quant_prerequisites.py 5/5. They
rerun on GPU with this branch's image.

Upstream: sgl-project#45544

Co-Authored-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 09d9f99)
(cherry picked from commit cb640ad)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants