Skip to content

[AMD] Fuse shared-expert sigmoid + bf16->fp32 cast into the MoE append kernel (3 kernels -> 1) - #28658

Merged
HaiShaw merged 2 commits into
sgl-project:mainfrom
yichiche:fuse-shared-expert-sigmoid-append
Jul 8, 2026
Merged

HaiShaw merged 2 commits into
sgl-project:mainfrom
yichiche:fuse-shared-expert-sigmoid-append

Conversation

@yichiche

@yichiche yichiche commented Jun 18, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

On the AITER shared-expert-fusion path (Qwen2MoeSparseMoeBlock._append_shared_to_topk_output), preparing the fused shared-expert routing weight launched three GPU kernels per MoE layer per decode step:

  1. sigmoid_kernel_cuda — w = F.sigmoid(shared_logits) in _get_shared_expert_weights (~5.5 us)
  2. bfloat16tofloat32_copy_kernel_cuda — shared_weights.to(topk_weights.dtype) inside the append wrapper (~4.5 us)
  3. _fused_append_shared_experts_with_weights_kernel — the append itself (~4.2 us)

These are tiny, bandwidth/launch-bound elementwise ops on small tensors. The sigmoid and the bf16→fp32 cast are pure glue feeding the append kernel, so they can be folded into the append kernel's prologue. This collapses 3 kernels into 1 and removes two global round-trips per MoE layer.

Modifications

  • python/sglang/srt/layers/moe/moe_runner/triton_utils/fused_moe_triton_kernels.py
    • _fused_append_shared_experts_with_weights_kernel: added a scale runtime arg and an APPLY_SIGMOID: tl.constexpr. When set, the shared-weight load computes sigmoid(logits.to(fp32)) * scale in-register, emitting fp32 straight into the output.
    • fused_append_shared_experts_with_weights(...): added apply_sigmoid=False, scale=1.0. When apply_sigmoid=True, raw bf16 gate logits are streamed in directly (host-side .to(fp32) cast skipped); the legacy path is byte-for-byte unchanged when the flag is off.
  • python/sglang/srt/models/qwen2_moe.py
    • _get_shared_expert_weights: returns the raw gate logits plus a 1/ep_size scale instead of sigmoid(logits) / ep_size (the activation and scale are now applied inside the kernel).
    • _append_shared_to_topk_output: passes apply_sigmoid=True, scale=... to the append wrapper.

Net effect: sigmoid + bf16→fp32 cast are fused into the existing append kernel — 3 kernels → 1, ~10 us/layer of glue removed, at ~0 added cost to the append kernel.

Accuracy Tests

GSM8K (200 questions, parallel 2000, greedy), Qwen3.5-397B-A17B-MXFP4, tp=2, AITER backend, MI35x. Run-to-run variance is large here (greedy + continuous-batching nondeterminism), so multiple samples were taken:

Mean difference 0.013 ≪ per-run σ ≈ 0.045 → within noise, no regression. Offline kernel equivalence test: routed weights bit-identical, expert ids exact, shared-expert column differs by ~4e-4 (the fused path computes sigmoid in fp32 vs the old bf16, i.e. strictly more precise).

Benchmarking and Profiling

torch profiler trace (decode), same config. ATen kernels retain the _cuda suffix in their symbol names on ROCm/HIP builds.

Kernel Before After Notes
sigmoid_kernel_cuda (<8, …sigmoid…>) ~5.5 us / layer 0 occurrences eliminated
bfloat16tofloat32_copy_kernel_cuda (per-layer) ~4.5 us / layer eliminated (13 unrelated residual one-offs remain)
_fused_append_shared_experts_with_weights_kernel ~4.2 us 780× @ 3.79 us now does sigmoid + cast in-register

The append kernel fires 780× in the profiling run; with the fusion there are zero standalone sigmoid_kernel_cuda instances feeding it. Per-invocation saving ≈ ~10 us (5.5 + 4.5), folded into the existing append kernel. This is decode glue (<0.1% of ITL), so end-to-end throughput impact is within benchmark noise by construction.

Checklist

Review Process

  1. Ping Merge Oncalls to start the PR flow. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • /tag-run-ci-label, /rerun-failed-ci, /tag-and-rerun-ci
  4. After green CI and required approvals, ask Merge Oncalls to merge.

CI States

Latest PR Test (Base): ❌ Run #27967780275
Latest PR Test (Extra): ❌ Run #27967778273

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request fuses the sigmoid activation and scaling of shared expert weights directly into the Triton kernel _fused_append_shared_experts_with_weights_kernel. This optimization avoids standalone PyTorch activation and casting kernels by passing raw logits and applying the sigmoid and scaling in-register during the fused append operation. There are no review comments, so we have no feedback to provide.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@yichiche yichiche added the run-ci CI: run the baseline test suite on this PR label Jun 18, 2026
@yichiche
yichiche force-pushed the fuse-shared-expert-sigmoid-append branch 2 times, most recently from a773fb3 to 33f3d5d Compare June 18, 2026 17:09
@yichiche

Copy link
Copy Markdown
Collaborator Author

@amd-bot ci-status

@amd-bot

amd-bot commented Jun 28, 2026

Copy link
Copy Markdown

@yichiche

CI Status for PR #28658

Merge verdict: All 13 executed failures are unrelated to this PR (perf-threshold flakes, an infra CUDA OOM, an RDMA-NIC disconnect, and a pre-existing server_args unit failure). But do not merge on "green" alone: this PR's actual changed code path — the AMD AITER qwen2_moe shared-expert sigmoid fusion — is not exercised by any PR-CI test, and NVIDIA's downstream base-c-* stage was fast-fail-skipped, so the NVIDIA signal is incomplete.

Caution

This PR's changed code is not exercised by PR CI. The new in-kernel sigmoid fusion only fires when _use_aiter and a qwen2_moe model has shared experts (num_shared_experts > 0, e.g. Qwen2-57B-A14B-Instruct, Qwen1.5-MoE-A2.7B). The only qwen2_moe model on AMD PR CI is Qwen3-30B-A3B (test_quark_mxfp4.py, suite stage-b-test-1-gpu-small-amd-mi35x, ✅ passed) — Qwen3 MoE has no shared expert gate, so _get_shared_expert_weights returns None and the changed branch is never hit (the in-file comment even notes Qwen1.5-MoE-A2.7B crashes in AITER). The models with shared experts only run in nightly-amd suites (test_gsm8k_eval_amd.py, test_text_models_perf_amd.py — both nightly=True), which do not run on PR CI. There is also no unit test for fused_append_shared_experts_with_weights(apply_sigmoid=True). Green does NOT verify this change. Before merge, run the nightly-amd qwen2_moe gsm8k + perf suites on a shared-expert model (Qwen2-57B-A14B-Instruct), or add a unit test asserting the fused-kernel output equals eager sigmoid(logits)*scale.

Caution

NVIDIA PR CI is incomplete. wait-for-base-b failed because base-b-test-1-gpu-small (6) hit an unrelated CUDA OOM, so the base-c-* stage was skipped (not tested). Re-run base-b after the OOM clears to get full NVIDIA signal.

Changed files: python/sglang/srt/layers/moe/moe_runner/triton_utils/fused_moe_triton_kernels.py (+28/-3), python/sglang/srt/models/qwen2_moe.py (+22/-8)

Executed CI failure attribution: AMD: 2 failures (0 related) · NPU: 1 (0 related) · CPU: 1 (0 related) · NVIDIA: 1 (0 related). Aggregator *-finish / pr-gate jobs (7) are roll-ups of the above, not independent failures.

AMD Executed Failures

Job Test File Test Function Error Related? Why
stage-b-test-1-gpu-large-amd (0) test/registered/perf/test_bench_serving_1gpu_part1.py test_online_lora_latency AssertionError: 2962.26 not less than 2400 🟢 LoRA latency perf on Llama-3.1-8B; no MoE/shared-expert path. Perf-threshold flake.
stage-b-test-large-8-gpu-mi35x-disaggregation-amd test/registered/amd/disaggregation/test_disaggregation_basic.py TestDisaggregationAccuracy.test_gsm8k ServerDisconnectedError → KeyError: 'answer' 🟢 Disagg server disconnect (RDMA NIC infra); see in-flight #29127.

