Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/api/fused_moe.rst
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,17 @@ CUTLASS Fused MoE

cutlass_fused_moe

cuTile Fused MoE
----------------

.. autosummary::
:toctree: ../generated

CuTileBf16Config
CuTileBf16Runner
CuTileNvfp4Config
CuTileNvfp4Runner

TensorRT-LLM Fused MoE
----------------------

Expand Down
8 changes: 8 additions & 0 deletions flashinfer/fused_moe/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
CutlassConfig,
CutlassBf16Config,
CutlassW4A16Config,
CuTileBf16Config,
CuTileNvfp4Config,
ExecutionConfig,
ExpertConfig,
MoEActivationPack,
Expand All @@ -50,6 +52,8 @@
B12xW4A16Runner,
CutlassBf16Runner,
CutlassW4A16Runner,
CuTileBf16Runner,
CuTileNvfp4Runner,
CuteDslNvfp4Runner,
TrtllmBf16RoutedRunner,
TrtllmFp4RoutedRunner,
Expand Down Expand Up @@ -148,6 +152,10 @@
"B12xNvfp4Runner",
"CutlassBf16Runner",
"CutlassW4A16Runner",
"CuTileBf16Config",
"CuTileBf16Runner",
"CuTileNvfp4Config",
"CuTileNvfp4Runner",
"B12xW4A16Config",
"B12xW4A16Runner",
"BackendOptions",
Expand Down
92 changes: 92 additions & 0 deletions flashinfer/fused_moe/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,9 @@ def __repr__(self) -> str:
# W4A16 uses Hopper-specific mixed-input weight and scale layouts.
_CUTLASS_W4A16_ARCHS = (90,)

_CUTILE_BF16_ARCHS = (89, 90, 120, 121)
_CUTILE_NVFP4_ARCHS = (120, 121)


@dataclass(frozen=True)
class TrtllmFp4Config:
Expand Down Expand Up @@ -623,6 +626,91 @@ def __repr__(self) -> str:
return "CutlassBf16Config()"


@dataclass(frozen=True)
class CuTileBf16Config:
"""cuTile BF16 backend.

Expert parallelism and fused shared experts are not supported.
"""

@classmethod
def supported(cls, arch: int) -> bool:
return arch in _CUTILE_BF16_ARCHS

@staticmethod
def prepare_weights(
w1_bf16,
w2_bf16,
*,
num_local_experts: int,
hidden_size: int,
intermediate_size: int,
activation: ActivationConfig = ActivationConfig.swiglu,
device=None,
):
"""Build the ``cutile_bf16`` weight view from canonical BF16 weights."""
from .prepare import prepare_cutile_bf16_weights

return prepare_cutile_bf16_weights(
w1_bf16,
w2_bf16,
num_local_experts=num_local_experts,
hidden_size=hidden_size,
intermediate_size=intermediate_size,
activation_type=activation.type,
device=device,
)

def __repr__(self) -> str:
return "CuTileBf16Config()"


@dataclass(frozen=True)
class CuTileNvfp4Config:
"""cuTile NVFP4-weight x NVFP4-activation backend."""

@classmethod
def supported(cls, arch: int) -> bool:
return arch in _CUTILE_NVFP4_ARCHS

@staticmethod
def prepare_weights(
w1_fp4,
w1_block_scale,
w1_global_scale,
w2_fp4,
w2_block_scale,
w2_global_scale,
*,
num_local_experts: int,
hidden_size: int,
intermediate_size: int,
activation: ActivationConfig = ActivationConfig.swiglu,
source_format: str = "modelopt",
device=None,
):
"""Build the ``cutile_nvfp4`` view from checkpoint NVFP4 weights."""
from .prepare import prepare_cutile_nvfp4_weights

return prepare_cutile_nvfp4_weights(
w1_fp4,
w1_block_scale,
w1_global_scale,
w2_fp4,
w2_block_scale,
w2_global_scale,
num_local_experts=num_local_experts,
hidden_size=hidden_size,
intermediate_size=intermediate_size,
activation_type=activation.type,
source_format=source_format,
device=device,
)

def __repr__(self) -> str:
return "CuTileNvfp4Config()"


