Skip to content

[Refactor] moe: Derive routing inputs from the layer and active forward - #44994

Merged
ch-wan merged 59 commits into
mainfrom
cheng/refactor/topk-routing-state
Oct 20, 2026
Merged

ch-wan merged 59 commits into
mainfrom
cheng/refactor/topk-routing-state

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

Model forwards can omit expert placement or the live token count, routing logical IDs against physical expert weights or processing padding as real tokens. Move those decisions into TopK and the active forward. Automatic padding also makes inactive routes reachable at EP1, so every affected consumer must skip their data, weights and expert addresses safely.

Modifications

  • Resolve placement per call and capture draft identity during construction. Align draft weight loading with identity routing, including in-range draft layer IDs; retain target placement-aware loading.
  • Bind the prepared ForwardBatch across eager execution, graph capture/replay, CPU graphs and TBO children. Bind copied row/tail batches too. Decline DeepSeek row-tail capture when its MoE count is a separate GLOBAL buffer, using the existing eager path.
  • Preserve lazy routing metadata until materialization. Keep the producing layer ID in TopKConfig, including piecewise reconstruction, so lazy LP conversion defaults to the correct solver while explicit overrides (including 0) still win. Keep the existing five-field tuple ABI. Reject logits-only consumers that cannot apply required remapping. Route DeepSeek graph admission through the same layer contract. Keep shared expert columns outside LP solving and routed-only remapping.
  • Make Triton, Marlin, GGUF, W4AFP8 and Humming consumers honor inactive routes independently of EP, including NaN inputs/weights and poisoned intermediate buffers. Generic Marlin reuses its projection allocation, clearing the down view after activation consumes the up view; LoRA retains separate zeroed buffers.
  • Support the published sglang-kernel==0.4.10 GGUF provider with Python block-size selection, safe vector indices, masked inactive intermediates/contributions, and initialized MMQ slack metadata. Retain the AOT source fixes for future wheel builds.
  • Initialize CUTLASS FP8 gather maps and use a masked Triton reduction that skips inactive data and weights. Pass token count and supported weight strides at runtime without value specialization so new lengths reuse compiled kernels. This fixes both block-FP8 and MXFP8 without requiring a newly released AOT wheel.
  • Reject LongCat zero-expert placement configurations at startup, since routed-only placement tables cannot represent its identity experts safely. Plain identity placement remains available.
  • Assert the Marlin allocation property rather than an incidental .zero_() call; set its CI runtime estimate to 720 seconds to cover cold compilation.

CI repairs and validation

Current head: 2447ebc8cd21ba19ceb5f94c67826d30ff4aeaa0; base #44993 is 4275a5026050615139c3658a72b6a7d05d65b17f. Updated by normal fast-forward pushes.

Two latest repairs:

  • Shared-expert routing fixture: publishing TP=1 and then overriding EP=8 failed topology validation before routing. Supply a consistent virtual TP=EP=8 topology at rank 3, without process groups or collectives. Registration and numerical assertions are unchanged. On one NVIDIA H200, the original complete file produced seven topology subtest errors; the repaired file passed all four tests at both stack production revisions, including five CUDA router variants, shared contribution and fullgraph compile behavior.
  • AMD AITER prefill: eager draft extend selected a new query-offset table in ForwardMetadata, while CK still received the backend's stale prompt table. Measured Q had 80 rows but the passed offsets reached 4,648, immediately followed by the GPU memory fault. Publish ordinary prefill offsets into the same metadata owner and consume that owner's view in CK, ASM and 5D prefill. Kernel selection, KV padding and speculative helpers are unchanged. #40872 describes the same defect with a producer-side repair; this patch keeps the existing per-forward owner authoritative at consumers.

AMD before/after: the unchanged EAGLE canary failed with a memory fault on both this stack and its original main base. After repair, all 20 requests and original assertions passed (50.6s process). A second serialized observation run passed too: CK received [0,4,...,80], all 588 eager CK calls returned, and no malformed query CSR or HSA fault was observed. Decode graphs and all test assertions remained enabled as configured. Hardware: one AMD MI350X; original CI used MI300. Torch 2.11.0+rocm10.0.0, Triton 3.8.0, AITER 2bb549102, CK 96afae1d5. NHD/BF16 is exercised; the corresponding 5D/FP8/ASM corrections have source review coverage. Final source differs from the tested repair only by removing a stale comment. Independent source review and configured pre-commit checks passed.