Other Executed Failures

Job Test File Test Function Error Related? Why
stage-b-test-1-npu-a2 (0) test/registered/ascend/basic_function/quant/test_npu_w8a8_quantization.py TestAscendW8A8CompressedTensors.test_gsm8k AssertionError: throughput 536 < 700 🟢 NPU w8a8 throughput threshold (4/5 passed); NPU path untouched by PR.
build-test (xeon-gnr, base-b-test-cpu) test/registered/unit/server_args/test_server_args.py test_hisparse_accepts_aiter_backend_on_rocm AttributeError: 'ServerArgs' has no attribute '_validate_hisparse_dsa_backend' 🟢 Pre-existing server_args issue; PR does not touch server_args.py.
base-b-test-1-gpu-small (6) test/registered/prefill_only/test_pooled_hidden_states.py N/A (server crash) torch.OutOfMemoryError → exit -9 🟢 CUDA OOM (another process holding 24.5 GiB); infra. Triggered the wait-for-base-b cascade.

Details / what to do before merge

  • Coverage (most important): the fusion is verified by nothing on PR CI. Before merge, run a shared-expert qwen2_moe model on AMD AITER — e.g. the nightly-amd gsm8k eval / perf on Qwen2-57B-A14B-Instruct — or add a unit test for fused_append_shared_experts_with_weights(apply_sigmoid=True) asserting numerical equality with eager sigmoid(shared_logits) * scale. The CUDA branch is unchanged (legacy eager path), so NVIDIA risk is low.
  • NVIDIA completeness: re-run base-b (and let base-c proceed) once the OOM clears; consider bypass-fastfail only if you need full signal urgently.
  • No action on the 5 red tests — none implicate the diff; the disagg flake is tracked by #29127. No open in-flight PRs found for the LoRA-latency, NPU-w8a8, or hisparse_dsa_backend failures.

Generated by amd-bot using Claude Code CLI

@kkHuang-amd kkHuang-amd 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.

LGTM

@HaiShaw

HaiShaw commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator

@amd-bot ci-status

@amd-bot

amd-bot commented Jul 6, 2026

Copy link
Copy Markdown

@HaiShaw

CI Status for PR #28658

Merge verdict: No PR-caused failures — all 5 executed failures are unrelated (perf-threshold flakes, CUDA OOM, a server-disconnect, and one pre-existing ServerArgs test). But do not merge on green alone: this PR's actual changed code (the AMD AITER in-kernel sigmoid-fusion path for shared-expert MoE models) is not exercised by any PR-CI test — the covering AMD model tests are nightly-only. The *-finish/pr-gate/wait-for-base-b reds are cascade reflections of these executed failures, not new problems.

Caution

This PR's changed code is not verified by PR CI. The runtime change (apply_sigmoid=_use_aiter → tl.sigmoid fused into _fused_append_shared_experts_with_weights_kernel) only fires on the AMD AITER path (SGLANG_USE_AITER + ROCm) for a shared-expert MoE model (Qwen2MoeSparseMoeBlock and its subclasses qwen3_5 / qwen3_next, with num_shared_experts > 0 and enable_shared_expert_fusion). The AMD tests that would hit this path (test/registered/amd/test_qwen3p5_triton_dcp.py, test/registered/lora/test_lora_qwen3_5_*, qwen3_next e2e) are nightly=True or CUDA/NPU-only, so they did not run on this PR. Green PR CI does not confirm numerical correctness of the fused kernel. Before merge, run a shared-expert Qwen MoE (e.g. Qwen1.5-MoE-A2.7B / Qwen3.5) accuracy check on AMD ROCm with SGLANG_USE_AITER=1, and verify the CUDA path is byte-identical (it takes the untouched F.sigmoid(logits)*scale branch).

Changed files: python/sglang/srt/layers/moe/moe_runner/triton_utils/fused_moe_triton_kernels.py (+28/-3), python/sglang/srt/models/qwen2_moe.py (+22/-8)

