Skip to content
86 changes: 85 additions & 1 deletion tests/kernels/moe/test_flashinfer_moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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],
Expand Down
24 changes: 24 additions & 0 deletions tests/utils_/test_flashinfer_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fi_moe_largest_bucket was recommended here. See #62948 (comment)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

implemented

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)
Expand Down Expand Up @@ -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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does this workspace differ from the ones allocated by the MoE framework? (workspace1, workspace2). Is this new workspace buffer additional memory that is required or could it be overlapped with the existing workspaces?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah looks like cutlass may use workspace_shapes since it only implements FusedMoEExpertsModular?.

BTW, I noticed that cutlass declared the workspace13, but never used it in the apply(): https://github.com/janbernloehr/vllm/blob/630e30d8f7127731e75bfd71cb593fef55db2992/vllm/model_executor/layers/fused_moe/experts/flashinfer_cutlass_moe.py#L245

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in 0dad84737f: CUTLASS scratch now comes from the MoE framework’s workspace2, and the unused workspace13 shape is zero. Scratch remains separate from the output.

On the same pinned image with 8× B200, the unpatched control reproduced the 19.99 GiB OOM; both revised serving runs completed all 1,605 requests. All 174 GPU tests passed, including numerical correctness, locked workspace reuse, and CUDA graph replay.

Full GSM8K (1,319 questions, 5-shot): 93.40% stock → 93.03% workspace2, a −0.38 pp difference versus reported standard errors of about 0.7 pp per run. Both completed all requests with no empty responses, HTTP errors or OOMs. This single comparison cannot rule out a small accuracy regression. Full results are in the PR description.

— Drafted with Codex

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,
Expand Down Expand Up @@ -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),
Expand All @@ -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:
Expand Down
23 changes: 23 additions & 0 deletions vllm/utils/flashinfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import functools
import importlib
import importlib.util
import inspect
import os
import shutil
from collections.abc import Callable, Iterator
Expand Down Expand Up @@ -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"
)
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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",
Expand All @@ -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",
Expand Down
Loading