H200 fixture runtime: Torch 2.13.0+cu130, Triton 3.7.1, sglang-kernel 0.4.7, FlashInfer 0.6.18. This is single-GPU routing validation, not eight-GPU collective or full-model validation.

Other failures in the latest CI run:

  • JIT B200 failed before tests: its local wheel was truncated to 94 MiB and lacked a ZIP central directory. A sibling verified the same artifact and installed its full 356 MiB wheel successfully (4,821 tests passed). A clean artifact download/retry is needed; no retry was triggered here.
  • Qwen3-Next FP8 HiCache multi-turn KL exceeded its unchanged threshold. The same production code passed this method in the preceding run. The local numerical A/B ran zero comparisons: its Rust cache extension could not build against Torch 2.14.1. No version-check bypass was applied. This failure remains unattributed; no numerical fix or passing baseline is claimed.
  • AMD disaggregation failed at startup with HIP OOM, also seen in an earlier main run. The AITER query-offset fix addresses the separately reproduced EAGLE memory fault, and does not claim to fix this startup failure.
  • NPU QwenImage has identical failing metrics in three unrelated PR runs with the same expected image. A scoped source audit found no changed numerical path from this MoE stack, but no bare-base NPU A/B was run and its root cause remains unresolved.

Earlier CI-only repairs at 0a3e1cfa68 remain included: inherited DeepSeek dual-stream fixture correction from #44993, current activation import, Bailing NextN/V3 parity ownership, and Python 3.11 wheel selection in the simulator job. Their recorded validation was 54 quantization tests, 85 kernel namespace tests, the complete DeepSeek opcheck/compile/graph-replay test at both production revisions, two parity tests, 49 fusion-gate tests plus 11 subtests, and artifact-name matching. Those checks were not rerun for these bounded changes. Full CI and full-model acceptance remain pending; earlier validation below stays tied to its named revisions.

Earlier validation after rebase

Head: 5a0a941ff3013d5c98cff1a5854d03bebff7324c. Rebased onto main 553836c1647b3bfbeb266b49d76ec2c9df012425; base cheng/refactor/moe-layer-backend-semantics is fc2dd3d90bf86fe1b61741c1bb8d28a4e121dc8a.

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: 068e12b7c155babfdc6eea074812b12c7830a3df, including #44993 at b37b73a1ae1bdf3d73b6108deb76a14679a079b4, all lower PRs, and main 693d33330647c57f82e09ac39a34122fa46b5763.

  • At this exact integrated head, 12 focused CPU modules passed: 119 tests plus 200 reported subtests. Coverage includes lazy LP ownership, routing metadata/graph bounds, dispatcher contracts, shared/routed scale, native model policy admission, ModelOpt/FP8 ownership, runner extensions and placement. The lower PR was also checked independently. New regressions fail against their pre-fix production sources for the intended conditions.
  • All 3 CUTLASS FP8 CUDA test methods passed on one NVIDIA B300, including real native block-FP8/MXFP8 GEMMs and mixed/all-inactive graph replay. The reduction test spans 12 token counts, contiguous/transposed weights, FP16/BF16 and poisoned NaN routes. The old real Triton cache grew to 23 entries per dtype; the fixed kernel retains 1. Tested kernel/test bytes are unchanged by the final merge.
  • Native environment: Python 3.12.15, Torch 2.14.1+cu130, Triton 3.8.0, FlashInfer 0.7.2 and published sglang-kernel 0.4.10. Incompatible FlashInfer 0.7.1 cubin/cache packages were ignored; kernels compiled as needed.
  • Configured hooks passed on all 11 files touched in this round. Strict registration/entrypoint checks pass: 2,472 files / 3,006 registrations.

Earlier validation at the preceding heads remains historical: 856 CPU tests across 43 modules with 7 skips, 18 native Marlin cases, 2 prior CUTLASS FP8 methods and 4 GGUF cases against the published 0.4.10 wheel. The new focused CPU and 3-method CUTLASS runs above replace the corresponding coverage for this revision; the Marlin/GGUF kernels are unchanged this round.

The earlier reduced Qwen3 TP4/EP4 reverse-placement graph smoke matched 72 generated IDs and logprobs at its recorded revision; it was not rerun as full-model validation here. No new all-valid reduction latency, dropped-block scan cost or serving throughput measurement is claimed. Native TRT-LLM selector parity, full-model accuracy, ROCm/NPU/AMX and external FlashInfer/HPC/KT consumer coverage remain unverified. Full CI has not been established for this head.

Main integration for merge

Current head: ad06555c737b78c7767cba9b51e0c2ba6305b8ed. Integrated main at 533020b500ba781bfafd1f5cbadabaf03d8986f7 with a history-preserving merge.

Retained TopK's ownership of per-call routing inputs, combined draft identity placement with main's explicit uses_expert_location API, preserved main's gfx1250 expert-parallel support, and reconciled the dispatcher and MegaMoE fixtures. Removed an automatically restored Qwen3 model-side dispatch input; the model routing audit found no remaining legacy inputs across 297 model files.

Independent static review and the normal configured pre-commit hooks passed for these integration changes. Unit/GPU tests and CI were not rerun for this landing; earlier results remain tied to their stated revisions. The two reviewed Muse/W4A8 allocation costs will be repaired in a separate follow-up PR.


CI States

Latest PR Test (Base): 🚫 Run #39514945471
Latest PR Test (Extra): 🚫 Run #39514945509
Latest PR Test (AMD ROCm 10): 🚫 Run #39514945468

@ch-wan ch-wan added run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci) bypass-fail-fast CI: a failing job no longer aborts its siblings (lint still gates) parallel-stages CI: stages dispatch together instead of waiting on each other labels Oct 18, 2026
@ch-wan
ch-wan requested a review from DarkSharpness as a code owner October 18, 2026 22:52
@ch-wan
ch-wan merged commit 299a75a into main Oct 20, 2026
61 of 82 checks passed
@ch-wan
ch-wan deleted the cheng/refactor/topk-routing-state branch October 20, 2026 23:26
Jacob0226 added a commit to Jacob0226/sglang that referenced this pull request Oct 21, 2026
Follow sgl-project#44994: TopK derives num_token_non_padded and the expert-location
dispatch info itself, so _gate_and_topk drops both and the one-launch
router reads them from moe.topk.routing_inputs().

Co-authored-by: Cursor <[email protected]>
05yuki added a commit to 05yuki/deepseek-v4.1-flash-1017-ktransformers that referenced this pull request Oct 21, 2026
…lts remeasured in one launch

- SGLang main moves from ed0b8f43 to da7e3f1c (149 commits). Its TopK now resolves
  --init-expert-location for every router (sgl-project/sglang#44994), so the placement
  patch no longer remaps logical to physical ids in the KT wrapper: done twice, the
  output was garbage with no error. The patch keeps the routing dump only. prefill-lend
  and stream-prefill follow upstream's padded-query buffer, tail source and CUTLASS
  workspace changes.
- serve.sh / lib/kt-lend-auto.sh: until a setup has fitted the prefill plan's cost, the
  plan uses a prior (KT_PREFILL_PLAN_COST_PRIOR, measured on two 16 GB cards). With a
  row-only cost, a new setup planned 13,312-row chunks at 1M and the indexer's scores
  ran out of memory.
- Results, every row from one launch at the new tag: decode Japanese prose 45.1, code
  33.8, math 37.6 tok/s; prefill 35K 758, 1M 579 tok/s. The previous README took the
  131K-1M rows from an earlier launch.
- Checked: tool calls 5/5, an 11.8K-token document summarised correctly, paired NLL
  3.1489, no out-of-memory up to 1M.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01C2UBZdnrDZSBh8yQz8rc9g
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bypass-fail-fast CI: a failing job no longer aborts its siblings (lint still gates) deepseek jit-kernel lora npu parallel-stages CI: stages dispatch together instead of waiting on each other quant LLM Quantization run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci) sgl-kernel

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants