Skip to content

[Refactor] moe: Derive layer contracts from the selected quant method - #44993

Merged
ch-wan merged 33 commits into
mainfrom
cheng/refactor/moe-layer-backend-semantics
Oct 20, 2026
Merged

ch-wan merged 33 commits into
mainfrom
cheng/refactor/moe-layer-backend-semantics

Conversation

@ch-wan

@ch-wan ch-wan commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator

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

Motivation

A MoE quantization method can execute on Triton while the requested backend remains FlashInfer or AITER. Dispatch, weight preparation and routing must follow the layer that actually executes. Backend identity also does not prove that a native router implements the model's routing policy: AUTO-resolved NVFP4 must preserve custom routing and renormalization.

Modifications

  • Quantization methods expose their effective execution backend, including wrapped methods, secondary runners and direct kernels. FusedMoE binds dispatch, expert-ID layout, transport payloads, post-load transforms and each model router to that contract.
  • TRT-LLM in-kernel routing requires a declared policy matching the model's scoring, grouping, bias, renormalization, custom-router and shared-slot behavior. Other routers retain materialized STANDARD output. Explicit Default enum value 0 remains a real policy, distinct from an unspecified selector.
  • TRT-LLM routed adapters consume materialized weights without renormalizing them again. Unsupported materialized per-tensor FP8 input fails before the kernel; an undeclared per-tensor router retains the Triton fallback and its compatible weight layout.
  • Materialized TRT-LLM routes include the routed factor for every effective quantization method, including compressed-tensors FP8/NVFP4 schemes. Grouped/biased fallback producers apply the factor independently of renormalization while preserving shared contributions. Native routers still apply their own factor once. Ordinary loaders zero untouched padded weight tails, including repeated loads.
  • Preserve model-wide DP layout for fallback payloads, gate AITER-specific transforms on the effective backend, and keep weight-only helpers with no runner valid. Binding is idempotent for the same contract and rejects conflicting reuse. The gfx1250 W4A8 internal router rejects unsupported expert sharding.

Equivalent native policies are declared for normalized MiMoV2 grouped sigmoid/bias, BailingMoE grouped sigmoid/bias or plain softmax, and Cohere2 sigmoid. Other configurations remain materialized. DeepSeek's logits-only dual-stream graph requires a BYPASSED router even when this PR is used independently.

Llama4 FP8 explicitly selects the model's top-1 sigmoid native policy. Gemma4 NVFP4 materializes its model router so selected-expert softmax weights retain the learned per-expert multiplier. These change behavior relative to the earlier native defaults; CPU contract tests cover the boundaries, but no full-model accuracy A/B is claimed for either model.

BailingLinear resolves its optional AWQ provider only when AWQ weights are loaded, so ordinary model construction does not require vllm. The Kimi constructor fixture declares the routing selector explicitly.

Requested-backend reads remain where they select a method, allocate compatible shapes or establish model-wide policy.

CI fixture repair

Current head: 4275a5026050615139c3658a72b6a7d05d65b17f.

The DeepSeek dual-stream test fixture now declares its native runner, BYPASSED TopK format and static expert dispatch policy. The production routing guard remains intact. This repairs the missing topk error in the registered CUDA graph test.

Validation: the original fixture reproduced the reported error at both the lower and upper PR production revisions. The corrected full test passed on one H200 GPU at both revisions, including opcheck, fullgraph compilation and CUDA graph capture/replay for replicated and non-replicated shared outputs. The tested fixture bytes match this commit. Applicable pre-commit checks passed.

GPU environment: Python 3.12.3, Torch 2.13.0+cu130, Triton 3.7.1, sgl-kernel 0.4.7 and FlashInfer 0.6.18. The test substitutes small CUDA operations for expert kernels; model loading, MoE numerical accuracy and full CI were not rerun for this fixture repair. Earlier validation below remains tied to its stated revisions.

Earlier validation after rebase

Head: fc2dd3d90bf86fe1b61741c1bb8d28a4e121dc8a. Rebased onto main 553836c1647b3bfbeb266b49d76ec2c9df012425; base cheng/hot-fix/server-args-positional-api is 77300dcce02c0b20d68cbc687bb56b54c4a97ace.

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.

Previous validation (before rebase)

