From 994acce994f94070e6b8398dc854e49b3442e895 Mon Sep 17 00:00:00 2001 From: jbernloehr Date: Wed, 7 Oct 2026 22:36:11 +0200 Subject: [PATCH 1/4] [Bugfix][MoE] Reuse the FlashInfer CUTLASS MoE workspace across layers Reserve caller-owned CUTLASS MoE scratch during profiling through the workspace manager and reuse it for bounded batches and sequential layers. Retain the existing allocation path when the workspace API is unavailable. Add compatibility and workspace lifetime regression coverage. Co-authored-by: Codex Signed-off-by: jbernloehr --- tests/kernels/moe/test_flashinfer_moe.py | 86 +++++++++++- tests/utils_/test_flashinfer_utils.py | 24 ++++ .../experts/flashinfer_cutlass_moe.py | 130 ++++++++++++++++++ vllm/utils/flashinfer.py | 23 ++++ 4 files changed, 262 insertions(+), 1 deletion(-) diff --git a/tests/kernels/moe/test_flashinfer_moe.py b/tests/kernels/moe/test_flashinfer_moe.py index a98844d5f8b5..4aed902616dc 100644 --- a/tests/kernels/moe/test_flashinfer_moe.py +++ b/tests/kernels/moe/test_flashinfer_moe.py @@ -3,6 +3,7 @@ import pytest import torch +import vllm.model_executor.layers.fused_moe.experts.flashinfer_cutlass_moe as fi_moe from tests.kernels.moe.utils import make_test_quant_config from tests.kernels.quantization.nvfp4_utils import ( FLOAT4_E2M1_MAX, @@ -29,9 +30,13 @@ ) from vllm.model_executor.layers.fused_moe.modular_kernel import FusedMoEKernel from vllm.platforms import current_platform -from vllm.utils.flashinfer import has_flashinfer_cutlass_fused_moe +from vllm.utils.flashinfer import ( + has_flashinfer_cutlass_fused_moe, + has_flashinfer_cutlass_fused_moe_workspace, +) from vllm.utils.math_utils import next_power_of_2 from vllm.utils.torch_utils import set_random_seed +from vllm.v1.worker.workspace import current_workspace_manager if not has_flashinfer_cutlass_fused_moe() or not current_platform.has_device_capability( 100 @@ -53,6 +58,85 @@ ] +@pytest.mark.skipif( + not has_flashinfer_cutlass_fused_moe_workspace(), + reason="Requires caller-owned CUTLASS MoE workspace support", +) +@pytest.mark.parametrize("dp_size", [1, 2]) +@pytest.mark.parametrize("activation", [MoEActivation.SILU, MoEActivation.RELU2_NO_MUL]) +@torch.inference_mode() +def test_flashinfer_workspace_reused_after_lock( + dp_size, activation, workspace_init, monkeypatch +): + """Small-first warmup must cover a gathered batch and reuse storage per layer.""" + parallel = FusedMoEParallelConfig.make_no_parallel() + parallel.dp_size = dp_size + config = FusedMoEConfig( + num_experts=8, + experts_per_token=2, + hidden_dim=256, + intermediate_size=512, + num_local_experts=8, + num_logical_experts=8, + activation=activation, + device="cuda", + moe_parallel_config=parallel, + in_dtype=torch.bfloat16, + routing_method=RoutingMethodType.TopK, + max_num_tokens=32, + ) + layers = [FlashInferExperts(config, FusedMoEQuantConfig.make()) for _ in range(2)] + max_rows = 32 * dp_size + x = torch.randn(max_rows, 256, device="cuda", dtype=torch.bfloat16) / 10 + w1 = ( + torch.randn( + 8, + 512 * (2 if activation.is_gated else 1), + 256, + device="cuda", + dtype=torch.bfloat16, + ) + / 10 + ) + w2 = torch.randn(8, 256, 512, device="cuda", dtype=torch.bfloat16) / 10 + ids = torch.tensor([0, 1], device="cuda").expand(max_rows, 2) + weights = torch.full((max_rows, 2), 0.5, device="cuda") + buffers = [] + kernel = fi_moe.flashinfer_cutlass_fused_moe + + def compare_with_unbuffered(**kwargs): + # Assert that the new path really ran, then compare the same kernel + # with and without caller-owned scratch. + buffers.append(kwargs["workspace_buffer"]) + result = kernel(**kwargs) + reference = torch.empty_like(kwargs["output"]) + kernel(**{**kwargs, "workspace_buffer": None, "output": reference}) + torch.testing.assert_close(kwargs["output"], reference) + return result + + monkeypatch.setattr(fi_moe, "flashinfer_cutlass_fused_moe", compare_with_unbuffered) + for layer, rows in [(layers[0], 1), (layers[1], max_rows), (layers[0], 16)]: + layer.apply( + output=torch.empty_like(x[:rows]), + hidden_states=x[:rows], + w1=w1, + w2=w2, + topk_weights=weights[:rows], + topk_ids=ids[:rows], + activation=activation, + global_num_experts=8, + expert_map=None, + a1q_scale=None, + a2_scale=None, + workspace13=None, + workspace2=None, + expert_tokens_meta=None, + apply_router_weight_on_input=False, + ) + current_workspace_manager().lock() + assert all(buffer is buffers[0] for buffer in buffers) + + @pytest.mark.parametrize( "activation", [MoEActivation.SWIGLUOAI, MoEActivation.SWIGLUOAI_UNINTERLEAVE], diff --git a/tests/utils_/test_flashinfer_utils.py b/tests/utils_/test_flashinfer_utils.py index 3d28486ff50b..d5e3a07d867c 100644 --- a/tests/utils_/test_flashinfer_utils.py +++ b/tests/utils_/test_flashinfer_utils.py @@ -3,12 +3,36 @@ import importlib.util from collections.abc import Iterator from pathlib import Path +from types import SimpleNamespace import pytest import vllm.utils.flashinfer as fi +@pytest.mark.parametrize("has_sizer", [False, True]) +@pytest.mark.parametrize("accepts_workspace", [False, True]) +def test_cutlass_workspace_requires_both_apis( + monkeypatch: pytest.MonkeyPatch, has_sizer: bool, accepts_workspace: bool +): + """Older FlashInfer versions must never receive an unsupported keyword.""" + module = SimpleNamespace( + cutlass_fused_moe=( + (lambda *, workspace_buffer=None: None) + if accepts_workspace + else (lambda: None) + ) + ) + if has_sizer: + module.cutlass_fused_moe_workspace_size = lambda: 256 + monkeypatch.setattr(fi, "has_flashinfer_cutlass_fused_moe", lambda: True) + monkeypatch.setattr(fi, "_get_submodule", lambda name: module) + # Bypass the process-wide capability cache without changing it for other tests. + assert fi.has_flashinfer_cutlass_fused_moe_workspace.__wrapped__() == ( + has_sizer and accepts_workspace + ) + + def _make_exe(path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.touch(mode=0o755) diff --git a/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py b/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py index 718e018c47e6..6dcd9f716d92 100644 --- a/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py +++ b/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py @@ -29,7 +29,13 @@ from vllm.platforms import current_platform from vllm.utils.flashinfer import ( flashinfer_cutlass_fused_moe, + flashinfer_cutlass_fused_moe_workspace_size, has_flashinfer_cutlass_fused_moe, + has_flashinfer_cutlass_fused_moe_workspace, +) +from vllm.v1.worker.workspace import ( + current_workspace_manager, + is_workspace_manager_initialized, ) logger = init_logger(__name__) @@ -91,6 +97,12 @@ def __init__( self.tp_size = moe_config.moe_parallel_config.tp_size self.out_dtype = moe_config.in_dtype self.use_dp = moe_config.moe_parallel_config.dp_size > 1 + # Upper bound on input.size(0) seen by the kernel. With DP the MoE + # input can be gathered across DP ranks before the experts run. + self._max_workspace_rows = moe_config.max_num_tokens * max( + 1, moe_config.moe_parallel_config.dp_size + ) + self._workspace_nbytes: dict[tuple, int] = {} # Enables DeepSeek-style FP8 block-scale path: # - pass per-block weight scales to the kernel # - skip input activation quantization (kernel applies scaling) @@ -242,6 +254,110 @@ def workspace_shapes( # potential communication op and is involved in the expert computation. return (workspace1, workspace2, output_shape) + def _get_workspace_buffer( + self, + hidden_states: torch.Tensor, + fc1_expert_weights: torch.Tensor, + fc2_expert_weights: torch.Tensor, + top_k: int, + activation: MoEActivation, + use_mxfp8_act_scaling: bool, + use_w4_group_scaling: bool, + ) -> torch.Tensor | None: + """Return a persistent FlashInfer CUTLASS MoE workspace, or None. + + Without a caller-owned workspace, FlashInfer allocates and frees its + GEMM scratch (about 20 GiB for 16k tokens with DP=8) through the + PyTorch caching allocator on every MoE layer call, which fragments the + allocator during large prefills. Size one buffer for the largest batch + once, during memory profiling, and share it across all MoE layers that + run sequentially in the current ubatch and lane. + """ + if ( + not has_flashinfer_cutlass_fused_moe_workspace() + or not is_workspace_manager_initialized() + # Unexpectedly large batches keep the per-call allocation rather + # than pinning one more persistent buffer per distinct size. + or hidden_states.size(0) > self._max_workspace_rows + ): + return None + + # Always size for the maximum so every call shares a single buffer. + rows = self._max_workspace_rows + hidden_size = fc2_expert_weights.size(1) + # fc1 rows are logical (unpacked): inter_size, times 2 if gated. + inter_size = fc1_expert_weights.size(1) // (2 if activation.is_gated else 1) + num_experts_total = fc2_expert_weights.size(0) * self.ep_size + size_key = ( + rows, + hidden_size, + inter_size, + num_experts_total, + top_k, + hidden_states.dtype, + fc1_expert_weights.dtype, + activation, + use_mxfp8_act_scaling, + use_w4_group_scaling, + ) + nbytes = self._workspace_nbytes.get(size_key) + if nbytes is None: + try: + nbytes = int( + flashinfer_cutlass_fused_moe_workspace_size( + rows, + hidden_size, + inter_size, + num_experts_total, + top_k, + x_dtype=hidden_states.dtype, + weight_dtype=fc1_expert_weights.dtype, + output_dtype=self.out_dtype, + activation_type=activation_to_flashinfer_type(activation), + tp_size=self.tp_size, + tp_rank=self.tp_rank, + ep_size=self.ep_size, + ep_rank=self.ep_rank, + use_deepseek_fp8_block_scale=self.use_deepseek_fp8_block_scale, + use_w4_group_scaling=use_w4_group_scaling, + use_mxfp8_act_scaling=use_mxfp8_act_scaling, + device=hidden_states.device, + ) + ) + except (RuntimeError, ValueError) as e: + logger.warning_once( + "FlashInfer CUTLASS MoE workspace sizing failed (%s); " + "falling back to per-call workspace allocation.", + e, + ) + nbytes = 0 + self._workspace_nbytes[size_key] = nbytes + if nbytes <= 0: + return None + + device = hidden_states.device + key = ("flashinfer_cutlass_fused_moe_workspace", device, nbytes) + + def _allocate() -> torch.Tensor: + logger.info_once( + "Reserving a persistent %.2f GiB FlashInfer CUTLASS MoE " + "workspace for up to %d tokens.", + nbytes / (1 << 30), + rows, + ) + return torch.empty((nbytes,), dtype=torch.uint8, device=device) + + try: + return current_workspace_manager().get_persistent_resource(key, _allocate) + except AssertionError: + # The workspace is locked and this size was not reserved in warmup. + logger.warning_once( + "FlashInfer CUTLASS MoE workspace of %d bytes was not reserved " + "during warmup; falling back to per-call allocation.", + nbytes, + ) + return None + def apply( self, output: torch.Tensor, @@ -362,6 +478,19 @@ def apply( fc1_expert_weights = w1 fc2_expert_weights = w2 + workspace_kwargs = {} + workspace = self._get_workspace_buffer( + hidden_states, + fc1_expert_weights, + fc2_expert_weights, + topk_ids.size(1), + activation, + use_mxfp8_act_scaling, + use_w4_group_scaling, + ) + if workspace is not None: + workspace_kwargs["workspace_buffer"] = workspace + _ = flashinfer_cutlass_fused_moe( input=hidden_states, token_selected_experts=topk_ids.to(torch.int), @@ -386,6 +515,7 @@ def apply( use_deepseek_fp8_block_scale=self.use_deepseek_fp8_block_scale, use_mxfp8_act_scaling=use_mxfp8_act_scaling, use_w4_group_scaling=use_w4_group_scaling, + **workspace_kwargs, ) def moe_sum(self, input: torch.Tensor, output: torch.Tensor) -> None: diff --git a/vllm/utils/flashinfer.py b/vllm/utils/flashinfer.py index d7fa807c33b3..40bf4870310e 100644 --- a/vllm/utils/flashinfer.py +++ b/vllm/utils/flashinfer.py @@ -9,6 +9,7 @@ import functools import importlib import importlib.util +import inspect import os import shutil from collections.abc import Callable, Iterator @@ -266,6 +267,9 @@ def pin_host_range_buf(length: int) -> None: flashinfer_cutlass_fused_moe = _lazy_import_wrapper( "flashinfer.fused_moe", "cutlass_fused_moe" ) +flashinfer_cutlass_fused_moe_workspace_size = _lazy_import_wrapper( + "flashinfer.fused_moe", "cutlass_fused_moe_workspace_size" +) flashinfer_cutedsl_grouped_gemm_nt_masked = _lazy_import_wrapper( "flashinfer.cute_dsl.blockscaled_gemm", "grouped_gemm_nt_masked" ) @@ -530,6 +534,23 @@ def has_flashinfer_cutlass_fused_moe() -> bool: return True +@functools.cache +def has_flashinfer_cutlass_fused_moe_workspace() -> bool: + """Return `True` if FlashInfer CUTLASS fused MoE accepts a caller-owned + workspace buffer (``workspace_buffer=`` plus + ``cutlass_fused_moe_workspace_size``).""" + if not has_flashinfer_cutlass_fused_moe(): + return False + mod = _get_submodule("flashinfer.fused_moe") + if mod is None or not hasattr(mod, "cutlass_fused_moe_workspace_size"): + return False + try: + params = inspect.signature(mod.cutlass_fused_moe).parameters + except (TypeError, ValueError): + return False + return "workspace_buffer" in params + + @functools.cache def has_flashinfer_cutedsl_grouped_gemm_nt_masked() -> bool: """Return ``True`` if FlashInfer CUTLASS fused MoE is available.""" @@ -1301,6 +1322,7 @@ def is_flashinfer_cudnn_fp8_prefill_attn_supported() -> bool: "is_flashinfer_cutedsl_bf16_gemm_supported", "flashinfer_trtllm_fp8_block_scale_moe", "flashinfer_cutlass_fused_moe", + "flashinfer_cutlass_fused_moe_workspace_size", "flashinfer_cutedsl_grouped_gemm_nt_masked", "flashinfer_prepare_bf16_fp4_weights", "flashinfer_fp4_quantize", @@ -1323,6 +1345,7 @@ def is_flashinfer_cudnn_fp8_prefill_attn_supported() -> bool: "has_flashinfer_nvlink_two_sided", "has_flashinfer_nvlink_one_sided", "has_flashinfer_cutlass_fused_moe", + "has_flashinfer_cutlass_fused_moe_workspace", "has_flashinfer_cutedsl_grouped_gemm_nt_masked", "has_flashinfer_recurrent_kda", "has_flashinfer_fused_kda_decode", From 630e30d8f7127731e75bfd71cb593fef55db2992 Mon Sep 17 00:00:00 2001 From: jbernloehr Date: Fri, 23 Oct 2026 11:28:26 +0200 Subject: [PATCH 2/4] Fix CUTLASS workspace sizing for autotuning and elastic DP Use fi_moe_largest_bucket for the persistent workspace reservation. Extend the existing reuse regression to check capacity for the autotuning floor and elastic DP while preserving buffered output comparison and reuse after locking. Co-authored-by: Codex Signed-off-by: jbernloehr --- tests/kernels/moe/test_flashinfer_moe.py | 36 ++++++++++++++++--- .../experts/flashinfer_cutlass_moe.py | 7 ++-- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/tests/kernels/moe/test_flashinfer_moe.py b/tests/kernels/moe/test_flashinfer_moe.py index 4aed902616dc..fd2af030e8df 100644 --- a/tests/kernels/moe/test_flashinfer_moe.py +++ b/tests/kernels/moe/test_flashinfer_moe.py @@ -29,6 +29,9 @@ is_valid_flashinfer_cutlass_fused_moe, ) from vllm.model_executor.layers.fused_moe.modular_kernel import FusedMoEKernel +from vllm.model_executor.layers.quantization.utils.flashinfer_utils import ( + activation_to_flashinfer_type, +) from vllm.platforms import current_platform from vllm.utils.flashinfer import ( has_flashinfer_cutlass_fused_moe, @@ -62,13 +65,22 @@ not has_flashinfer_cutlass_fused_moe_workspace(), reason="Requires caller-owned CUTLASS MoE workspace support", ) -@pytest.mark.parametrize("dp_size", [1, 2]) +@pytest.mark.parametrize( + "max_num_tokens, dp_size, elastic_ep_max_dp_size, workspace_rows", + [(32, 1, None, 8192), (32, 2, None, 8192), (4096, 2, 4, 16384)], +) @pytest.mark.parametrize("activation", [MoEActivation.SILU, MoEActivation.RELU2_NO_MUL]) @torch.inference_mode() def test_flashinfer_workspace_reused_after_lock( - dp_size, activation, workspace_init, monkeypatch + max_num_tokens, + dp_size, + elastic_ep_max_dp_size, + workspace_rows, + activation, + workspace_init, + monkeypatch, ): - """Small-first warmup must cover a gathered batch and reuse storage per layer.""" + """Locked reuse must cover gathered inputs, autotuning and elastic DP.""" parallel = FusedMoEParallelConfig.make_no_parallel() parallel.dp_size = dp_size config = FusedMoEConfig( @@ -83,10 +95,11 @@ def test_flashinfer_workspace_reused_after_lock( moe_parallel_config=parallel, in_dtype=torch.bfloat16, routing_method=RoutingMethodType.TopK, - max_num_tokens=32, + max_num_tokens=max_num_tokens, + elastic_ep_max_dp_size=elastic_ep_max_dp_size, ) layers = [FlashInferExperts(config, FusedMoEQuantConfig.make()) for _ in range(2)] - max_rows = 32 * dp_size + max_rows = max_num_tokens * dp_size x = torch.randn(max_rows, 256, device="cuda", dtype=torch.bfloat16) / 10 w1 = ( torch.randn( @@ -101,6 +114,18 @@ def test_flashinfer_workspace_reused_after_lock( w2 = torch.randn(8, 256, 512, device="cuda", dtype=torch.bfloat16) / 10 ids = torch.tensor([0, 1], device="cuda").expand(max_rows, 2) weights = torch.full((max_rows, 2), 0.5, device="cuda") + expected_nbytes = fi_moe.flashinfer_cutlass_fused_moe_workspace_size( + workspace_rows, + 256, + 512, + 8, + 2, + x_dtype=x.dtype, + weight_dtype=w1.dtype, + output_dtype=x.dtype, + activation_type=activation_to_flashinfer_type(activation), + device=x.device, + ) buffers = [] kernel = fi_moe.flashinfer_cutlass_fused_moe @@ -108,6 +133,7 @@ def compare_with_unbuffered(**kwargs): # Assert that the new path really ran, then compare the same kernel # with and without caller-owned scratch. buffers.append(kwargs["workspace_buffer"]) + assert buffers[-1].nbytes >= expected_nbytes result = kernel(**kwargs) reference = torch.empty_like(kwargs["output"]) kernel(**{**kwargs, "workspace_buffer": None, "output": reference}) diff --git a/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py b/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py index 6dcd9f716d92..8f8952cb0aa1 100644 --- a/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py +++ b/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py @@ -13,6 +13,7 @@ from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import ( TopKWeightAndReduceNoOP, ) +from vllm.model_executor.layers.fused_moe.utils import fi_moe_largest_bucket from vllm.model_executor.layers.quantization.utils.flashinfer_utils import ( activation_to_flashinfer_type, ) @@ -97,11 +98,7 @@ def __init__( self.tp_size = moe_config.moe_parallel_config.tp_size self.out_dtype = moe_config.in_dtype self.use_dp = moe_config.moe_parallel_config.dp_size > 1 - # Upper bound on input.size(0) seen by the kernel. With DP the MoE - # input can be gathered across DP ranks before the experts run. - self._max_workspace_rows = moe_config.max_num_tokens * max( - 1, moe_config.moe_parallel_config.dp_size - ) + self._max_workspace_rows = fi_moe_largest_bucket(moe_config) self._workspace_nbytes: dict[tuple, int] = {} # Enables DeepSeek-style FP8 block-scale path: # - pass per-block weight scales to the kernel From 0dad84737f74bf686bbcf750c24927122c487289 Mon Sep 17 00:00:00 2001 From: jbernloehr Date: Tue, 27 Oct 2026 09:14:40 +0100 Subject: [PATCH 3/4] Use framework workspace2 for FlashInfer CUTLASS MoE scratch Co-authored-by: Codex Signed-off-by: jbernloehr --- tests/kernels/moe/test_flashinfer_moe.py | 101 +++++--- .../experts/flashinfer_cutlass_moe.py | 215 +++++++----------- 2 files changed, 154 insertions(+), 162 deletions(-) diff --git a/tests/kernels/moe/test_flashinfer_moe.py b/tests/kernels/moe/test_flashinfer_moe.py index fd2af030e8df..ea72934cf9ac 100644 --- a/tests/kernels/moe/test_flashinfer_moe.py +++ b/tests/kernels/moe/test_flashinfer_moe.py @@ -29,6 +29,9 @@ is_valid_flashinfer_cutlass_fused_moe, ) from vllm.model_executor.layers.fused_moe.modular_kernel import FusedMoEKernel +from vllm.model_executor.layers.fused_moe.prepare_finalize.no_dp_ep import ( + MoEPrepareAndFinalizeNoDPEPModular, +) from vllm.model_executor.layers.quantization.utils.flashinfer_utils import ( activation_to_flashinfer_type, ) @@ -70,6 +73,7 @@ [(32, 1, None, 8192), (32, 2, None, 8192), (4096, 2, 4, 16384)], ) @pytest.mark.parametrize("activation", [MoEActivation.SILU, MoEActivation.RELU2_NO_MUL]) +@pytest.mark.parametrize("quant_dtype", [None, "nvfp4"]) @torch.inference_mode() def test_flashinfer_workspace_reused_after_lock( max_num_tokens, @@ -77,10 +81,11 @@ def test_flashinfer_workspace_reused_after_lock( elastic_ep_max_dp_size, workspace_rows, activation, + quant_dtype, workspace_init, monkeypatch, ): - """Locked reuse must cover gathered inputs, autotuning and elastic DP.""" + """Framework scratch must survive locking and graph replay without aliasing.""" parallel = FusedMoEParallelConfig.make_no_parallel() parallel.dp_size = dp_size config = FusedMoEConfig( @@ -98,7 +103,6 @@ def test_flashinfer_workspace_reused_after_lock( max_num_tokens=max_num_tokens, elastic_ep_max_dp_size=elastic_ep_max_dp_size, ) - layers = [FlashInferExperts(config, FusedMoEQuantConfig.make()) for _ in range(2)] max_rows = max_num_tokens * dp_size x = torch.randn(max_rows, 256, device="cuda", dtype=torch.bfloat16) / 10 w1 = ( @@ -112,6 +116,25 @@ def test_flashinfer_workspace_reused_after_lock( / 10 ) w2 = torch.randn(8, 256, 512, device="cuda", dtype=torch.bfloat16) / 10 + quant_config = FusedMoEQuantConfig.make() + if quant_dtype is not None: + w1, w2, quant_config = make_test_quant_config( + 8, + 512, + 256, + in_dtype=x.dtype, + quant_dtype=quant_dtype, + block_shape=None, + per_act_token_quant=False, + make_gate=activation.is_gated, + ) + layers = [ + FusedMoEKernel( + MoEPrepareAndFinalizeNoDPEPModular(), + FlashInferExperts(config, quant_config), + ) + for _ in range(2) + ] ids = torch.tensor([0, 1], device="cuda").expand(max_rows, 2) weights = torch.full((max_rows, 2), 0.5, device="cuda") expected_nbytes = fi_moe.flashinfer_cutlass_fused_moe_workspace_size( @@ -120,30 +143,35 @@ def test_flashinfer_workspace_reused_after_lock( 512, 8, 2, - x_dtype=x.dtype, - weight_dtype=w1.dtype, + x_dtype=torch.uint8 if quant_dtype == "nvfp4" else x.dtype, + weight_dtype=torch.long if quant_dtype == "nvfp4" else w1.dtype, output_dtype=x.dtype, activation_type=activation_to_flashinfer_type(activation), device=x.device, ) buffers = [] + call_args: dict = {} kernel = fi_moe.flashinfer_cutlass_fused_moe - def compare_with_unbuffered(**kwargs): - # Assert that the new path really ran, then compare the same kernel - # with and without caller-owned scratch. - buffers.append(kwargs["workspace_buffer"]) - assert buffers[-1].nbytes >= expected_nbytes - result = kernel(**kwargs) - reference = torch.empty_like(kwargs["output"]) - kernel(**{**kwargs, "workspace_buffer": None, "output": reference}) - torch.testing.assert_close(kwargs["output"], reference) - return result - - monkeypatch.setattr(fi_moe, "flashinfer_cutlass_fused_moe", compare_with_unbuffered) - for layer, rows in [(layers[0], 1), (layers[1], max_rows), (layers[0], 16)]: - layer.apply( - output=torch.empty_like(x[:rows]), + def record_workspace(**kwargs): + call_args.clear() + call_args.update(kwargs) + scratch = kwargs["workspace_buffer"] + output = kwargs["output"] + buffers.append(scratch) + assert scratch.dtype == torch.uint8 and scratch.ndim == 1 + assert scratch.nbytes >= expected_nbytes + # The common workspace reserves the output before workspace2, even + # when prepare/finalize supplies an external output allocation. + assert scratch.storage_offset() >= output.nbytes + assert ( + scratch.data_ptr() + scratch.nbytes <= output.data_ptr() + or output.data_ptr() + output.nbytes <= scratch.data_ptr() + ) + return kernel(**kwargs) + + def run(layer, rows): + return layer.apply( hidden_states=x[:rows], w1=w1, w2=w2, @@ -152,15 +180,36 @@ def compare_with_unbuffered(**kwargs): activation=activation, global_num_experts=8, expert_map=None, - a1q_scale=None, - a2_scale=None, - workspace13=None, - workspace2=None, - expert_tokens_meta=None, apply_router_weight_on_input=False, ) - current_workspace_manager().lock() - assert all(buffer is buffers[0] for buffer in buffers) + + def check_reference(output): + reference = torch.empty_like(output) + kernel(**{**call_args, "workspace_buffer": None, "output": reference}) + torch.testing.assert_close(output, reference) + + monkeypatch.setattr(fi_moe, "flashinfer_cutlass_fused_moe", record_workspace) + with set_current_vllm_config(VllmConfig()): + check_reference(run(layers[0], max_rows)) + manager = current_workspace_manager() + manager.lock() + storage_ptr = manager.get_simultaneous(((1,), torch.uint8))[0].data_ptr() + for layer, rows in [(layers[1], 1), (layers[0], 17), (layers[1], max_rows)]: + check_reference(run(layer, rows)) + + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + run(layers[0], 16) + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + output = run(layers[0], 16) + for _ in range(2): + x[:16].normal_(std=0.1) + graph.replay() + check_reference(output) + assert all(b.untyped_storage().data_ptr() == storage_ptr for b in buffers) @pytest.mark.parametrize( diff --git a/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py b/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py index 8f8952cb0aa1..97df786f67fc 100644 --- a/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py +++ b/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py @@ -34,10 +34,7 @@ has_flashinfer_cutlass_fused_moe, has_flashinfer_cutlass_fused_moe_workspace, ) -from vllm.v1.worker.workspace import ( - current_workspace_manager, - is_workspace_manager_initialized, -) +from vllm.utils.math_utils import cdiv logger = init_logger(__name__) @@ -225,135 +222,90 @@ def workspace_shapes( expert_tokens_meta: mk.ExpertTokensMetadata | None, activation: MoEActivation, ) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]: - # We use global_num_experts due to how moe_align_block_size handles - # expert_maps. - """Compute the shapes for the temporary and final outputs of the two gemms - and activation in the fused expert function. Since the gemms are - independent, the workspace for the first gemm can be shared with the - workspace for the last gemm. - - Returns a tuple of: - - workspace13 shape tuple: must be large enough to hold the - result of either expert gemm. - - workspace2 shape tuple: must be large enough to hold the - result of the activation function. - - output shape tuple: must be exact size of the final gemm output. - - Workspace type: The dtype to use for the workspace tensors. - - Note: in order for activation chunking to work, the first dimension - of each tuple must be the number of tokens. - """ - workspace1 = (M, K) - workspace2 = (0,) - # For NVFP4, the output is stored in a packed int8 format, - # so the actual hidden dim is 2x the size of K here. - output_shape = (M, K * 2 if self.quant_dtype == "nvfp4" else K) - # The workspace is determined by `aq`, since it comes after any - # potential communication op and is involved in the expert computation. - return (workspace1, workspace2, output_shape) - - def _get_workspace_buffer( + # K is packed for NVFP4 activations; N is always the logical fc1 width. + hidden_size = K * 2 if self.quant_dtype == "nvfp4" else K + output_shape = (M, hidden_size) + workspace2: tuple[int, ...] = (0,) + if M and has_flashinfer_cutlass_fused_moe_workspace(): + nbytes = self._workspace_size_bytes( + max(M, self._max_workspace_rows), + hidden_size, + self.adjust_N_for_activation(N, activation), + local_num_experts * self.ep_size, + topk, + activation, + ) + workspace2 = (M, cdiv(nbytes, M * self.out_dtype.itemsize)) + # workspace13 aliases the output, which must not overlap CUTLASS scratch. + return (0,), workspace2, output_shape + + def _workspace_size_bytes( self, - hidden_states: torch.Tensor, - fc1_expert_weights: torch.Tensor, - fc2_expert_weights: torch.Tensor, + rows: int, + hidden_size: int, + inter_size: int, + num_experts_total: int, top_k: int, activation: MoEActivation, - use_mxfp8_act_scaling: bool, - use_w4_group_scaling: bool, - ) -> torch.Tensor | None: - """Return a persistent FlashInfer CUTLASS MoE workspace, or None. - - Without a caller-owned workspace, FlashInfer allocates and frees its - GEMM scratch (about 20 GiB for 16k tokens with DP=8) through the - PyTorch caching allocator on every MoE layer call, which fragments the - allocator during large prefills. Size one buffer for the largest batch - once, during memory profiling, and share it across all MoE layers that - run sequentially in the current ubatch and lane. - """ - if ( - not has_flashinfer_cutlass_fused_moe_workspace() - or not is_workspace_manager_initialized() - # Unexpectedly large batches keep the per-call allocation rather - # than pinning one more persistent buffer per distinct size. - or hidden_states.size(0) > self._max_workspace_rows - ): - return None - - # Always size for the maximum so every call shares a single buffer. - rows = self._max_workspace_rows - hidden_size = fc2_expert_weights.size(1) - # fc1 rows are logical (unpacked): inter_size, times 2 if gated. - inter_size = fc1_expert_weights.size(1) // (2 if activation.is_gated else 1) - num_experts_total = fc2_expert_weights.size(0) * self.ep_size - size_key = ( - rows, - hidden_size, - inter_size, - num_experts_total, - top_k, - hidden_states.dtype, - fc1_expert_weights.dtype, - activation, - use_mxfp8_act_scaling, - use_w4_group_scaling, + ) -> int: + size_key = (rows, hidden_size, inter_size, num_experts_total, top_k, activation) + if size_key in self._workspace_nbytes: + return self._workspace_nbytes[size_key] + + x_dtype = self.quant_dtype + if self.expects_unquantized_inputs or x_dtype is None: + x_dtype = self.out_dtype + elif x_dtype == "nvfp4": + x_dtype = torch.uint8 + elif x_dtype == "mxfp8": + x_dtype = torch.float8_e4m3fn + + use_mxfp8_act_scaling = ( + self.weight_quant_dtype == "mxfp4" and self.quant_dtype == "mxfp8" ) - nbytes = self._workspace_nbytes.get(size_key) - if nbytes is None: - try: - nbytes = int( - flashinfer_cutlass_fused_moe_workspace_size( - rows, - hidden_size, - inter_size, - num_experts_total, - top_k, - x_dtype=hidden_states.dtype, - weight_dtype=fc1_expert_weights.dtype, - output_dtype=self.out_dtype, - activation_type=activation_to_flashinfer_type(activation), - tp_size=self.tp_size, - tp_rank=self.tp_rank, - ep_size=self.ep_size, - ep_rank=self.ep_rank, - use_deepseek_fp8_block_scale=self.use_deepseek_fp8_block_scale, - use_w4_group_scaling=use_w4_group_scaling, - use_mxfp8_act_scaling=use_mxfp8_act_scaling, - device=hidden_states.device, - ) - ) - except (RuntimeError, ValueError) as e: - logger.warning_once( - "FlashInfer CUTLASS MoE workspace sizing failed (%s); " - "falling back to per-call workspace allocation.", - e, - ) - nbytes = 0 - self._workspace_nbytes[size_key] = nbytes - if nbytes <= 0: - return None - - device = hidden_states.device - key = ("flashinfer_cutlass_fused_moe_workspace", device, nbytes) - - def _allocate() -> torch.Tensor: - logger.info_once( - "Reserving a persistent %.2f GiB FlashInfer CUTLASS MoE " - "workspace for up to %d tokens.", - nbytes / (1 << 30), - rows, - ) - return torch.empty((nbytes,), dtype=torch.uint8, device=device) + use_w4_group_scaling = ( + self.weight_quant_dtype == "mxfp4" and not use_mxfp8_act_scaling + ) + weight_dtype = self.weight_quant_dtype + if self.quant_dtype == "nvfp4" or use_mxfp8_act_scaling: + # Match the packed weight views passed to FlashInfer in apply(). + weight_dtype = torch.long + elif use_w4_group_scaling: + weight_dtype = torch.uint8 + elif weight_dtype is None: + weight_dtype = self.out_dtype try: - return current_workspace_manager().get_persistent_resource(key, _allocate) - except AssertionError: - # The workspace is locked and this size was not reserved in warmup. + nbytes = int( + flashinfer_cutlass_fused_moe_workspace_size( + rows, + hidden_size, + inter_size, + num_experts_total, + top_k, + x_dtype=x_dtype, + weight_dtype=weight_dtype, + output_dtype=self.out_dtype, + activation_type=activation_to_flashinfer_type(activation), + tp_size=self.tp_size, + tp_rank=self.tp_rank, + ep_size=self.ep_size, + ep_rank=self.ep_rank, + use_deepseek_fp8_block_scale=self.use_deepseek_fp8_block_scale, + use_w4_group_scaling=use_w4_group_scaling, + use_mxfp8_act_scaling=use_mxfp8_act_scaling, + device=self.device, + ) + ) + except (RuntimeError, ValueError) as e: logger.warning_once( - "FlashInfer CUTLASS MoE workspace of %d bytes was not reserved " - "during warmup; falling back to per-call allocation.", - nbytes, + "FlashInfer CUTLASS MoE workspace sizing failed (%s); " + "falling back to per-call workspace allocation.", + e, ) - return None + nbytes = 0 + self._workspace_nbytes[size_key] = nbytes + return nbytes def apply( self, @@ -476,17 +428,8 @@ def apply( fc2_expert_weights = w2 workspace_kwargs = {} - workspace = self._get_workspace_buffer( - hidden_states, - fc1_expert_weights, - fc2_expert_weights, - topk_ids.size(1), - activation, - use_mxfp8_act_scaling, - use_w4_group_scaling, - ) - if workspace is not None: - workspace_kwargs["workspace_buffer"] = workspace + if workspace2 is not None and workspace2.numel(): + workspace_kwargs["workspace_buffer"] = workspace2.view(torch.uint8).view(-1) _ = flashinfer_cutlass_fused_moe( input=hidden_states, From a1f591ea49623729f70293c76f9cfcc5c91d6339 Mon Sep 17 00:00:00 2001 From: Jan Bernloehr Date: Sat, 14 Nov 2026 23:37:46 +0100 Subject: [PATCH 4/4] Fix CUTLASS workspace docstring Markdown Co-authored-by: Codex Signed-off-by: Jan Bernloehr --- vllm/utils/flashinfer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vllm/utils/flashinfer.py b/vllm/utils/flashinfer.py index c4468ed3893a..2403f65f4e3a 100644 --- a/vllm/utils/flashinfer.py +++ b/vllm/utils/flashinfer.py @@ -654,8 +654,8 @@ def has_flashinfer_cutlass_fused_moe() -> bool: @functools.cache def has_flashinfer_cutlass_fused_moe_workspace() -> bool: """Return `True` if FlashInfer CUTLASS fused MoE accepts a caller-owned - workspace buffer (``workspace_buffer=`` plus - ``cutlass_fused_moe_workspace_size``).""" + workspace buffer (`workspace_buffer=` plus + `cutlass_fused_moe_workspace_size`).""" if not has_flashinfer_cutlass_fused_moe(): return False mod = _get_submodule("flashinfer.fused_moe")