@dataclass(frozen=True)
class CutlassW4A16Config:
"""CUTLASS MXFP4-weight x BF16-activation backend for SM90.
Expand Down Expand Up @@ -798,6 +886,8 @@ def __repr__(self) -> str:
TrtllmMxInt4Config,
CutlassConfig,
CutlassBf16Config,
CuTileBf16Config,
CuTileNvfp4Config,
CutlassW4A16Config,
CuteDslConfig,
B12xNvfp4Config,
Expand All @@ -812,6 +902,8 @@ def __repr__(self) -> str:
TrtllmMxInt4Config,
CutlassConfig,
CutlassBf16Config,
CuTileBf16Config,
CuTileNvfp4Config,
CutlassW4A16Config,
CuteDslConfig,
B12xNvfp4Config,
Expand Down
15 changes: 15 additions & 0 deletions flashinfer/fused_moe/cutile/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright (c) 2026 by FlashInfer team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Internal cuTile kernels for the unified MoE API."""
144 changes: 144 additions & 0 deletions flashinfer/fused_moe/cutile/activation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
# Copyright (c) 2026 by FlashInfer team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Reusable cuTile activation kernels for fused MoE pipelines."""

from __future__ import annotations

from typing import TypeAlias

import cuda.tile as ct
import torch

from ...tllm_enums import ActivationType
from ...utils import next_positive_power_of_2

ConstInt: TypeAlias = ct.Constant[int]

_SWIGLU = int(ActivationType.Swiglu)
_RELU2 = int(ActivationType.Relu2)
SUPPORTED_ACTIVATIONS = (ActivationType.Swiglu, ActivationType.Relu2)


def _apply_activation(x, activation_type: ConstInt):
"""Apply activation math in FP32; ``activation_type`` is compile-time."""
if activation_type == _SWIGLU:
return x / (1.0 + ct.exp(-x))
elif activation_type == _RELU2:
relu = ct.maximum(x, 0.0)
return relu * relu
else:
# Unsupported codes are rejected by launch_activation before tracing.
return x


@ct.kernel
def _gated_activation(
X,
OUT,
activation_type: ConstInt,
I: ConstInt,
TILE_I: ConstInt,
NUM_TILES: ConstInt,
):
Comment thread
bkryu marked this conversation as resolved.
Resolved
row = ct.bid(0)
offsets = ct.bid(1) * TILE_I + ct.arange(TILE_I, dtype=ct.int32)
check_bounds = NUM_TILES * TILE_I != I
gate = ct.astype(
ct.gather(X, (row, offsets), check_bounds=check_bounds, latency=1),
ct.float32,
)
up = ct.astype(
ct.gather(X, (row, offsets + I), check_bounds=True, latency=1),
ct.float32,
)
result = _apply_activation(gate, activation_type) * up
ct.scatter(
OUT,
(row, offsets),
ct.astype(result, OUT.dtype),
check_bounds=check_bounds,
latency=1,
)


@ct.kernel
def _ungated_activation(
X,
OUT,
activation_type: ConstInt,
I: ConstInt,
TILE_I: ConstInt,
NUM_TILES: ConstInt,
):
row = ct.bid(0)
offsets = ct.bid(1) * TILE_I + ct.arange(TILE_I, dtype=ct.int32)
check_bounds = NUM_TILES * TILE_I != I
values = ct.astype(
ct.gather(X, (row, offsets), check_bounds=check_bounds, latency=1),
ct.float32,
)
result = _apply_activation(values, activation_type)
ct.scatter(
OUT,
(row, offsets),
ct.astype(result, OUT.dtype),
check_bounds=check_bounds,
latency=1,
)


def launch_activation(
x: torch.Tensor,
output: torch.Tensor,
activation_type: ActivationType,
) -> None:
"""Launch a gated or plain MoE activation into caller-owned storage."""
activation_type = ActivationType(activation_type)
if activation_type not in SUPPORTED_ACTIVATIONS:
raise NotImplementedError(
f"cuTile MoE does not support activation {activation_type!r}."
)
if x.ndim != 2 or output.ndim != 2 or x.shape[0] != output.shape[0]:
raise ValueError(
"cuTile MoE activation expects 2D input/output with matching rows."
)

intermediate_size = output.shape[1]
expected_input_size = intermediate_size * (2 if activation_type.is_gated else 1)
if x.shape[1] != expected_input_size:
raise ValueError(
f"cuTile MoE activation input width {x.shape[1]} != expected "
f"{expected_input_size} for {activation_type!r}."
)

tile_i = min(next_positive_power_of_2(intermediate_size), 1024)
num_tiles = (intermediate_size + tile_i - 1) // tile_i
kernel = _gated_activation if activation_type.is_gated else _ungated_activation
ct.launch(
torch.cuda.current_stream(x.device),
(x.shape[0], num_tiles),
kernel,
(
x,
output,
int(activation_type),
intermediate_size,
tile_i,
num_tiles,
),
)


__all__ = ["SUPPORTED_ACTIVATIONS", "launch_activation"]
Loading
Loading