Repository navigation
feat(moe): sync SM12x W4A16 fused MoE family to b12x HEAD #4255
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
73b4e8c
feat(moe): sync SM12x W4A16 fused MoE family to sparkinfer HEAD
yichengj0 f947957
docs(moe): tighten comments and docstrings in the W4A16 port
yichengj0 07c6d2e
fix(moe): address review findings in the W4A16 port
yichengj0 c717d62
perf(moe): cap W4A16 TC-decode at the direct-topk route bound
yichengj0 0d98f50
perf(moe): lower the W4A16 TC-decode cap to m=4
yichengj0 de9c0df
docs(moe): trim W4A16 comments and docstrings
yichengj0 32db1d2
docs(moe): cut the TC-decode cap comment to constant-site size
yichengj0 da1edde
perf(moe): compile the fused W4A16 kernel at O3
yichengj0 adb976a
fix(moe): tighten the W4A16 torch-op and route-pack contracts
yichengj0 f9afbf0
Merge branch 'main' into b12x-w4a16-moe-sync
bkryu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
82 changes: 82 additions & 0 deletions
82
flashinfer/fused_moe/cute_dsl/blackwell_sm12x/moe_w4a16_activations.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
110
flashinfer/fused_moe/cute_dsl/blackwell_sm12x/moe_w4a16_compiler.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| return compiled | ||
|
|
||
|
|
||
| def clear_compile_cache() -> None: | ||
| with _COMPILE_CACHE_LOCK: | ||
| _COMPILE_CACHE.clear() | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.There was a problem hiding this comment.
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 andclear_compile_cache()is test-only, the current simple locking approach is appropriate here. Withdrawing this finding.π
βοΈ Learnings added
You are interacting with an AI system.