Previous head: b37b73a1ae1bdf3d73b6108deb76a14679a079b4, based on #44991 and main 693d33330647c57f82e09ac39a34122fa46b5763.

  • At this exact head, 4 focused CPU modules passed: 28 tests plus 48 reported subtests, covering model policy constructors, shared scaling, ModelOpt dispatch and FP8 ownership. The full StandardDispatcher module also passed 21 tests plus 45 subtests on source bytes verified against this commit.
  • The same new tests fail against the previous production sources for the intended missing scale, non-normalized shared compensation, model admission and dual-stream conditions. Compressed FP8/NVFP4 cases use real scheme/FusedMoE construction, TopK and dispatch with unit/nonunit factors and both renormalization choices. Model policy tests control FP8 quantization/native-provider boundaries; these CPU checks do not execute native quantized GEMMs.
  • The integrated [Refactor] moe: Derive routing inputs from the layer and active forward #44994 head separately passed 119 CPU tests across 12 modules, plus 200 reported subtests. Configured hooks and registration/entrypoint lint pass; strict parsing collects 2,472 files / 3,006 registrations. CPU execution: Python 3.12.15, Torch 2.14.1+cu130, GPUs hidden.

Earlier validation remains historical: the previous stack passed 856 CPU tests across 43 modules with 7 skips. At 97c954fdf334055dee221483622a5b8ae02c6e05, a mixed block-FP8/BF16 Qwen3MoE smoke on 4 NVIDIA B300 GPUs (TP4/EP4) matched all 24 greedy IDs against Triton, with maximum generated-token logprob difference 0.0039258003. Neither result is full-model accuracy validation of this head.

Native TRT-LLM selector parity and full-model accuracy/performance have not been run for these policy changes. Unsupported ModelOpt per-tensor FP8 and compressed MXINT4 materialized-routing capabilities remain limited; rejection still occurs at apply rather than binding, and no compatibility claim is made for unverified conditional checkpoints. ROCm/NPU/XPU/gfx1250 execution and full CI remain unverified. Refs #44291, #40623; related #41636.


CI States

Latest PR Test (Base): ❌ Run #39514001815
Latest PR Test (Extra): ❌ Run #39514001794
Latest PR Test (AMD ROCm 10): ❌ Run #39514001830

detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
… commits since 2a6c204 @ merge-sgl-project#5)

Conflicts: 110 files (106 content / 4 add-add / 0 modify/delete) at the settled
321 tip 2d87757 -- vs merge sgl-project#5's 167; the smaller count despite 950 commits
(merge sgl-project#5: 1,120) is the merge-era's re-plant landing INSIDE upstream's new
window (many fork families -- qwen4 varlen, fast_file, hicache-liveness, the
209-218 controller semantics -- now collide as DUAL IMPLEMENTATIONS: upstream
grew the same families independently in the window). By class: A 7
(auto-takes-upstream, dedupe-verified), B 36 (mechanical union/custom splices),
C 46 (upstream structure taken, fork hunks extracted for re-plant), D 21
(fork-owned flips + dual-impl adjudications, incl. the whole fast_file family).
228 conflict regions total: 69 union (all def/class-collision-checked), 118
take-upstream (104 marked, 14 dedupe-verified), 25 keep-fork (17 fold-marked,
8 strict supersets), 16 custom import/region splices.

121 TODO(merge6) markers planted (tree census): b1 12 / b2 23 / b3 18 / b4 39 /
b5 17 / b6 12. (Resolver census at region-resolution was 117; the cascade-repair
grafts below added the rest.) REPLANT INVENTORY: /tmp/opencode/merge6-dossier/
replant/ -- per conflicted file: <name>.fork-hunks.patch (full 2a6c..321 delta),
<name>.upstream-side.patch (full 2a6c..eb73 delta), <name>.ours-dropped.txt /
<name>.theirs-dropped.txt region snapshots, MANIFEST.tsv (file, zone, regions,
kinds, fork-hunk counts, per-region notes). Work records (conflict census JSON,
decision tables, class table, logs) under .../work/.

D-list outcomes (must-not-auto-resolve, handled deliberately):
- sgl-project#45520 (entry 302): STILL OPEN upstream at eb73a50 (gh-verified + ZERO
  "sgl-project#45520" strings in the +950 window). Entry-230's fail-safe layer is UNTOUCHED
  and stays (standard.py warn-once + published-auto guards intact; the re-apply
  rule armed in CAVEATS was NOT needed this merge).
