Repository navigation
[Feat] [NVIDIA] moe: FlashInfer CUTLASS MoE for W4AFP8 on SM90 - #40538
cognaiger9 wants to merge 5 commits into
Conversation
a60929d to
c95e1f2
Compare
- Size the FlashInfer tune range with _cutlass_moe_tune_max_num_tokens, like the other cutlass_fused_moe calls (sgl-project#43363). A per-call value leaves MoERunner.refine_tuning_config's lru_cache on stale token buckets. - Read TP/EP placement from the runner config; FlashInferCutlassMoeQuantInfo no longer carries it. - Tests: W4AFP8 site in the tune-range unit test; kernel test publishes server args, passes the layer to MoeRunnerConfig, follows _load_w13's signature and the current A2A error message.
c95e1f2 to
87faf57
Compare
sglang-bot
left a comment
There was a problem hiding this comment.
[sglang-bot Review Agent] A few things to fix before this can go in.
Reviewed with gpt-6.2-astra · xhigh.
| quant_scales=[ | ||
| layer.w13_weight_scale_inv, | ||
| layer.w2_weight_scale_inv, | ||
| a1.reciprocal().to(torch.bfloat16).expand(hidden).contiguous(), |
There was a problem hiding this comment.
[sglang-bot Review Agent] On a warm presharded load, an FC1 scale of 0.75 is restored after this reciprocal was built from 1. The first forward still uses 1. Could we restore the derived scales with the shard or rebuild them after the copy?
There was a problem hiding this comment.
Fixed in 22b9210. The FC1/FC2 activation-scale reciprocals and the per-expert alphas are now registered layer parameters (w13_act_scale_inv, w2_act_scale_inv, w13_alpha, w2_alpha). The presharded copy restores them in place, and apply builds the FlashInfer payload from layer on every call. test_presharded_warm_reload_restores_derived_scales post-processes placeholders, copies the dumped state in, and checks the output matches bit for bit.
There was a problem hiding this comment.
[sglang-bot Review Agent] The warm presharded loader now copies both reciprocals and both alphas into registered parameters. The first apply reads those restored values from the layer.
| layer, | ||
| name, | ||
| Parameter( | ||
| interleave_moe_weights_for_sm90_mixed_gemm(packed, "int4"), |
There was a problem hiding this comment.
[sglang-bot Review Agent] Switching a warm W4AFP8 presharded cache from native CUTLASS to FlashInfer reuses the native gate-first weights. Both runners have the same parameter signature before packing. Could we include the packed layout in the shard key?
There was a problem hiding this comment.
Fixed in 22b9210. _collect_shard_config adds w4afp8_moe_layout: "flashinfer_sm90" when a W4AFP8 model runs with flashinfer_cutlass, next to the cutedsl swap-AB key. Native and FlashInfer W4AFP8 now get different cache folders; other cache keys are unchanged. Covered by test_w4afp8_flashinfer_layout_changes_cache_key.
There was a problem hiding this comment.
[sglang-bot Review Agent] _build_subfolder_name hashes the w4afp8_moe_layout field that FlashInfer adds, so switching from native CUTLASS to FlashInfer selects a different cache folder.
| dispatch_output: StandardDispatchOutput, | ||
| ) -> CombineInput: | ||
| if self.use_flashinfer: | ||
| return self.runner.run(dispatch_output, self.flashinfer_quant_info) |
There was a problem hiding this comment.
[sglang-bot Review Agent] With --cpu-offload-gb covering an expert weight, functional_call stages that weight on GPU, but this payload still points at the CPU parameter. Could we read the packed weights from layer in apply?
There was a problem hiding this comment.
Fixed in 22b9210. apply now reads the packed weights and scales from layer, so the copies functional_call stages on GPU are what reach the kernel. test_cpu_offload_stages_packed_weights offloads the layer with OffloaderV1 and matches the non-offloaded output bit for bit.
There was a problem hiding this comment.
[sglang-bot Review Agent] apply now reads the packed weights and scales from the layer inside OffloaderV1’s functional_call, so the kernel gets the staged GPU tensors.
| ) | ||
|
|
||
| def _process_flashinfer_weights(self, layer: Module) -> None: | ||
| if getattr(layer, "_flashinfer_w4afp8_prepared", False): |
There was a problem hiding this comment.
[sglang-bot Review Agent] A DeepSeek update_weights_from_disk reaches param.weight_loader on a packed parameter that lost that attribute. Could we restore the load-time parameters before the update, or reject it through _derived_weight_cache_error before any weights are written?
There was a problem hiding this comment.
Fixed in 22b9210. FlashInfer W4AFP8 layers set _derived_weight_cache_error, so an online update is rejected before any weight is written, and the error message points to --moe-runner-backend cutlass. Restoring the load-time parameters would also need the packed weights re-interleaved after each update, so I kept this path load-once.
There was a problem hiding this comment.
[sglang-bot Review Agent] update_weights_from_disk checks only local modules, so a DeepSeek pipeline stage containing just the initial dense layers can write the new weights before the MoE stage rejects the update. Could every stage reject this configuration before loading starts?
There was a problem hiding this comment.
Fixed in 4de5d8b. The rejection no longer depends on a local MoE module. W4AFp8Config.get_quant_method runs for every layer on every rank and sets a process-wide flag when the runner backend is flashinfer_cutlass. _unsupported_derived_weight_cache_error then rejects on every rank before any weight is written, following the HPC-Ops bf16xfp32 pattern. Covered by test_weight_updates_rejected_on_every_rank.
There was a problem hiding this comment.
[sglang-bot Review Agent] update_weights_from_disk now checks the flag before it creates the loader. A dense-only DeepSeek stage sets that flag during linear-layer setup, so it returns before loading the new checkpoint.
| "For DeepEP, use --moe-runner-backend cutlass." | ||
| ) | ||
| if ( | ||
| self.quant_config.group_size != 128 |
There was a problem hiding this comment.
[sglang-bot Review Agent] A checkpoint declaring group_size=64 reaches this check as 128 because from_config dropped the value. It gets through validation and fails later copying FC1 scales. Could we validate the declared group size and activation scheme here?
There was a problem hiding this comment.
Fixed in 22b9210. from_config now reads group_size and rejects anything other than 128 for both runners. The native path also assumes group 128 and used to fail later, while copying scales. The activation scheme stays static: W4AFP8 checkpoints don't declare a MoE activation scheme, and from_config has always fixed it.
There was a problem hiding this comment.
[sglang-bot Review Agent] When hf_quant_config.json is the only quantization config, get_quant_config still constructs W4AFp8Config() with defaults, so an expert declaring group_size=64 gets FC1 scales sized for 128. Could the loader carry the expert metadata through and validate it in W4AFp8MoEMethod.create_weights, where the restriction also leaves Humming’s group-64 path intact?
There was a problem hiding this comment.
The group-size check now lives in W4AFp8MoEMethod.create_weights (4de5d8b), so whatever reaches the config is validated for both runners. When the metadata exists only in hf_quant_config.json, get_quant_config builds W4AFp8Config() with defaults because get_config_filenames() is empty. The native runner has the same gap, so I'd rather fix it in a separate PR than widen this one.
There was a problem hiding this comment.
[sglang-bot Review Agent] When the expert group size is declared only in hf_quant_config.json, get_quant_config still defaults to 128, so FusedMoE._load_w13 tries to copy group-64 FC1 scales into a tensor with half the required columns. Could the loader pass the declared expert group size to create_weights so FlashInfer rejects it before allocation?
There was a problem hiding this comment.
For W4AFP8, get_config_filenames() is empty, so when config.json has no quantization_config, get_quant_config returns W4AFp8Config() and the declared group size never reaches the method. The native runner fails the same way at _load_w13, and nothing in this PR changes it. Teaching the loader to read W4AFP8 metadata from hf_quant_config.json changes how every W4AFP8 checkpoint loads, so I'd keep it for a separate PR.
There was a problem hiding this comment.
[sglang-bot Review Agent] With the expert group size declared only in hf_quant_config.json, get_quant_config still defaults to 128 and FusedMoE._load_w13 fails copying group-64 scales into half as many columns. Could the FlashInfer path check the expert entries when ModelConfig reads that file, before allocating the scales?
| tune_max_num_tokens=_cutlass_moe_tune_max_num_tokens(x.shape[0]), | ||
| ) | ||
| if runner_config.routed_scaling_factor is not None: | ||
| output.mul_(runner_config.routed_scaling_factor) |
There was a problem hiding this comment.
[sglang-bot Review Agent] With DeepSeek's KT wrapper and a routed scale of 1.5, the GPU contribution gets 2.25 while the CPU contribution gets 1.5. The model scales the combined output after this multiply. Could we apply the factor once after the two branches join?
There was a problem hiding this comment.
Fixed in 22b9210. The W4AFP8 path now goes through _maybe_apply_routed_scaling_factor, and the payload sets apply_routed_scaling_factor from should_fuse_routed_scaling_factor_in_topk. KTransformers is rejected for FlashInfer W4AFP8 when the layer is created, since deepseek_v2.py scales the combined CPU + GPU output itself. The native cutlass_w4a8_moe path applies the factor the same way under KT, so that path is unchanged here.
There was a problem hiding this comment.
[sglang-bot Review Agent] KTEPWrapperMethod.create_weights calls the GPU method’s create_weights, which now rejects FlashInfer W4AFP8 when kt_weight_path is set. That stops this combination before the first forward.
- Register the derived activation scales and alphas as layer parameters and build the FlashInfer payload from the layer in apply, so presharded warm loads restore them and CPU offload stages them with the weights. - Key the presharded cache on the FlashInfer W4AFP8 layout; native and FlashInfer store different rows at the same shapes. - Refuse online weight updates on FlashInfer W4AFP8 layers through _derived_weight_cache_error. - Parse group_size in W4AFp8Config.from_config and reject values other than 128. - Reject KTransformers CPU experts on this path, and apply the routed scaling factor through _maybe_apply_routed_scaling_factor. - Tests: warm-reload, CPU-offload, scaling opt-out, config and KT checks; shard-config key test.
sglang-bot
left a comment
There was a problem hiding this comment.
[sglang-bot Review Agent] A few things to fix before this can go in.
Still open from my last review:
- The FlashInfer guard checks defaults instead of checkpoint metadata (
python/sglang/srt/layers/quantization/w4afp8.py:377)
Reviewed with gpt-6.2-astra · xhigh.
| weight_block_size = [128, 128] | ||
| # Both the native and FlashInfer kernels use group-128 weight scales. | ||
| group_size = cls.get_from_keys_or(config, ["group_size"], 128) | ||
| if group_size != 128: |
There was a problem hiding this comment.
[sglang-bot Review Agent] A group-64 W4AFP8 checkpoint with --quantization humming now fails here before Humming can build its scale tensors. Could we keep the declared size in the shared parser and enforce 128 in W4AFp8MoEMethod.create_weights?
There was a problem hiding this comment.
Fixed in 4de5d8b. from_config keeps the declared group_size, and the group-128 check is now in W4AFp8MoEMethod.create_weights, so Humming's group-64 path is untouched.
There was a problem hiding this comment.
[sglang-bot Review Agent] from_config preserves a declared group size of 64, and Humming uses it to size its expert scales. The group-128 check now lives in W4AFp8MoEMethod.create_weights.
| "w2_act_scale_inv", | ||
| a2.reciprocal().to(torch.bfloat16).expand(intermediate), | ||
| ), | ||
| ("w13_alpha", a1.expand(experts)), |
There was a problem hiding this comment.
[sglang-bot Review Agent] After an EPLB move, an expert can use the source rank's alpha with the destination rank's reciprocal. That changes its GEMM result when the ranks have different activation-scale maxima. Could we keep these rank-wide scales out of the parameters EPLB migrates?
There was a problem hiding this comment.
Fixed in 4de5d8b. The derived activation scales and alphas are rank-wide, so they are marked _sglang_require_global_experts and filter_moe_weight_param_global_expert leaves them in place. EPLB still moves only the packed weights and their group scales. Covered in test_payload_and_fail_fast.
There was a problem hiding this comment.
[sglang-bot Review Agent] With one local expert, a1.expand(1).contiguous() still shares storage with w13_input_scale, and DeepSeek’s get_moe_weights selects that unmarked input scale, so EPLB can overwrite the alpha while its reciprocal stays put. Could you mark both replacement input-scale parameters _sglang_require_global_experts too?
There was a problem hiding this comment.
Fixed in 05c9415. The derived scales are now copied with clone(memory_format=torch.contiguous_format), so w13_alpha no longer shares storage with w13_input_scale. Both replacement input-scale parameters are marked _sglang_require_global_experts, so EPLB leaves them in place. test_single_local_expert_scales_stay_put checks the EPLB filter at one local expert and that the alphas and input scales use separate storage.
There was a problem hiding this comment.
[sglang-bot Review Agent] At 05c9415f35, both alphas have their own storage, and DeepSeek’s EPLB filter skips both replacement input scales even with one local expert. That fixes the issue.
| self._flashinfer_no_zeros = torch.empty( | ||
| 0, dtype=torch.bfloat16, device=a1.device | ||
| ) | ||
| layer._derived_weight_cache_error = ( |
There was a problem hiding this comment.
[sglang-bot Review Agent] With DeepSeek's initial dense layers on their own PP stage, that stage can load the new checkpoint before the stage with packed experts rejects it. Could we make this rejection visible on every stage before the first write?
There was a problem hiding this comment.
Fixed in 4de5d8b. The rejection no longer depends on a local MoE module. W4AFp8Config.get_quant_method runs for every layer on every rank and sets a process-wide flag when the runner backend is flashinfer_cutlass. _unsupported_derived_weight_cache_error then rejects on every rank before any weight is written, following the HPC-Ops bf16xfp32 pattern. Covered by test_weight_updates_rejected_on_every_rank.
There was a problem hiding this comment.
[sglang-bot Review Agent] DeepSeek’s dense MLP projections call W4AFp8Config.get_quant_method, which now sets the FlashInfer flag even on a stage with no local experts. That stage rejects the disk update before its first write.
- Keep the declared group_size in W4AFp8Config.from_config (Humming reads it) and enforce group 128 in W4AFp8MoEMethod.create_weights. - Mark the rank-wide derived activation scales and alphas as global so EPLB does not migrate them between ranks. - Reject online weight updates through a process-wide flag set in W4AFp8Config.get_quant_method, so pipeline stages without MoE layers reject them too. - Tests: EPLB filter, every-rank update rejection, group_size check in create_weights.
sglang-bot
left a comment
There was a problem hiding this comment.
[sglang-bot Review Agent] A few things to fix before this can go in.
Still open from my last review:
- The FlashInfer guard checks defaults instead of checkpoint metadata (
python/sglang/srt/layers/quantization/w4afp8.py:401) - Expert rebalancing moves alphas away from their matching reciprocals (
python/sglang/srt/layers/quantization/w4afp8.py:490)
Reviewed with gpt-6.2-astra · xhigh.
| flashinfer_w4afp8_weight_update_error, | ||
| ) | ||
|
|
||
| if (reason := flashinfer_w4afp8_weight_update_error()) is not None: |
There was a problem hiding this comment.
[sglang-bot Review Agent] With a FlashInfer W4AFP8 target and an unquantized draft, begin_weight_update(selector="draft") now returns the target’s packed-weight error. Could we keep this flag on the selected runner while still setting it on every pipeline stage?
There was a problem hiding this comment.
Fixed in 05c9415. The process-wide flag is gone, and weight_updater.py matches main again. W4AFp8Config.get_quant_method now sets _derived_weight_cache_error on every layer it builds, MoE and dense alike. A dense-only PP stage still rejects, while a draft built from another config does not. test_weight_updates_rejected_per_model covers both cases.
There was a problem hiding this comment.
[sglang-bot Review Agent] W4AFp8Config.get_quant_method marks Qwen3 MoE’s lm_head, and DSpark registers that same module on the draft at dspark.py:610, so begin_weight_update(selector="draft") still finds the target’s error. Could the target runner own the flag on each pipeline stage?
- Copy the derived activation scales and alphas instead of aliasing the input scales, and keep the replacement input scales out of EPLB, so a rank with one local expert does not move rank-wide scales. - Mark every layer built by W4AFp8Config with _derived_weight_cache_error instead of a process-wide flag, so a draft model from another config can still take online weight updates; weight_updater.py matches main.
Motivation
W4AFP8 MoE checkpoints such as GLM-5.2-W4AFP8 run their routed experts only on SGLang's native CUTLASS W4A8 kernel. FlashInfer ships an SM90 CUTLASS MoE for INT4 group-128 weights with FP8 activations; once autotuned it is 8–16 % faster than the native kernel per MoE call from 2k to 64k tokens on H200. This PR lets
--moe-runner-backend flashinfer_cutlassrun W4AFP8 MoE layers.Modifications
w4afp8.py: withflashinfer_cutlass, load FC1 in[up; gate]order, interleave the packed INT4 weights and group-128 scales with FlashInfer's SM90 mixed-GEMM helpers, reduce the static FP8 activation scales to one per GEMM (as the native path does), and run throughMoeRunner. Rejects non-SM90 GPUs, non-BF16 activations, group size ≠ 128, dynamic activation scales and FlashInfer < 0.6.18.flashinfer_cutlass.py: aw4afp8quant type and itscutlass_fused_moecall (use_w4_group_scaling,use_packed_weights).moe_hook.py: acceptw4afp8forflashinfer_cutlass; only--moe-a2a-backend none(DeepEP stays on--moe-runner-backend cutlass).compressed_tensors_w4a8_fp8_moe.py: compressed-tensors W4AFP8 checkpoints raise a clear error withflashinfer_cutlass.Accuracy Tests
GLM-5.2-W4AFP8, 8×H200, TP8 / DP attention 8 / EP1, native
cutlassvsflashinfer_cutlass:rtol=0.01, atol=0.1(max abs diff 0.22).test/registered/kernels/ops/moe/test_w4afp8_flashinfer.py: 27 passed, 16 subtests passed on H200.Speed Tests and Profiling
Kernel
One MoE call (
FusedMoE.forward_impl), GLM-5.2 TP8 / EP1 shard shapes (256 experts, top-8, hidden 6144) on one H200, in ms; eager CUDA events, median of three rounds. Both arms tuned; collectives excluded.End to end
Measured using
sglang.benchmark.servingonPhalaCloud/GLM-5.3-W4AFP8(same MoE shapes as GLM-5.2), 8×H200, mainfd3c7f6461+ this PR, FlashInfer 0.7.4, sglang-kernel 0.4.11; the FlashInfer arm sets--moe-runner-backend flashinfer_cutlass.Common serving settings:
Benchmark settings:
10 × concurrencyrequests per cell after one full-length warmup batch; request rate unlimited.From concurrency 32, output throughput rises 1–3 %; median TTFT falls 3–4 % at every concurrency. At concurrency 8, throughput is 1 % lower and TPOT 12 % higher.
Output throughput
Median TTFT and TPOT
In milliseconds.
Checklist
CI States
Latest PR Test (Base): ⊘ Skipped -- a maintainer comments⚠️ Run #46840263850
/tag-and-rerun-cito run CI tests.Latest PR Test (Extra): ⊘ Skipped -- a maintainer comments
/tag-and-rerun-cito run CI tests.Latest PR Test (AMD ROCm 10):
Tip
Base CI only covers the core cases, and its workload may not exercise your change. Use
/rerun-testto run the tests your change touches, or copy this prompt for an agent: