Repository navigation
[Refactor] moe: Scope shared-expert configuration to each model - #44913
Conversation
720d6db to
ac55bb9
Compare
|
@ch-wan AMD CI jobs started failing after this PR was merged, and #41391 proposes a fix. Could you review it? MiniCPM-v-2_6 crashes at runner warmup with AttributeError: 'MiniCPMV2_6' object has no attribute 'shared_experts_config'. The PR sets the attribute on the MiniCPMV wrapper, but the loader's model.eval() returns the inner module. The last passing run was on Failing jobs (6):
If this PR isn't the cause, please say so here so the attribution can be corrected. Posted automatically by amd-bot, the AMD CI monitor. Confidence: HIGH. |
…project#44901) cherry-pick -x 3a059de. PORT ORDER: landed FIRST in this family because its merged mainline chronology makes it the strict precondition of sgl-project#44904 (main merges: sgl-project#44901 16:54 -> sgl-project#44904 16:56 -> sgl-project#44912 16:57 -> sgl-project#44913 16:59; sgl-project#44904's diff preimage literally consumes fused_shared_expert_weight / is_routed_scaling_factor_fused_in_topk introduced here, and sgl-project#44913's preimage deletes the helpers sgl-project#44912 introduces -- the only cherry-pickable order is the mainline one; later commits in this family build on earlier ones). Conflict resolutions (2): * models/deepseek_v2.py: the pick's hunk anchors on `class MergedMoEOutput(MoEOutput)` as CONTEXT, but that class is upstream sgl-project#44657 content this fork never took (review-record skip family), so the region conflicted empty-vs-context. Kept ONLY sgl-project#44901's own addition: _scale_routed_and_add_shared (verified byte-identical to the upstream post-image function text) plus all nine routed_scaling_factor_fused_in_topk sites (two __init__ sets, the aiter shared-scaling compensation block, two non-CUDA post-MoE-multiply guards, and the forward_deepep/state-based forward replacements). Nothing in this tree references MergedMoEOutput; did not smuggle it in. * test/registered/unit/layers/moe/test_mega_moe_decode_capacity.py: modify/delete conflict (the file was created by sgl-project#44657, absent here; sgl-project#44901 merely touched 1 line inside it). Kept it deleted. Fidelity: 7/12 python files are BYTE-IDENTICAL to the upstream post-image (topk.py, hash_topk.py, waterfill.py, moe_ep_setup.py, glm4_moe.py, glm4_moe_lite.py, vl_routing.py). mega_moe/mega_moe_flydsl/bailing_moe_v3/ dots3 landed inside files carrying nemotron-era (sgl-project#44518) upstream drift we do not have; their fold changes were diff-reviewed line by line (old `should_fuse_routed_scaling_factor_in_topk or _use_aiter` predicates replaced by the new config-level predicate; residual old-form reads match upstream's own post-image -- legitimately kept). WaterfillBalancer's routed_scaling_factor kwarg became shared_weight (one production constructor, moe_ep_setup, updated by the pick; no other call sites in the tree). Battery (CVD=9) vs base 0df18e9: test_fused_shared_expert_scaling.py 6P -> 12P/25sub (upstream's +343-line fold matrix, green); test_hash_topk.py 3P -> 4P; test_jit_grouped_topk 10S -> 12S (CUDA-gated adds); every pin held (standard_dispatcher_runner_backend 12P, smallm 28P/66sub, b12x 67P/46sub, kernels_namespace 76P, model_overrides 111P/1S/179sub, modelopt suites exact). Pre-existing classes unchanged (trtllm-gen 8F, fused_gate 46F, round-robin 37F, triton-fused-moe 96F, mem_pool_ep 1F, mega_moe_deepgemm 1F). ruff --select=F401,F821,F823,UP037 + ruff format clean on all 18 files. Fold-predicate e2e on real NVFP4 weights stays GPU-window debt (the standalone CPU contract probe follows this family as its own commit). (cherry picked from commit 3a059de) Co-authored-by: port-moe-contracts subagent (cherry picked from commit c4511d515077ea018200eeccfff256cc25ff18e5)
…project#44913) Frozen SharedExpertsConfig resolved once per model at the loader's single instantiation point; the runtime_context MOE flags leaves disable_shared_experts_fusion / speculative_disable_shared_experts_fusion are gone (0 residual readers), model/runner/graph/draft forwards wrap get_model().override(shared_experts=...). Pick adaptations (2 textual conflicts, 1 union fix): * base_runner.py: BOTH methods kept -- model_context() (upstream) + the fork's validate_model_support() (entry-240-era) live side by side; the entry-175 prefill autotune body stays inside the renamed _warmup(). * glm5_next.py: stale MB-era import block; adopted get_num_fused_shared_experts only (upstream's get_moe_runner_backend import feeds code paths the fork never took; F401-clean without it). * test_draft_entry_hook_parity.py NOTE(fork): GATE_WITHOUT_COUNT names upstream-only archs absent from this tree (MiniCPMV4_7 postdates merge sgl-project#4); the lost-gate sweep is scoped to present classes. missing-count assert unchanged. FORK-GATE PRESERVATION (each verified on the final tree): 1. entry 231 mixed-precision fusion veto: ModelOptMixedPrecisionConfig. can_fuse_shared_expert (modelopt_quant.py:1564, Fp4 twin :863) UNTOUCHED -- sgl-project#44913 does not touch modelopt_quant.py or qwen2_moe.py; the veto is consumed at block level (qwen2_moe.py can_fuse_shared_expert -> the block's own num_fused decision), a path sgl-project#44913 leaves byte-identical. Qwen3_5* entry classes sit in upstream's GATE_WITHOUT_COUNT exemption (loader never fuses them) -- block-level fusion stays authoritative for the qwen family. Fork tests survive: TestModelOptMixedBody in test_shared_experts_fusion_gates.py kept alongside upstream's rewrite; test_modelopt_nvfp4.py untouched by the pick. 2. entry 244 degrade-not-raise small-M eligibility wrapper: flashinfer_cutlass.py/modelopt_quant.py not in this pick's 62 files; layer.num_fused_shared_experts reads (modelopt_quant.py:2680 etc.) keep resolving (FusedMoE still takes the kwarg from blocks; layer.py is not in any of this family's picks). battery: test_nvfp4_smallm_dispatch. 3. entry 244 SGLANG_NVFP4_MOE_SM120_MAX_EP predicate: untouched. 4. entry 247 b12x: moe/utils.py ends as upstream-post + the fork's 7 b12x lines only (enum/predicates; zero deletions vs upstream); overrides.py _moe_runner_fusion_disable arg-time force-off feeds get_exec().moe.disable_shared_experts_fusion (fields/exec_.py:930 -- EXEC field survives; only the FLAGS leaves die), so resolve_shared_ experts_config's `disabled` starts from the b12x-set intent. 5. entry 230 published-backend fixes: overrides.py/token_dispatcher/ standard.py not in this pick -- untouched. 6. entry 206/225/239 dispatcher convention: standard.py untouched here. Inventory guard: no KernelSpec added or removed (test_kernels_namespace). Loader hunk verified: resolve_shared_experts_config(model_class, hf_config, quant_config) keeps the quant_config parameter the veto families rely on. Co-authored-by: port-moe-contracts subagent (cherry picked from commit bfc40e12cc9adfd72c8017ae97923305fb9144d2)
… rides entry 300 (sgl-project#44913) sgl-project#44913 wrapped decode-graph replay in base_runner.model_context() -> get_model().override(shared_experts=...), and get_model() raises "config namespace 'model' not published" on a __new__-built runner stub. Production publishes that namespace, so this is the repo's established fork-stub adaptation class (precedent: entry 294's pp_sync_drain _hcs_state pre-memoization), and the file already stubs every other runner hook the same way. TEST-ONLY, zero production lines. Proven by the integrator: 37P at 0df18e9 and at every pick up to sgl-project#44912; 2F/35P from sgl-project#44913 onward, INCLUDING ON THE WORKER'S OWN TREE (aa671ba8cf) -- so the break is inside the delivered batch, not a base-interaction with the landed waves; their battery list did not cover this file. Restored to 37P by this commit. ruff (repo ruleset) + format + check_registered_tests clean.
|
AMD CI jobs started failing after this PR was merged, and the evidence points at this change. MiniCPM-v-2_6 crashes at runner warmup with AttributeError: 'MiniCPMV2_6' object has no attribute 'shared_experts_config'. The PR sets the attribute on the wrapper, but model.eval() returns the inner module; this has failed on all three ROCm lanes since Oct 20. The last passing run was on Failing jobs (4):
If this PR is the cause, a fix or a revert would turn these jobs green again. If it isn't, please say so here so the attribution can be corrected. Posted automatically by amd-bot, the AMD CI monitor. Confidence: HIGH. |
…ies 28,165,166,186,194,206,296,297,299,300
PER-MARKER TRUTH (census: B5 markers in this set now ZERO):
kernels/aot topk.cu (28): VERIFIED-ABSORBED -- upstream's in-range
legacy_radix_topk::select rewrite gates the threshold-bin population
against the stash BEFORE staging (coarse_population >= StashEntries ->
full-row byte-per-pass refinement), structurally fixing the overflow
the fork patched after-the-fact; jit twin keeps its s_prefix_bins.
kernels/ops/attention/utils.py (194): VERIFIED-ABSORBED -- the function
re-sited to ops/attention/kv_indices.py (spec_kv_index_token_blocks with
the 32768 gate) and every consumer imports it at that module; the saved
utils re-export would be a dead hunk (zero importers).
elementwise/elementwise.py (166): VERIFIED-PRESENT -- the batch-invariant
num_warps clamp rides upstream's guard_or_false refactor ('or
is_batch_invariant_mode_enabled()' intact).
kvcache/__init__.py (186): VERIFIED-PRESENT -- the store_cache_fp8
registry entry is the merge commit's own graft (entry 310), imports +
capabilities in place.
moe/hash_topk.py + moe/topk.py (296/297/299/300): the merged upstream
canonicals of sgl-project#44901/sgl-project#44904/sgl-project#44912/sgl-project#44913 are IN RANGE (all four
MERGED commits proven ancestors of 2a6c204); every fork symbol
(fused_shared_expert_weight, is_routed_scaling_factor_fused_in_topk,
num_shared_topk_slots x54, has_per_rank_fused_shared_slots,
SharedExpertsConfig wiring) verified present. Markers stale.
moe/flashinfer_trtllm.py (165): SUPERSEDED-BY-EQUIVALENT -- upstream's
own in-range rewrite of the deferred block covers the routed triple
(do_finalize=not defer + _make_deferred_finalize_output) fail-LOUDER
(valid_deferred_input raise); the fork's sgl-project#6077 ignored-autotune-buffer
targeted the OLD block shape and is deliberately NOT restored (GPU
perf-only, defer+routed is not our production arm).
moe/mega_moe.py (296): deep_gemm transform_sf redirect RE-PLANTED to the
guarded wrapper (import-safety contract; sibling fix in dsv4 below).
fused_moe_triton/layer.py (165/206/239): _built_runner_backend hunk
ABSORBED by sgl-project#44993 (config carries the built runner); the entry-206
supports_routed_deferred_finalize property RE-PLANTED (upstream's
packed_nvfp4_routed_deferred covers TRTLLM only, NOT trtllm_routed --
our runner arm), with the sgl-project#44993 2-arg fold predicate; the debug-log OR
re-plant paired.
models/deepseek_v2.py (296/297/300/236): fold chain verified; the
entry-206 format-ternary consumer arm RE-PLANTED (BYPASSED ->
supports_deferred_finalize, else supports_routed_deferred_finalize --
restoring what sgl-project#44993's rewrite dropped).
Battery ACTUALS (CVD=9, prod venv, PYTHONPATH=python, import sglang OK):
fused_shared_expert_scaling + mega_moe_deepgemm_api + moe_runner_
extensions + topk_routing_inputs + model_overrides + kernels_namespace:
GREEN (see B5-4 commit for full 43-file battery actuals)
… C closure -- the post-merge port queue is now decided ARRIVAL SCAN (git log 12dc623..2a6c204 --grep) + LIVE gh STATE + head-sha comparison for EVERY deferred item. Verdicts: RELEASED-BY-MERGE: sgl-project#42689 (@ 7a632cf in-range -- the SECTION-B cherry is now redundant; behavior note rides the restart). CLOSED (C-items whose PRs arrived and whose integration this stack performed): C1 (the dedicated merge week WAS merge sgl-project#5; all eight precursor PRs in-range), C2 (sgl-project#44993/sgl-project#44994 -- B5), C3 (sgl-project#45232/ sgl-project#45236/sgl-project#45334 -- B2), C4 (sgl-project#45238/sgl-project#45241/sgl-project#45242 -- B3), C5 (sgl-project#44912/ sgl-project#44913 -- arrived; entry-230 canary re-planted as its guard), C9 (sgl-project#39727 -- verified OPT-IN, no purge; BOOT_DELTA anti-needle), C0a (arrival shas already recorded at entry 310 -- Section C now carries NO open code-integration items: C6/C10 retain only their explicitly-named docs/boot-measurement remainders, re-stated). STILL-OPEN: sgl-project#44342 (head unchanged; auto-merge comfort LOST to #46970x), sgl-project#46153/sgl-project#37106/sgl-project#32479/sgl-project#45391 (gh CONFLICTING -- stale bases, rebase before any port), sgl-project#41624/sgl-project#42525/sgl-project#42660/sgl-project#44462/sgl-project#35617 (open, heads unchanged), sgl-project#46191/sgl-project#39845-class (watch-list, none in range). HOLD STANDS (operator decision, binding): sgl-project#43356/sgl-project#46452/sgl-project#43240/ sgl-project#43471 KV route -- step-1 'MERGE sgl-project#5 lands first' is NOW MET; the sequence may be re-visited ONLY with the post-merge PCIe-IPC measurement at an operator sitting. sgl-project#44732: the 'one purge if done WITH the merge' premise LAPSED when merge sgl-project#5 completed without it -- later execution costs the SAME single purge once; no penalty, no haste. Recorded for the operator, not decided by B6.
…t gate main renamed TopKConfig.num_fused_shared_experts to num_shared_topk_slots (sgl-project#44913), so the eligibility check raised AttributeError and the server failed to boot. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n the inner model Since sgl-project#44913, _initialize_model sets model.shared_experts_config on the object the model class returns. For MiniCPM-V that is the MiniCPMV wrapper, whose __getattr__ forwards eval() to the inner nn.Module. The loader then holds the inner model, the attribute is lost, and the first forward fails with "'MiniCPMV4_0' object has no attribute 'shared_experts_config'" on all devices. Forward attribute writes (other than the wrapper's own minicpmv/config) to the inner model, mirroring __getattr__.
This PR is part of a stack (oldest at bottom):
Motivation
Shared-expert fusion determines expert weights, router widths and capture buffers for the lifetime of a loaded model. Resolving the count in each MoE block and passing it through intermediate constructors duplicates that decision; storing target/draft copies in process flags adds a separate restoration protocol.
Resolve the layout once, keep its related quantities together, and expose the active model's configuration during construction and execution.
Modifications
SharedExpertsConfig, owned by the loader-created model. It contains the resolved fusion decision, fused expert count and Waterfill policy. Itsnum_shared_topk_slotsproperty is zero when Waterfill writes the shared slots later, otherwise the fused count.get_model().shared_expertsleaf. The loader scopes construction; runner boundaries scope eager execution, warmup, capture and replay, including direct draft graph paths. Existing bag overrides restore nested and exceptional exits. Model replacement reads the replacement model's configuration.num_fusable_shared_expertscapability. Model families and wrapper entry classes supply the appropriate hooks. MoE blocks and weight loaders read the resolved count at construction.FusedMoE's count argument with its shape inputs. Qwen-family gated shared-expert fusion remains block-local.API changes
TopK.top_kcounts routed experts only and itsnum_fused_shared_expertsargument is removed. HashTopK parameters afternum_expertsare keyword-only. Model integrations declarenum_fusable_shared_expertsalongside their fusion veto instead of overridingdetermine_num_fused_shared_experts. TopKConfig receivesshared_experts, with the ordinary slot count exposed as a read-only property.Validation
At
b500124929, with PyTorch 2.14.1+cu130, sglang-kernel 0.4.10, FlashInfer 0.7.2 and Transformers 5.19.0:test_topk_padded_region.py,test_fused_append_remap_per_rank_shared_slots.py,test_topk_renormalize_degenerate.py,test_jit_grouped_topk.py(31 cases, 7 backend-specific skips).torch.compile(fullgraph=True)with Inductor and CUDA Graph capture/replay pass for ordinary fusion, Waterfill and unfused configurations: three graphs, nine replays with changed inputs and different ambient configurations.6a5c963f49exactly in tokens and expert routes. One of two batched requests varies between repeated PR1 runs; the repeated PR1 run matches PR2 on all six requests. This is limited smoke coverage, not an accuracy benchmark.At the updated head
faaf4bb4e6, after integrating #44912b7f88f502e:setUp, before construction, and removes publication from the numerical reference. Constructor-only scaling fixtures also restore their scope before returning.Not covered: full-model Waterfill or fused-draft E2E, distributed DeepEP/MegaMoE E2E, AMD, NPU or XPU runtime execution.
CI fixture follow-up at
5214d477ecThe ROCm 10 MI35x job failed at
faaf4bb4e6becausetest_deepseek_v4_amd_tp4.py::_moe_stubbypassesDeepseekV2MoE.__init__and omittedrouted_scaling_factor_fused_in_topk. The stub now supplies that construction state. The other five test files in that partition passed. This fixes the test fixture; production executable behavior is unchanged.On one H200, the original fixture reproduces the same AttributeError with the AITER epilogue flags forced; after repair, all four normal/dual-stream and shared-TP1 combinations pass through the actual forward methods. This checks the Python fixture/epilogue contract, not native ROCm collectives or graph replay. The complete AMD TP4 file still needs CI validation.
The kernel comparison now covers normalization and explicit folding independently; the complete standalone router test file passes all 52 cases on one H200. Its stale normalization explanation and CUDA JIT parity claim are corrected. The CUDA counterpart retains its existing unnormalized shared-weight behavior; caller search found tests and benchmarks, with no serving caller.
TopKConfig documents its total ordinary output width and the global AITER absolute shared coefficient versus the standard-path multiplier. Eager/fused subtest labels include the folding mode. Duplicate ordinary model-context scopes and a derived routed-count property remain optional follow-ups. Applicable pre-commit hooks pass. No native AMD rerun or model accuracy result is claimed for this follow-up.
The repaired stack is #44901
cdf052beb7→ #44904beb15ea999→ #44912720d6dbef4→ #449135214d477ec.Attention draft-runner CI follow-up at
bb8c02ce3bThe H100 job failed at
5214d477ecin the MLA Triton draft graph test: the shared attention test kit's_TinyDraftModelbypasses loading and lackedshared_experts_config, whichBaseRunner.model_contextnow requires. The adjacent_EagleDraftExtendForwardtest model had the same omission. Both pure-attention model constructors now carry an explicit emptySharedExpertsConfig, matching the model-owned layout contract. The production runner remains unchanged.On one H200 (torch 2.14.1+cu130, FlashInfer 0.7.2, Triton 3.8.0), the original source produces three missing-attribute errors across the two existing draft decode/extend test methods. After repair, the complete MLA Triton file passes nine tests and the complete dense Triton file passes ten, including EAGLE decode/extend and Frozen-KV capture/replay. Applicable pre-commit checks pass. The earlier image-output equality assertion passed on retry and was not the terminal job failure; no base/head attribution is claimed for it.
Only #44913 changes in this follow-up. The full CI partition has not been rerun locally; these results cover the existing attention graph integration files.
Landing cleanup and CI cost (2026-10-19)
Current head:
974a4e067d, rebased onto main after #44901, #44904 and #44912 merged.torch.compilemodel-context case totest_shared_expert_routing_extra.py, registered for opt-inextra-a-test-1-gpu-small. Their numerical bodies and assertions are preserved, with isolated context setup in the new file.CI States
Latest PR Test (Base): 🚫 Run #39344911007
Latest PR Test (Extra): ❌ Run #39344911138
Latest PR Test (AMD ROCm 10): ⏳ Run #39344910979