- sgl-project#44590 (entry 228): the window did NOT move the floor further -- upstream
  pyproject stays sglang-kernel==0.4.10 (absorbed at merge sgl-project#5 via sgl-project#43922) and
  the engine assert_pkg_version stays 0.4.9 in BOTH trees; the
  _load_inline_fragment_probes_available() probe never existed on either side
  (docs-mention only). Nothing to re-assert; both pins kept byte-identical.
- flashinfer_cutlass.py (fork-owned per merge-sgl-project#5 flip): did NOT conflict; 56
  b12x refs intact, dispatcher reads untouched.
- modelopt_quant sgl-project#44993/sgl-project#44994-ERA B12X W4A16 arms: the fork's
  defer-swizzle/b12x conditions at L2941-2996 are CONTESTED against upstream's
  skip_swizzled_blockscales rewrite -> took upstream, b5 markers + region
  snapshots (boot-integrity fields live in the fork-owned cutlass file, which
  survived; the b12x selection ARMS need the B5-style re-plant).
- DUAL-IMPLEMENTATION FAMILIES (the new pattern of this merge; upstream grew
  the same features the fork replanted -- take-upstream + fold-diff replant,
  NEVER a silent pick): kernels/ops/mamba/qwen4_short_conv.py + its test suite,
  srt/models/qwen4_exp.py varlen trio, mem_cache/storage/fast_file/fast_file_store.py +
  test_hicache_fast_file_unit.py, test_hicache_sidecar_restore.py,
  fused_moe_triton/layer.py nvfp4-deferred clause,
  tokenizer_manager _validate_top_logprobs_num, hicache_best_practices.mdx.
  All fork-side versions snapshotted; replant batches diff
  ours-dropped.txt against the taken upstream.
- environ.py: took upstream's SGLANG_EXACT_CHUNK_FILL removal; kept ONLY the
  fork-added SGLANG_SPLIT_PREFILL_AT_MAMBA_FORK line (custom splice).
- entry-219 gauge schema: per-pool hicache_host_pool_{used,total}_tokens names
  SURVIVED the auto-merge (metrics_collector/hicache_pool_stats/metrics_reporter/
  urc all intact); the marked b3 controller regions must RE-VERIFY the producer
  dict end-to-end at re-plant, not assume it.

Cascading silent-auto-merge repairs (files NOT in the conflict set, broken by
auto-merge splices -- all found by the ruff-F821/check_* gates, all fixed here):
utils/common.py upstream prune RE-HOMED the fork's get_mixed_precision_moe_quant_algos
into configs/quant_utils.py (next to the moved siblings) + the make_layers
empty_cache into layers/utils/layer_list.py, importers rewired;
mem_cache/pool_host/base.py silently LOST the entry-sgl-project#44462-era
host_memory_budget_bytes() helper whose caller survived -- grafted back;
model_executor/runner/eager_runner.py CP helpers retargeted to upstream's NEW
layers/cp/utils (cp_shard_model_inputs/cp_gather_after_forward) replacing the
retired runner_utils.cp_extend pair; runner/flashinfer_autotune.py + qsa/mqa.py +
modelopt_quant.py import retargets for the utils/device + layers/dp_attention
move; mem_cache/memory_pool.py lossless-verify tuple buffers re-grafted around
upstream's replayssm skip-chain; unified_radix_cache.py host-capacity deadline
preamble re-grafted (marker kept); qwen4_exp.py _use_qwen4_direct_decode
re-grafted (its kernels survived); qwen4_exp_ple_table.py _HOST_PAGE_TABLES
memo dict re-grafted; rotary_embedding/factory.py get_rope param restored;
multimodal_gen forward_context teacache_plan param restored + server_args.py
Literal import; parallel_executor.py rebuilt as fork-owned + upstream's
raise_if_cancelled guards folded into the fork loop structure;
hybrid_cache_controller.py _reduce_prefetch_ack if/zero_ splice repaired;
python_bindings.rs pyo3 signature REORDERED to match the unioned fn new()
argument order (mamba_value_seqlen position -- a positional-bind footgun, fixed
pre-commit); test_io_struct.py get_context/MAX_PARALLEL_SAMPLES imports;
stat_loggers_di + test_flashinfer_autotune_sync + fused_lora_compose +
tp_worker + compressed_tensors + minimax_h3 + hc_mix + scheduler_mixin +
pool_configurator + scheduler/tokenizer_manager import prunes/grafts.

Gates at commit (CVD=9, prod venv, worktree PYTHONPATH): import sglang OK;
check_registered_tests / check_no_bare_pytest_main / check_no_registered_tests_in_package
ALL rc=0; ruff (F401,F821,F823,UP037 @ v0.17.1 vs pinned 0.15.1) ZERO new errors
on the 3,269 merge-touched .py -- the residual 161 are BYTE-IDENTICAL INHERITED
rows present at BOTH parents (kernels/aot, api_types, mm entrypoints/utils, etc.;
0.17-only detections, not merge damage); ruff format clean on the same set;
py_compile clean; CARGO sglang-radix-tree check+test GREEN: 966 passed / 0 failed
/ 1 ignored (vs merge-sgl-project#5-era 943P -- upstream grew the suite +23; NOTE the crate
is now `exclude`d from the rust/ workspace with extension-manifests metadata --
`cargo -p sglang-radix-tree` from rust/ no longer works; run inside the crate).

NON-ADOPTIONS honored: sglang-kernel floor 0.4.9 (engine assert) untouched;
sgl-project#45520 not brought (fail-safe layer intact by rule).

Re-plant batches owed (per marker zones): B2-2026 test re-home (23), B3-2026
mem_cache/controllers/rust (18), B4-2026 scheduler/managers/runner (39),
B5-2026 moe/quant/kernels/qwen4 (17), B6-2026 environ/arg_groups/docs re-pins
(12), B1-2026 diffusion folds (12). PROD BOOT FORBIDDEN until the B3/B4 zones
re-plant the entry-209/218 controller semantics (the trailing_endpoint gate will
read RED at this commit, exactly as at merge-sgl-project#5's damage state).
YaoleWu added a commit to YaoleWu/sglang that referenced this pull request Nov 12, 2026
… factor

Since sgl-project#44993, TopK folds `routed_scaling_factor` into the top-k weights when
the quant method reports `fuse_routed_scaling_factor_in_topk`. The KT wrapper
forwards that report from its MXFP4 methods, yet the DeepseekV2 MoE epilogue
still scaled the routed output whenever the quant method is a KTEPWrapperMethod
— DSv4.1 (factor 1.5) came out at 2.25x per layer.

Make the decision single-sourced: `KTEPWrapperMethod` declares a duck-typed
`applies_routing_weights_as_given = True` (same style as the fold flag), and
one `_post_moe_needs_routed_scaling()` helper replaces the two hand-copied
conditionals in `forward_normal_dual_stream` and `_post_combine_hook`. The
old `or isinstance(...)` clause made the CUDA short-circuit dead for KT; the
helper makes that impossible by construction. KT is scaled exactly once on
every device; CUDA/MUSA/XPU/AITER and plain-CPU paths keep their runner- vs
epilogue-owned semantics unchanged.

Supersedes sgl-project#45810 (absorbing its teacher-forced accuracy evidence: mean NLL
2.5960 vs reference 2.5940, was 2.8780 before).

Signed-off-by: wuyaole <[email protected]>
05yuki added a commit to 05yuki/sglang-upstream that referenced this pull request Nov 14, 2026
Since sgl-project#44993 the top-k folds routed_scaling_factor into its weights whenever the
quant method says so, and KTEPWrapperMethod forwards that question to its GPU
method (the MXFP4 ones answer yes). DeepseekV2MoE still multiplied the routed
output by the factor again for every KT layer, so the routed experts came out
1.5x too strong on DeepSeek V4.1. Paired NLL on 11,496 tokens against the
checkpoint's own inference code: 2.878 before, 2.596 after (reference 2.594).
QNan0513 added a commit to QNan0513/sglang that referenced this pull request Nov 20, 2026
Since sgl-project#44993, Qwen2MoeSparseMoeBlock binds its TopK to the experts'
runner_backend and routing_method_type when it is built.
SovietPower added a commit to SovietPower/sglang that referenced this pull request Nov 30, 2026
Force STANDARD routing for DeepseekV2, Qwen2MoE, and Qwen3MoE
under MegaMoE, fixing the regression introduced by sgl-project#44993.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blackwell SM100/SM120 deepseek diffusion SGLang Diffusion quant LLM Quantization

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants