Repository navigation
[Fix] [NVIDIA] modelopt-nvfp4: Read w13 global scales in the TRT-LLM [up, gate] order - #44858
Conversation
|
/rerun-test test/registered/unit/layers/quantization/test_modelopt_nvfp4_moe_scales.py test/registered/unit/layers/quantization/test_modelopt_nvfp4_moe_dispatch.py test/registered/unit/layers/quantization/test_modelopt_nvfp4.py test/registered/unit/layers/moe/test_flashinfer_megamoe.py test/registered/backends/test_flashinfer_trtllm_gen_moe_backend.py::TestFlashinferTrtllmGenMoeBackendNvFp4UntiedGateUp test/registered/backends/test_flashinfer_trtllm_gen_moe_backend.py::TestFlashinferTrtllmGenMoeBackendNVFP4 test/registered/backends/test_flashinfer_trtllm_gen_moe_backend.py::TestFlashinferTrtllmGenMoeBackendNvFp4PerTokenActivationRouted test/registered/unit/layers/quantization/test_nvfp4_moe_backends.py test/registered/e2e/models/test_deepseek_v3_fp4.py test/registered/rl/test_update_weights_from_disk_blackwell.py test/registered/e2e/models/test_inkling_small_nvfp4.py test/registered/backends/test_flashinfer_nvfp4_online_moe_backend.py |
|
🚀 🚀 |
| backend = "flashinfer_trtllm" | ||
|
|
||
|
|
||
| class TestFlashinferTrtllmGenMoeBackendNvFp4UntiedGateUp( |
b8zhong
left a comment
There was a problem hiding this comment.
Btw: maybe it's worth checking/asking does the original reported checkpoint absolutely need separate gate and up scales? Since also ModelOpt does this unconditionally since NVIDIA/Model-Optimizer#1033
The only recent checkpoint I found doing it publicly by design is: https://huggingface.co/meta-models/Muse-Spark-Open-816B-A42B-NVFP4 (it use muse_spark_nvfp4_moe.py and doesn't have this bug)
Only flashinfer_trtllm and DeepGEMM MegaMoE NVFP4 support separate scales. It's rejected by Flashinfer MegaMoE, and Flashinfer CuteDSL takes gate global scale and ignore up without warning, which might cause some unexpected inference differences
Revert the contents of 78185f4 while retaining the original canonical-scale loader implementation, MegaMoE layout guard, SwiGLU beta correction, and loader/post-load regression tests. Adopt main's MegaMoE CPU fixture update.
…k-274, wanted_stack LANDED marks, CAVEATS docs-only ledger items (A) Header: STACK line 260->274; three wave lines (+spec-mamba-2026-10-28 (pr45491+pr45435+pr45472+pr45670), +admission-2026-10-28(pr46272*+ pr43484*+pr46496*+pr46643*+pr45607*+pr45789*), +parsers-2026-10-28 (pr44124+pr45631+pr45855+pr46167)); tip line -> 2714457; updated 261-274 headline block (entry-119 SUPERSEDED by upstream sgl-project#45435/sgl-project#45472; classic-pool mamba admission gate w/ upstream ImportError CAUGHT; UNCONDITIONAL latch reset = TTFT watch; coder-parser union; logits trilogy as CONTRACT UNIT; 14 picks, 0 integrator conflicts). (B) wanted_stack.txt: FAM-A5 + FAM-B234 blocks deleted -> LANDED records (chain shas, interlock audit, supersession + behavior-change pointers into entries 261-270); SECTION-B sgl-project#44124/trilogy blocks -> LANDED; sgl-project#37958/sgl-project#45559 block -> DONE (verdict now in CAVEATS). (C) DOCS-ONLY LEDGER ITEMS: CAVEATS gains the sgl-project#37958/sgl-project#45559 VERIFIED- INERT bullet (two independent hard gates, coarse-barrier fallback, do-not-re-litigate-at-merge-sgl-project#5 line, revisit condition = dropping NEXTN or HiCache) and the dated C0b/C0c corrections (sgl-project#44030 obsolete rationale, sgl-project#44858 REVERSED by sgl-project#45289 [ported-pending wt-moe], sgl-project#44115 permanent N/A, 10-28 open-status re-verification list, no-pin-moves note: 0.7.2/0.4.9 floor unchanged) with the C0a tick (sgl-project#37625/sgl-project#37941/sgl-project#39727 still outstanding; only sgl-project#43927/sgl-project#44849 partially satisfied). C0b/C0c/C8 marked DONE in wanted_stack; C0a stays open.
sgl-project#45289) Loader keeps canonical [gate, up] for the per-tensor global scales while weights/block scales follow the kernel's physical row order; TRT-LLM SwiGLU beta gains the 1/g1_alphas_up correction and the gate/up scale-mismatch warning. Reverts sgl-project#44858's call-site workaround -- which THIS fork never had (its skip-note in the 10-19 review record is now stale), so every sgl-project#44858 form is absent here by construction, verified: _compute_gemm1_alphas is byte- identical to the pre-sgl-project#44858 AND post-sgl-project#45289 state, and _compute_trtllm_gated_act_params exists nowhere in the tree. Picks/adaptations (cherry-pick -x 5b1dbc2): * fused_moe_triton/layer.py landed upstream's final form (the trtllm scale re-read block deleted; ModelOpt NVFP4 excluded from the reorder set). * modelopt_quant.py TRT-LLM params inlined with the warning + _up beta. * Seam carve-out: _align_fp4_moe_weights_for_flashinfer_trtllm added to the NVFP4 method (upstream shape from sgl-project#44666, which the oracle test mocks as its GPU-packing stub) wrapping the fork's identical inline call -- the oracle's mock.patch.object(layer.quant_method, ...) seam; behavior for a real boot is unchanged. * Fork guard: load_up_proj_weight_first reads the new use_flashinfer_trtllm_weight_layout term through getattr(..., False); entry-247's b12x CPU contract suite builds the method with __new__ and 6 tests regressed (AttributeError) without the default. b12x itself still resolves False everywhere (not trtllm/cutlass/cutedsl-v2), so b12x_w4a16_w13_layout(up_first=False) -> "w31" (entry-247 defect-(3) derivation) is preserved; test_up_proj_order_is_not_flipped_for_b12x green. * ORACLE test_modelopt_nvfp4_moe_scales.py landed upstream's final form byte-identical EXCEPT the _nvfp4_loader_layer stub carries the placement attrs this fork's SM120 small-M gate reads at process_weights time (num_local_experts/num_fused_shared_experts/moe_ep_rank/moe_ep_size and _num_global_routed behind the property; entry-225's precedent for exactly this stub gap). Assertions untouched. 20 passed + 44 subtests. RED PROOF: reverting the beta line to the pre-sgl-project#45289 1.0/g1_alphas fails test_trtllm_post_load_activation_parameters[situ] here. * backends/test_flashinfer_trtllm_gen_moe_backend.py: sgl-project#45289's change there reverts sgl-project#44858's test edits -> literal no-op for this tree; file verified byte-identical to the upstream post-image. Battery delta vs baseline: scales file 17P/30sub -> 20P/44sub (new oracle tests, green); b12x 67P/46sub after the getattr guard; deferred-scales, modelopt_nvfp4, dispatch, loader, smallm, dispatcher, kernels_namespace (76P, inventory guard), fp8 blockwise suites unchanged. GPU-WINDOW DEBT: end-to-end scale-ordering numerics on the real NVFP4 checkpoint (gate/up alpha mapping through a live TRT-LLM/CUTLASS forward); this commit pins it at CPU contract level only. (cherry picked from commit 5b1dbc2) Co-authored-by: port-moe-contracts subagent (cherry picked from commit 4ec7fdb603ebc300b1177364b4928554ca0a0610)
…20 commits since 12dc623 @ merge-sgl-project#4) Conflicts: 167 files (149 content / 14 add/add / 4 modify/delete) at the settled 309 tip d28e7cd -- dossier predicted 146 +/-25; the +21 shift is entries 275-309 landing qsa-ring/hicache-ctrl/gdn/moe/llguard deltas into the conflict zone. By class: A 13 (auto-takes-upstream, dedupe-verified), B 80, C 56, D 18. 102 TODO(merge5) re-plant/fold markers planted: B1 x15, B2 x29, B3 x12, B4 x23, B5 x23. Re-plant stock: 117 files under /tmp/opencode/merge5-dossier/replant/ (76 fork-hunks patches, 19 upstream-side patches, 14 AA fork copies, 8 preremove snapshots) -- sessions 2/3 re-plant from real code, not memory. D-list outcomes (must-not-auto-resolve, handled personally): - sgl-project#45289-vs-sgl-project#44858 (entry 301): VERIFIED, not re-resolved -- the gate/up-order final form is in origin/main (5b1dbc2 in range); scales test taken as upstream oracle, fork 191-line version saved to replant/ for B5 diffing. sgl-project#44858's call-site shape CANNOT survive (our base never had it). - entry-230 dispatcher vs sgl-project#44993/sgl-project#44994: took upstream structure in token_dispatcher/standard.py; published-value CONTRACT lives upstream via get_moe_runner_backend() in the LoRA-EP guard; fork's warn-once mismatch diagnostic re-plants (B5 marker). UNION GATE: standard_dispatcher 16P (was 12P, suite grew), model_overrides 121P/1S/210sub (was 112P/1S/181sub), fold probe 6P/2F (upstream added a runner_backend arg to the predicate -- B5 re-pins the probe). - entry-219 gauge names vs sgl-project#43727 return + sgl-project#44968: PER-POOL NAMES KEPT as the serving schema -- hicache_host_pool_{used,total}_tokens{pool} dataclass fields, Gauge registrations and labels(pool=) emission re-restored over the #4697x structure; hicache_host_pool_evicted_tokens_total already survived auto-merge; producer dict restored by union in metrics_reporter. ANTI-NEEDLE SATISFIED: old mamba-only gauges are NOT the serving schema. - entry-221 eager-direct add/add: DEDUPED to upstream (bodies identical except est_time 15->9); MEASUREMENT DEBT RECORDED: prefill t/s must be re-measured post-B4 before trusting the est_time. - entry-168 D2H fence vs sgl-project#44800: the fence is ALREADY UPSTREAM (both load_fence_stream + write_fence_stream with the load-thread-corruption comment in origin/main's cache_controller.py) -- nothing re-planted; the two real regions resolved as import-union + comment wording (merge sgl-project#4 stale-tail pattern avoided). Fork hunks still saved to replant/ (belt). - entry-209 clamp + 216/218 ordering + 288-295 hicache-ctrl-era vs #46970x KV rewrite: ADOPTED-UPSTREAM across unified_radix_cache/hicache_storage/ hybrid_cache_controller/memory_pool/kv_cache_builder; EVERY fork hunk extracted to replant/*.fork-hunks.patch; B3 re-plant markers planted. sgl-project#45703's short-full-match seam arrives with upstream. - sgl-project#45090 SGLANG_ENABLE_UNIFIED_RADIX_TREE: REMOVAL TAKEN (fork had already moved it to _DeprecatedEnv; now gone). grep: ZERO .py readers repo-wide; 2 upstream-owned docs jsx snippets still export it (deepseek-v4, glm-5.2 -- upstream's own debt). OPERATOR-OWED CHECK: confirm no /root harness exports it (unreadable from this seat). - sgl-project#39727 unified L3 key: VERIFIED OPT-IN -- merged hicache_storage.py keeps the DEFAULT legacy suffix composition _<model>_<tp_rank>_<tp_size> (content-anchor: HiCacheFile._init_config_suffix, raise-guarded when _unified_chunk_spans is set). ANTI-NEEDLE: no silent key-scheme switch; warm /root/hicache_store contents stay addressable. Modify/delete (4, all victims of upstream sgl-project#45672 test prune + URC split): - test_unified_radix_cache_unittest.py: REMOVED (adopted split) -- its bare unified_tree_core_inspector imports are unreachable post-sgl-project#45236 re-home; fork source + hunks saved; B2 marker planted in the new core test. - test_fused_moe_triton_config.py: REMOVED -- imports common_utils, absent from both sides post-sgl-project#45672; the 2 live entry-3/235 tests re-plant in B2. - test_scheduler_batch_is_full_latch.py: REMOVED -- fork delta was 3 stub-attr lines documenting sgl-project#46643's absorbed arms; upstream deletion correct. - test_qsa_kv_pool.py: KEPT -- fork's 147 added lines are entry-187/200 sharding + 285-287 QSA-ring tests with NO upstream replacement; qsa_kv_pool.py sides converged byte-identical; collects clean. B2 marker. Cascading silent-auto-merge repairs (classes not in the conflict set but broken by auto-merge + union splices -- all found by gates, now fixed): kernels/ops/activation/__init__.py (dead _CUDA registration dup), kernels/ops/ diffusion/__init__.py (5-tuple _SPECS entry), kernels ops embeddings/moe/ attention/mamba __init__ (KernelSpec fields removed upstream: description/ format_signature stripped, CapabilityRequirement->CUDA_ONLY), base_runner/ eager_runner cp_extend + shared_read_event imports retargeted per upstream's "no imports in runner_utils/__init__" contract, and 4 fork helpers grafted back onto their take-upstream homes because merged code/tests still import them (memory_pool.spec_intermediate_bytes_per_req, kv_cache_builder. _adjust_hicache_size_for_draft + _device_pool_size_per_token, hybrid_cache_controller.local_restorable_mask, validation_hook. validate_replayssm_spec_algorithm, arg_groups/moe_hook b12x validator). flashinfer_cutlass.py flipped to FORK-OWNED (b12x route is fork-only, 760 vs 95 lines; upstream sgl-project#44993 hunks = B5 fold patch saved). Silent-semantics notes: sgl-project#46127/sgl-project#44912 riders arrived via per-PR picks (union); sgl-project#45520 (entry 302) is STILL OPEN upstream -- entry-230 fail-safe layer stays as entry 303 records; if a future sync brings it, re-apply the fail-safe reads. qwen4_exp holder-contract fused (ctor takes optional batch). Gates at commit: import sglang OK (CVD=9, prod venv); check_registered_tests/ check_no_bare_pytest_main/check_no_registered_tests_in_package rc=0; ruff F821 +E9+format clean on the resolution set; collect-only over unit/{mem_cache, model_executor,distributed,layers/moe} = 4337 nodes, 3 ERRORS: 2x cargo/torch- sys libtorch probe (REPRODUCED IDENTICALLY AT THE PRE-MERGE TIP -- env issue, not merge damage) + test_hicache_async_ready_sync.py (entry-253-era attribute gone with the URC rewrite -- EXPECTED pre-B3). sessions 2/3 owed: B2 test re-home, B3 mem_cache+rust re-plant (+hicache-ctrl re-ports), B4 scheduler/admission, B5 moe/quant/dispatcher, B6 environ+C0a+ CAVEATS re-pin. PROD BOOT FORBIDDEN until B3 completes (209 clamp + 218 ordering re-plant).
…pair + verified-present consumption -- markers 9-16/17 consumed modelopt_quant (markers x3, "default take-upstream (contested)"): the merged skip_swizzled_blockscales kept upstream's NEW terms (marlin, lora_marlin, auto -- all correct: AUTO resolves later and PWAL rebinds) but LOST the two fork arms the merge-sgl-project#5 B5 era had planted: (i) the entry-247 b12x route (_use_flashinfer_b12x_w4a16 -- fork-only; without it the b12x boot swizzles uninitialized scales at construction, doubling scale storage), and (ii) the entry-296-era serialized-CUTLASS deferral (is_checkpoint_nvfp4_serialized AND enable_flashinfer_cutlass_moe -- the CUTLASS PWAL builds the derived layout after loading). Re-planted as a UNION preserving upstream's shape; the oracle test_nvfp4_deferred_scales went 5P/2F-subtests -> 7P green (the red proof IS real: it asserts swizzle_blockscale NOT called). fp8.py (marker :1984): upstream's new allow_fp8_blockwise_tail restructure re-keyed the w13 scale grid on (block_n, block_k) where the FORK assignment of that pair is (w13's refined N, w2's refined K) -- under the fork's _tp_refined_moe_block_sizes the w13 COLUMNS were then sized by W2's refined k while the refined scale loader repeats each checkpoint k-block by ck_k // weight_block_size[1] == 1 onto the w13 grid: shape mismatch at load on any TP-refined block-FP8 MoE checkpoint. Restored w13_block_n/w13_block_k for the w13 grid (the fork's exact formula byte-restored; upstream's tail arm kept, re-parameterized identically). The refine end-to-end test is CUDA-registered (honest-skip on this seat); the CPU fp8 suites are unchanged (16P, weight_gating's 2 subF in MIXED-file runs reproduce identically with and without this change -- pre-existing cross-file interaction, passes standalone 5P; battery runs per-file). fused_moe layer.py (marker :647): DUAL resolved VERIFIED-PRESENT -- upstream sgl-project#42654 landed its own deferred-finalize-for-routed-TRTLLM inside the window; the fork's entry-206 property survives at :637 with the identical clause set (is_flashinfer_trtllm_routed + nvfp4_deferred + a2a-none + the 2-arg _fuses_routed_scaling_factor_in_topk B5-1 probe contract), the dsv2 format-ternary consumer (entry-301 shape) reads it at deepseek_v2.py:1255-7, and sgl-project#44858's call-site remains GONE (git grep zero -- entry-301's rule holds). Marker consumed. Also consumed VERIFIED-PRESENT (line-removal only): - kernels/ops/gemm/hc_mix.py:303 -- upstream's num_ctas tweak is N/A against the fork's config-table restructure (num_ctas is a per-_HCMixConfig field, min(80, sm_count) cap documented in-file from the 240-combination retune). - configs/quant_utils.py:112 -- the fork helper get_mixed_precision_moe_quant_ algos IS re-homed beside its upstream-moved siblings; both entry-230 consumers (arg_groups/overrides.py:56, model_overrides/qwen3_moe.py:11) import the new address. - qwen_sparse_attn_backend.py:86 -- the fork-owned QSA file absorbed the upstream tweak (vendored FA4 CuTe path sglang.kernels.ops.attention. flash_attn.cute.interface, module exists; ForwardMode via the forward_batch_info re-export). Boot-integrity sweep alongside: entry-178 SM120-FP8-KV trtllm fail-loud ALIVE (trtllm_mha_backend:425-436); entry-230 warn-once + published-auto guards ALIVE in standard.py (:48-50, :160-187); pair_w2_weight fold ALIVE in the fork-owned flashinfer_cutlass.py (:93, :802, :808). Gates: ruff repo ruleset + format + py_compile rc=0 on the 4 touched .py; registration trio + opt-in tiers rc=0.
Motivation
On the FlashInfer TRT-LLM MoE backend, ModelOpt NVFP4 experts whose gate (w1) and up (w3) global scales (
weight_scale_2) differ are dequantized with the two scales swapped. Under this layout the loader stores w13 rows, and their per-tensor scales, as[up, gate], but_compute_gemm1_alphas(#27588) reads column 0 as gate.Standard ModelOpt exports tie gate/up scales (NVIDIA/Model-Optimizer#1033), so most checkpoints are unaffected. Before Model-Optimizer 0.45 (NVIDIA/Model-Optimizer#1560), experts never reached during calibration could stay untied, e.g. 6 of 3,840 in
nvidia/Gemma-4-26B-A4B-NVFP4. It was reported on an in-house checkpoint with untied scales. Online NVFP4 (nvfp4_online.py) quantizes gate/up together with one shared scale, so it is unaffected.Modifications
_compute_gemm1_alphastakesup_firstand reads the columns in w13 row order;process_weights_after_loadingpassesup_first=self.use_flashinfer_trtllm_weight_layout. Other backends are unchanged._compute_trtllm_gated_act_params. Beta is added to the raw up half, so it now usesg1_alphas_up. The kernel applies one clamp limit to both raw halves, which can't be exact for both when their scales differ; it stays in gate-half units and logs a warning.mmangkad/Qwen3-30B-A3B-NVFP4-untied-gate-uponflashinfer_trtllmand require GSM8K >= 0.90 (sgl-eval). Locally: 0.960 with this PR, 0.305 on the base commit.Accuracy Tests
mmangkad/Qwen3-30B-A3B-NVFP4-untied-gate-upisnvidia/Qwen3-30B-A3B-NVFP4withup_proj.weight_scale_2 *= 4andup_proj.weight_scale /= 4in every expert: gate/up differ, dequantized weights are bit-identical.sgl-eval 0.1.3 GSM8K, 200 examples,
--moe-runner-backend flashinfer_trtllm, TP1, 1x B300 (Qwen3 cookbook recipe, but with an NVFP4 checkpoint and a forced MoE backend):Thinking: temperature 0.6, top_p 0.95, max_tokens 32768. Non-thinking: temperature 0.7, top_p 0.8, max_tokens 2048.
Kernel checks for the SwiGLU params: one expert with gate/up scale ratio 0.30, run through
prepare_static_weights_for_trtllm_fp4_moeandtrtllm_fp4_block_scale_moeagainst a dequantized reference (alpha 1.702). Relative error; FP4 noise floor 0.09.Beta:
1/up_alphagives 0.089,1/gate_alphagives 0.508.Clamp, real limit L, kernel given P. Each row is a hypothesis for the real thresholds the kernel applies:
The kernel clamps both raw halves at P, so with untied scales no single P gives both halves the real limit L.
CI States
Latest PR Test (Base): ✅ Run #39319155924
Latest PR Test (Extra): ❌ Run #39319155908
Latest PR Test (AMD ROCm 10): ❌ Run #39319155997