Executed CI failure attribution: AMD: 2 failures (0 related) · Others: 3 failures (0 related). No jobs pending.

AMD Executed Failures

Job Test File Test Function Error Related? Why
stage-b-test-large-8-gpu-mi35x-disaggregation-amd test/registered/amd/disaggregation/test_disaggregation_basic.py TestDisaggregationAccuracy.test_gsm8k ServerDisconnectedError → KeyError: 'answer' → retry exceeded (log) 🟢 Disaggregation runs a dense model; server-disconnect during gsm8k is an infra/flake, not the MoE shared-expert path.
stage-b-test-1-gpu-large-amd (0) test/registered/perf/test_bench_serving_1gpu_part1.py TestBenchServing1GPUPart1.test_online_lora_latency AssertionError: 2962.26 not less than 2400 (+ detokenizer health-check timeout) 🟢 LoRA serving latency threshold + health-check flake; unrelated to shared-expert sigmoid fusion.

Other Executed Failures

Job Test File Test Function Error Related? Why
base-b-test-1-gpu-small (6) test/registered/prefill_only/test_pooled_hidden_states.py N/A (server crash) torch.OutOfMemoryError → exit -9 🟢 CUDA OOM in prefill-only pooling; no MoE code path involved.
stage-b-test-1-npu-a2 (0) test/registered/ascend/basic_function/quant/test_npu_w8a8_quantization.py TestAscendW8A8CompressedTensors.test_gsm8k AssertionError: throughput 536.3 < 700 🟢 NPU perf threshold; PR is AMD-only, does not touch the Ascend path.
build-test (xeon-gnr, base-b-test-cpu) test/registered/unit/server_args/test_server_args.py TestHiSparseDsaBackendPolicy.test_hisparse_accepts_aiter_backend_on_rocm AttributeError: 'ServerArgs' object has no attribute '_validate_hisparse_dsa_backend' 🟢 Pre-existing ServerArgs/HiSparse-DSA test lag (relates to DSA cleanup #29912 / #30186), nothing to do with MoE.

Details / what to do before merge

  • Coverage gap (the only real action item): none of the 5 failures matter for merge risk, but the fused-kernel path is untested by this PR's CI. Run on AMD ROCm with SGLANG_USE_AITER=1 a shared-expert Qwen MoE accuracy test (Qwen1.5-MoE-A2.7B / Qwen3.5) and diff outputs against the pre-fusion baseline. Confirm the scale = 1/ep_size folding is correct on an EP>1 config (the code moves the w / ep_size division into the in-kernel scale).
  • CUDA safety: verify the non-AITER branch is unchanged — it returns F.sigmoid(shared_logits) * scale, 1.0 with apply_sigmoid=False, so the kernel keeps shared_weights.to(topk_weights.dtype) legacy behavior. Looks correct by inspection, but a CUDA Qwen-MoE run would confirm.
  • Failures to re-run (unrelated flakes): the two AMD perf/disaggregation reds and the base-b OOM are flaky/threshold failures; a rerun should clear them. The NPU throughput and CPU test_server_args failures are pre-existing on main and not this PR's responsibility.

Generated by amd-bot using Claude Code CLI

@HaiShaw

HaiShaw commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator

@yichiche Would you please post Qwen3.5 nightly result with this commit?

@yichiche

yichiche commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

@yichiche Would you please post Qwen3.5 nightly result with this commit?

@HaiShaw

CUDA_VISIBLE_DEVICES=${GPU:-0} python -m pytest \
    test/registered/moe/test_fused_append_shared_experts.py -v
test/registered/moe/test_fused_append_shared_experts.py::TestFusedAppendSharedExperts::test_fused_sigmoid_matches_eager PASSED                                                                    [ 25%]
test/registered/moe/test_fused_append_shared_experts.py::TestFusedAppendSharedExperts::test_legacy_path_unchanged PASSED                                                                          [ 50%]
test/registered/moe/test_fused_append_shared_experts.py::TestFusedAppendSharedExperts::test_routed_columns_preserved PASSED                                                                       [ 75%]
test/registered/moe/test_fused_append_shared_experts.py::TestFusedAppendSharedExperts::test_zero_shared_is_noop PASSED                                                                            [100%]

All pass.

@HaiShaw
HaiShaw merged commit 96368a5 into sgl-project:main Jul 8, 2026
154 of 167 checks passed
yichiche added a commit to yichiche/sglang that referenced this pull request Jul 15, 2026
…ter)

Fold the shared_expert_gate GEMV + sigmoid + 1/ep_size scale into the
fused shared-expert append kernel on the AITER path, eliminating the
standalone gate GEMM launch. The kernel gains a `fuse_gate` mode that
reduces hidden[pid, :] . W_gate[:] in fp32 per token and broadcasts
sigmoid(logit) * scale to the shared slots; CUDA keeps the legacy eager
sigmoid(logits) * scale path unchanged.

Rebased onto main after the fused_moe_triton_kernels.py refactor moved
it to sglang/kernels/ops/moe/; the stacked apply_sigmoid fusion (sgl-project#28658)
is already merged, so this carries only the fuse_gate delta plus its unit
and MI35x nightly e2e tests.
TianHao65 pushed a commit to apinge/sglang that referenced this pull request Aug 12, 2026
TianHao65 pushed a commit to apinge/sglang that referenced this pull request Aug 12, 2026


Ports both commits of zejunchen-zejun#286 (cfae48f "Fused kernel
before moe", da7a0d2 "Add shared_expert_topk_fusion") onto this branch,
replacing the in-kernel activation added by 1214860a4 (upstream sgl-project#28658).

The shared-expert gate now runs as a standalone Triton kernel
(fused_linear_sigmoid_kernel, one kernel for sigmoid(x @ w^T) on a bias-free
(1, H) linear) and its per-token output is appended to the routed top-k by
_fused_append_shared_experts_gated_kernel. Previously the raw gate logits were
streamed into _fused_append_shared_experts_with_weights_kernel, which applied
sigmoid + the 1/ep_size scale in-register on the fp32 output.

Measured on Qwen3.5-397B-A17B-PTPC-FP8, TP=8, 8x MI308X, ROCm 7.2.0, torch
profiler over 4 prompts x 8000 in / 10 out. Kernel times are summed over the
profiled window; 480 calls == 48 layers x 10 decode steps.

Performance: this is a net regression on the shared-expert path.

  kernel                                       before            after
  ------------------------------------------------------------------------
  Cijk_..._MT16x128x128     (gate GEMM)    240 /  9817.6us    0 /       0us
  Cijk_..._MT16x16x128      (gate GEMM)    240 /  2042.9us    0 /       0us
  fused_linear_sigmoid_kernel                0 /      0us   480 /  9564.2us
  _fused_append_shared_experts_with_weights 480 /  3340.7us    0 /       0us
  _fused_append_shared_experts_gated         0 /      0us   480 /  3336.0us
  bfloat16tofloat32_copy_kernel_cuda         8 /     43.5us  488 /  3236.9us
  ------------------------------------------------------------------------
  path total, TP-0                             15244.7us        16137.2us

The Triton gate kernel genuinely beats hipBLASLt on this shape: 9564.2us vs
11860.5us over the same 480 calls, -2296.3us (-19.4%). But it stores its result
as bf16, and topk_weights is fp32 (topk.py allocates it fp32 on every routing
path), so fused_append_shared_experts_gated's shared_weights.to(topk_weights
.dtype) launches one copy kernel per layer per step. That cast goes from 8
calls / 43.5us to 488 calls / 3236.9us, +3193.4us, which more than gives the
GEMM saving back.

Net per rank, all eight profiled:

  TP-0 +892.5us (+5.9%)   TP-4 +828.0us (+5.4%)
  TP-1 +661.0us (+4.3%)   TP-5 +778.4us (+5.1%)
  TP-2 +668.9us (+4.4%)   TP-6 +941.2us (+6.1%)
  TP-3 +714.8us (+4.7%)   TP-7 +775.1us (+5.1%)

Same sign and same kernel set on every rank, so this is structural, not noise.
End-to-end serving numbers are not reported: the profiling config is 4 prompts
at concurrency 1 with 10 output tokens, far inside the 5-12% launch-to-launch
noise band for this box.

Reachability, TP-0 and TP-1 python_function stacks confirm the dispatch chain
Qwen2MoeSparseMoeBlock._append_shared_to_topk_output ->
get_shared_expert_gate_weights -> can_fuse_shared_expert_gate ->
fused_linear_sigmoid -> append_shared_to_topk, with both target kernels at
480 calls and the old with_weights kernel at 0.

Two deliberate differences from the upstream patch:

- Import path. sgl-project#286 imports fused_append_shared_experts_gated from
  layers/moe/fused_moe_triton/, which does not exist on this tree; the Triton
  MoE kernels live under layers/moe/moe_runner/triton_utils/. The import sits
  inside a try/except ImportError, so taking sgl-project#286 verbatim would silently fall
  back to the eager append_shared_to_topk_ref and neither Triton kernel would
  ever run.

- 1/ep_size pre-scale. sgl-project#286 drops the scale that 1214860a4 applies to cancel
  the post-experts all_reduce summing the fused shared expert ep_size times.
  Re-folded into _get_shared_expert_weights after the gate call, since the
  gated append kernel takes the weights verbatim. No-op and no extra kernel at
  moe_ep_size == 1, which is every TP-only serving config here.

Two consequences worth noting for review:

- 1214860a4 kept a _use_aiter branch so CUDA stayed on eager sigmoid; sgl-project#286 has
  no such branch, so the CUDA path now also goes through the Triton kernels.
  Not exercised here, this is a ROCm-only box.

- fused_append_shared_experts_with_weights and its kernel are left in place but
  now have no callers.

Known follow-up, not included here: giving fused_linear_sigmoid an out_dtype
argument and passing topk_weights.dtype from the caller makes the kernel store
fp32 straight out of its already-fp32 internal sigmoid. That deletes the cast
entirely and turns the +892us regression into a -2.3ms win, and drops gate
error from 1.952e-3 to 7.040e-4. It is left out so this port stays faithful to
sgl-project#286 and the A/B stays clean.

Numerics, validated on device against eager references: gate max abs error
1.952e-3 versus an fp32 linear+sigmoid reference, which is bf16 store rounding
(2^-8 ULP); append output ids exactly equal and weights bit-identical to
append_shared_to_topk_ref.

Files: python/sglang/srt/layers/fused_linear_sigmoid_mul_triton.py (new),
python/sglang/srt/layers/moe/shared_expert_topk_fusion.py (new),
python/sglang/srt/layers/moe/moe_runner/triton_utils/fused_moe_triton_kernels.py,
python/sglang/srt/models/qwen2_moe.py. 392 insertions, 30 deletions.
TianHao65 pushed a commit to apinge/sglang that referenced this pull request Aug 13, 2026
TianHao65 added a commit to apinge/sglang that referenced this pull request Aug 13, 2026


Ports both commits of zejunchen-zejun#286 (cfae48f "Fused kernel
before moe", da7a0d2 "Add shared_expert_topk_fusion"), merged into the
Qwen3.5_v0.5.9 branch of that fork:

  zejunchen-zejun#286
  https://github.com/zejunchen-zejun/sglang/tree/Qwen3.5_v0.5.9

It replaces the in-kernel activation added by 1214860a4, that branch's copy
of upstream sgl-project#28658.

The shared-expert gate now runs as a standalone Triton kernel
(fused_linear_sigmoid_kernel, sigmoid(x @ w^T) on a bias-free (1, H) linear)
and its per-token output is appended to the routed top-k by
_fused_append_shared_experts_gated_kernel. Previously the raw gate logits were
streamed into _fused_append_shared_experts_with_weights_kernel, which applied
sigmoid and the 1/ep_size scale in-register on the fp32 output.

Two deviations from the upstream patch. zejunchen-zejun#286 imports
fused_append_shared_experts_gated from layers/moe/fused_moe_triton/, which does
not exist on this tree; the kernels live under
layers/moe/moe_runner/triton_utils/. The import sits in a try/except
ImportError, so taking it verbatim would silently fall back to the eager
append_shared_to_topk_ref. And it drops the 1/ep_size pre-scale that cancels
the post-experts all_reduce summing the fused shared expert ep_size times; it
is re-folded into _get_shared_expert_weights. No-op at moe_ep_size == 1.

Qwen3.5-397B-A17B-PTPC-FP8, TP=8, 8x MI308X, ROCm 7.2.0.

End-to-end, 8000 in / 500 out, concurrency 1, mean +- spread over repeat
runs:

  metric   | before          -> after           | delta
  ---------+-----------------+------------------+-------
  tok/s    | 112.41 +- 1.67  -> 112.89 +- 4.16  | +0.4%
  TPOT ms  |  8.156 +- 0.121 ->  8.115 +- 0.297 | -0.5%
  TTFT ms  |  377.8 +- 9.7   ->  392.6 +- 15.5  | +3.9%

The gate stores bf16 while topk_weights is fp32, so this port introduces a
shared_weights.to(topk_weights.dtype) conversion in
fused_append_shared_experts_gated. It is removed by the follow-up cherry-pick
of zejunchen-zejun#291.

Numerics: gate max abs error 1.952e-3 against an fp32 linear+sigmoid reference
(bf16 store rounding); append output ids exactly equal and weights
bit-identical to append_shared_to_topk_ref.

Signed-off-by: TianHao65 <[email protected]>
sammysun0711 added a commit to apinge/sglang that referenced this pull request Aug 14, 2026
…ct#291 (#20)

* [AMD] Fuse shared-expert sigmoid + bf16->fp32 cast into the MoE append kernel (3 kernels -> 1) (sgl-project#28658)

Signed-off-by: TianHao65 <[email protected]>

* [AMD] Port the Triton shared-expert gate fusion from zejunchen-zejun#286

Ports both commits of zejunchen-zejun#286 (cfae48f "Fused kernel
before moe", da7a0d2 "Add shared_expert_topk_fusion"), merged into the
Qwen3.5_v0.5.9 branch of that fork:

  zejunchen-zejun#286
  https://github.com/zejunchen-zejun/sglang/tree/Qwen3.5_v0.5.9

It replaces the in-kernel activation added by 1214860a4, that branch's copy
of upstream sgl-project#28658.

The shared-expert gate now runs as a standalone Triton kernel
(fused_linear_sigmoid_kernel, sigmoid(x @ w^T) on a bias-free (1, H) linear)
and its per-token output is appended to the routed top-k by
_fused_append_shared_experts_gated_kernel. Previously the raw gate logits were
streamed into _fused_append_shared_experts_with_weights_kernel, which applied
sigmoid and the 1/ep_size scale in-register on the fp32 output.

Two deviations from the upstream patch. zejunchen-zejun#286 imports
fused_append_shared_experts_gated from layers/moe/fused_moe_triton/, which does
not exist on this tree; the kernels live under
layers/moe/moe_runner/triton_utils/. The import sits in a try/except
ImportError, so taking it verbatim would silently fall back to the eager
append_shared_to_topk_ref. And it drops the 1/ep_size pre-scale that cancels
the post-experts all_reduce summing the fused shared expert ep_size times; it
is re-folded into _get_shared_expert_weights. No-op at moe_ep_size == 1.

Qwen3.5-397B-A17B-PTPC-FP8, TP=8, 8x MI308X, ROCm 7.2.0.

End-to-end, 8000 in / 500 out, concurrency 1, mean +- spread over repeat
runs:

  metric   | before          -> after           | delta
  ---------+-----------------+------------------+-------
  tok/s    | 112.41 +- 1.67  -> 112.89 +- 4.16  | +0.4%
  TPOT ms  |  8.156 +- 0.121 ->  8.115 +- 0.297 | -0.5%
  TTFT ms  |  377.8 +- 9.7   ->  392.6 +- 15.5  | +3.9%

The gate stores bf16 while topk_weights is fp32, so this port introduces a
shared_weights.to(topk_weights.dtype) conversion in
fused_append_shared_experts_gated. It is removed by the follow-up cherry-pick
of zejunchen-zejun#291.

Numerics: gate max abs error 1.952e-3 against an fp32 linear+sigmoid reference
(bf16 store rounding); append output ids exactly equal and weights
bit-identical to append_shared_to_topk_ref.

Signed-off-by: TianHao65 <[email protected]>

* Remove explicit dtype conversion in shared expert fusion (zejunchen-zejun#291)

Cherry-pick of zejunchen-zejun#291 "Remove explicit dtype conversion in
shared expert fusion", authored by Xiake Sun, merged 2026-07-10 by yixionghuo
as merge commit 3038fa5 into the Qwen3.5_v0.5.9 branch of that fork:

  zejunchen-zejun#291
  https://github.com/zejunchen-zejun/sglang/tree/Qwen3.5_v0.5.9

Built on zejunchen-zejun#290, follows zejunchen-zejun#286.

What it does:

- fused_linear_sigmoid gains an optional out_dtype, defaulting to
  hidden_states.dtype.
- fused_append_shared_experts_gated drops the host-side
  shared_weights.to(topk_weights.dtype).
- _fused_append_shared_experts_gated_kernel promotes the shared gate weight
  in-register via tl.load(...).to(ws.dtype).

Path remap: zejunchen-zejun#291 edits
python/sglang/srt/layers/moe/fused_moe_triton/fused_moe_triton_kernels.py,
which does not exist on this tree; the kernels live under
layers/moe/moe_runner/triton_utils/. Both hunks otherwise applied verbatim at
offset +269 lines. Its other commit, d2cf787 "add fused_topk", is not
carried: this branch already dispatches to aiter.fused_moe.fused_topk under
_use_aiter.

Qwen3.5-397B-A17B-PTPC-FP8, TP=8, 8x MI308X, ROCm 7.2.0.

End-to-end, 8000 in / 500 out, concurrency 1, mean +- spread over repeat
runs, measured against the same baseline as the zejunchen-zejun#286
port:

  metric   | before          -> after           | delta
  ---------+-----------------+------------------+-------
  tok/s    | 112.41 +- 1.67  -> 122.22 +- 2.27  | +8.7%
  TPOT ms  |  8.156 +- 0.121 ->  7.457 +- 0.131 | -8.6%
  TTFT ms  |  377.8 +- 9.7   ->  374.5 +- 13.2  | -0.9%

Kernel effect: the bfloat16tofloat32_copy_kernel_cuda launches that
zejunchen-zejun#286 added, 488 calls / 3236.9us on TP-0 over a 4-prompt
8000-in/10-out profile window, go to zero. A 20-iteration profile of the
append path contains no copy kernel.

Reported on the upstream PR, PTL, ISL 8K / OSL 5, concurrency 1: prefill
41.63us -> 35.14us, decode 17.98us -> 13.64us; gsm8k 0.980 over 200 questions;
QPS 0.95 -> 1.00 at concurrency 10 on ISL 8K / OSL 500.

Verified on device against the eager references: the fused kernel handle
resolves non-None; out_dtype defaults to bf16 and honours an explicit
torch.float32; append output ids are exactly equal and weights bit-identical to
append_shared_to_topk_ref with bf16 shared_weights against fp32 topk_weights,
max diff 0.000e+00. The gate still stores bf16 and no caller passes out_dtype,
so gate error against an fp32 linear+sigmoid reference is unchanged at 1.9e-3.

Signed-off-by: Xiake Sun <[email protected]>
(cherry picked from commit a953003)

Co-authored-by: TianHao65 <[email protected]>
Signed-off-by: TianHao65 <[email protected]>

---------

Signed-off-by: TianHao65 <[email protected]>
Co-authored-by: jacky.cheng <[email protected]>
Co-authored-by: TianHao65 <[email protected]>
Co-authored-by: Xiake Sun <[email protected]>
Chronostasys pushed a commit to MindLab-Research/sglang that referenced this pull request Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants