Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
_W4A16_ALLOWED_ROUTED_SIZES,
max_packed_route_slots,
packed_gemm_scratch_elements,
route_pack_numel_capacity,
unswizzle_block_scale,
validate_activation,
)
Expand Down Expand Up @@ -1932,6 +1933,7 @@ def _w4a16_workspace_geometry(
*,
routed_rows: int,
route_num_experts: int,
num_topk: int,
k: int,
n: int,
is_gated: bool,
Expand All @@ -1943,9 +1945,14 @@ def _w4a16_workspace_geometry(
fc2_c_tmp_elements = 1
fc1_cols = (2 if is_gated else 1) * int(n)
sms = get_num_sm(device)
# Size the route buffers for the power-of-2 capacity so route packing keeps
# a single triton specialization across token counts.
routed_rows_capacity = route_pack_numel_capacity(
int(routed_rows), topk=int(num_topk)
)
for block_size in _W4A16_ALLOWED_ROUTED_SIZES:
slots = max_packed_route_slots(
int(routed_rows),
routed_rows_capacity,
int(block_size),
int(route_num_experts),
)
Expand Down Expand Up @@ -2020,6 +2027,7 @@ def _allocate_sm120_w4a16_workspace(
) = _w4a16_workspace_geometry(
routed_rows=routed_rows,
route_num_experts=route_num_experts,
num_topk=num_topk,
k=k,
n=n,
is_gated=is_gated,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""Activation metadata for the SM12x W4A16 fused MoE path.

Only silu and relu2 are supported. The kernel code normalizes swiglu
parameters through the helpers here for every activation.
"""

from __future__ import annotations

import math


SWIGLUOAI_UNINTERLEAVE = "swigluoai_uninterleave"
SWIGLUOAI_DEFAULT_LIMIT = 7.0
SWIGLUOAI_DEFAULT_ALPHA = 1.702
SWIGLUOAI_DEFAULT_BETA = 1.0

SUPPORTED_MOE_ACTIVATIONS = frozenset({"silu", "relu2"})
GATED_MOE_ACTIVATIONS = frozenset({"silu"})


def normalize_moe_activation(activation: str) -> str:
activation = str(activation)
if activation not in SUPPORTED_MOE_ACTIVATIONS:
raise ValueError(f"unsupported activation {activation!r}")
return activation


def is_gated_moe_activation(activation: str) -> bool:
return normalize_moe_activation(activation) in GATED_MOE_ACTIVATIONS


def moe_activation_w1_rows(activation: str, n: int) -> int:
return (2 if is_gated_moe_activation(activation) else 1) * int(n)


def normalize_swiglu_limit_for_activation(
activation: str,
swiglu_limit: float | None,
) -> float | None:
activation = normalize_moe_activation(activation)
if swiglu_limit is None:
return SWIGLUOAI_DEFAULT_LIMIT if activation == SWIGLUOAI_UNINTERLEAVE else None
if activation not in GATED_MOE_ACTIVATIONS:
raise ValueError("swiglu_limit requires a gated MoE activation")
limit = float(swiglu_limit)
if not math.isfinite(limit) or limit <= 0.0:
raise ValueError(f"swiglu_limit must be positive and finite, got {limit}")
return limit


def normalize_swiglu_alpha_for_activation(
activation: str,
swiglu_alpha: float | None,
) -> float:
activation = normalize_moe_activation(activation)
if activation != SWIGLUOAI_UNINTERLEAVE:
if swiglu_alpha is not None and float(swiglu_alpha) != 1.0:
raise ValueError(
"swiglu_alpha is only configurable for swigluoai_uninterleave"
)
return 1.0
alpha = SWIGLUOAI_DEFAULT_ALPHA if swiglu_alpha is None else float(swiglu_alpha)
if not math.isfinite(alpha):
raise ValueError(f"swiglu_alpha must be finite, got {alpha}")
return alpha


def normalize_swiglu_beta_for_activation(
activation: str,
swiglu_beta: float | None,
) -> float:
activation = normalize_moe_activation(activation)
if activation != SWIGLUOAI_UNINTERLEAVE:
if swiglu_beta is not None and float(swiglu_beta) != 0.0:
raise ValueError(
"swiglu_beta is only configurable for swigluoai_uninterleave"
)
return 0.0
beta = SWIGLUOAI_DEFAULT_BETA if swiglu_beta is None else float(swiglu_beta)
if not math.isfinite(beta):
raise ValueError(f"swiglu_beta must be finite, got {beta}")
return beta
110 changes: 110 additions & 0 deletions flashinfer/fused_moe/cute_dsl/blackwell_sm12x/moe_w4a16_compiler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
"""In-memory compile cache for the SM12x W4A16 CuTe-DSL kernels."""

from __future__ import annotations

import json
from dataclasses import dataclass
from threading import RLock
from typing import Any


def _json_pod(value: Any, *, path: str = "value") -> Any:
"""Coerce a compile-spec fact into a JSON-stable plain value."""
if value is None or isinstance(value, (bool, int, float, str)):
return value
if isinstance(value, (list, tuple)):
return [_json_pod(v, path=f"{path}[{i}]") for i, v in enumerate(value)]
if isinstance(value, dict):
return {
str(k): _json_pod(v, path=f"{path}.{k}") for k, v in sorted(value.items())
}
raise TypeError(
f"compile spec fact {path} of type {type(value).__name__} is not a "
"JSON-stable plain value"
)


@dataclass(frozen=True)
class KernelCompileSpec:
kernel_id: str
version: int
json_key: str

@staticmethod
def from_facts(kernel_id: str, version: int, *facts: object) -> "KernelCompileSpec":
json_key = json.dumps(
[str(kernel_id), int(version), _json_pod(list(facts), path="facts")],
separators=(",", ":"),
)
return KernelCompileSpec(
kernel_id=str(kernel_id), version=int(version), json_key=json_key
)

@staticmethod
def from_key(
kernel_id: str,
version: int,
key: tuple[object, ...],
*,
labels: tuple[str, ...] | None = None,
) -> "KernelCompileSpec":
if labels is not None and len(labels) != len(key):
raise ValueError(
f"compile spec labels length {len(labels)} does not match "
f"key length {len(key)}"
)
facts: tuple[object, ...]
if labels is not None:
facts = tuple((str(labels[idx]), value) for idx, value in enumerate(key))
else:
facts = tuple(key)
return KernelCompileSpec.from_facts(kernel_id, version, *facts)


def _options_cache_key(options: Any) -> str:
"""Structural key for DSL compile options, whose default repr is
address-based."""
if options is None:
return "None"
state = vars(options) if hasattr(options, "__dict__") else options
return f"{type(options).__module__}.{type(options).__qualname__}:{state!r}"


_COMPILE_CACHE: dict[tuple[str, str], Any] = {}
_COMPILE_CACHE_LOCK = RLock()


def compile(
func: Any,
*args: Any,
compile_spec: KernelCompileSpec | None = None,
dsl_compile_options: Any = None,
**kwargs: Any,
) -> Any:
"""Memoizing wrapper over ``cute.compile``.

The compile spec fully identifies a kernel specialization, so it plus the
DSL compile options is a sufficient cache key.
"""
import cutlass.cute as cute

if compile_spec is None:
raise ValueError("compile() requires a compile_spec")
cache_key = (compile_spec.json_key, _options_cache_key(dsl_compile_options))
with _COMPILE_CACHE_LOCK:
compiled = _COMPILE_CACHE.get(cache_key)
if compiled is not None:
return compiled

compile_callable = cute.compile
if dsl_compile_options is not None:
compile_callable = compile_callable[dsl_compile_options]
compiled = compile_callable(func, *args, **kwargs)
with _COMPILE_CACHE_LOCK:
_COMPILE_CACHE[cache_key] = compiled
Comment on lines +94 to +104

@coderabbitai coderabbitai Bot Jul 31, 2026 •

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.

🎯 Functional Correctness | 🟠 Major | πŸ—οΈ Heavy lift

Make cache lookup, compilation, and invalidation atomic per key.

Line 94 releases the lock before compilation, so concurrent misses compile the same specialization repeatedly. More importantly, clear_compile_cache() can clear the cache while this work is in progress, then Line 103 repopulates it with a pre-clear result. Track in-flight compilations and a cache generation (or equivalent) so one caller compiles per key and pre-clear results cannot be inserted afterward.

πŸ€– Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@flashinfer/fused_moe/cute_dsl/blackwell_sm12x/moe_w4a16_compiler.py` around
lines 94 - 104, Update the compilation-cache flow around _COMPILE_CACHE and
clear_compile_cache() to serialize in-flight compilation per cache_key and track
cache generation across clears. Ensure concurrent misses for the same key share
one compilation, and only insert a compiled result when it belongs to the
current generation, so a pre-clear compilation cannot repopulate the cache after
invalidation.

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.

Compiling the same kernel twice gives the same result, so a concurrent miss only costs a wasted compile. clear_compile_cache() is a test helper. Keeping the simple lock.

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.

@yichengj0, understood. Given duplicate compilation is deterministic and clear_compile_cache() is test-only, the current simple locking approach is appropriate here. Withdrawing this finding.

πŸ‡


✏️ Learnings added
Learnt from: yichengj0
Repo: flashinfer-ai/flashinfer PR: 4255
File: flashinfer/fused_moe/cute_dsl/blackwell_sm12x/moe_w4a16_compiler.py:94-104
Timestamp: 2026-07-31T01:07:30.288Z
Learning: In `flashinfer/fused_moe/cute_dsl/blackwell_sm12x/moe_w4a16_compiler.py`, concurrent cache misses for the same SM12x W4A16 CuTe-DSL kernel specialization are intentionally allowed to compile redundantly because compilation is deterministic and the impact is only wasted compile work. `clear_compile_cache()` is a test helper, so cache-generation protection against in-flight pre-clear compilations is not required.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

return compiled


def clear_compile_cache() -> None:
with _COMPILE_CACHE_LOCK:
_COMPILE_CACHE.clear()
Loading
Loading