Repository navigation
feat(vibecuda_moe): add VibeCUDA AlphaMoE fused router #4780
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
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| """Benchmark the VibeCUDA AlphaMoE router against FlashInfer main. | ||
|
|
||
| The optimized CAKE baseline is still under review in PR #4339. Its separately | ||
| verified result is reported in the pull request description; this benchmark | ||
| does not vendor or compile unpublished reference code. | ||
| """ | ||
|
|
||
| import functools | ||
| from dataclasses import dataclass | ||
|
|
||
| import numpy as np | ||
| import torch | ||
|
|
||
| from flashinfer.fused_moe import allocate_alphamoe_route_plan, alphamoe_fused_router | ||
| from flashinfer.testing import bench_gpu_time | ||
| from flashinfer.trace.templates.moe import _alphamoe_fused_router_reference | ||
|
|
||
| DRY_RUN_ITERS = 5 | ||
| REPEAT_ITERS = 10 | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class RouterConfig: | ||
| name: str | ||
| num_tokens: int | ||
| num_experts: int | ||
| top_k: int | ||
| block_m: int | ||
| has_shared_expert: bool | ||
|
|
||
|
|
||
| CONFIGS = ( | ||
| RouterConfig("single-1tok-e512-shared", 1, 512, 2, 16, True), | ||
| RouterConfig("decode-8tok-e257-shared", 8, 257, 9, 8, True), | ||
| RouterConfig("batch-32tok-e512", 32, 512, 8, 16, False), | ||
| RouterConfig("batch-128tok-e512", 128, 512, 8, 16, False), | ||
| ) | ||
|
|
||
|
|
||
| def _make_logits(cfg: RouterConfig, case_index: int) -> torch.Tensor: | ||
| generator = torch.Generator(device="cuda").manual_seed(29001 + case_index) | ||
| return torch.randn( | ||
| cfg.num_tokens, | ||
| cfg.num_experts, | ||
| generator=generator, | ||
| device="cuda", | ||
| dtype=torch.float32, | ||
| ) | ||
|
|
||
|
|
||
| def _timed_us(fn, args: tuple) -> float: | ||
| samples = bench_gpu_time( | ||
| fn, | ||
| input_args=args, | ||
| enable_cupti=True, | ||
| dry_run_iters=DRY_RUN_ITERS, | ||
| repeat_iters=REPEAT_ITERS, | ||
| cold_l2_cache=True, | ||
| use_cuda_graph=False, | ||
| ) | ||
| return float(np.median(samples)) * 1e3 | ||
|
|
||
|
|
||
| def _assert_matches_reference( | ||
| cfg: RouterConfig, candidate: tuple[torch.Tensor, ...], reference: tuple | ||
| ) -> None: | ||
| torch.testing.assert_close(candidate[0], reference[0], rtol=1e-5, atol=1e-7) | ||
| for index in (1, 3, 4, 5, 6, 7): | ||
| torch.testing.assert_close(candidate[index], reference[index]) | ||
|
|
||
| # Scatter order within one expert is intentionally unspecified. Compare | ||
| # routed token ids as multisets and require every padding slot to be the | ||
| # documented sentinel. | ||
| sorted_ids = candidate[2] | ||
| ref_sorted_ids = reference[2] | ||
| counts = candidate[5].tolist() | ||
| offsets = candidate[6].tolist() | ||
| sentinel = cfg.num_tokens * cfg.top_k | ||
| for expert, count in enumerate(counts): | ||
| begin, end = offsets[expert], offsets[expert + 1] | ||
| got, _ = torch.sort(sorted_ids[begin : begin + count]) | ||
| want, _ = torch.sort(ref_sorted_ids[begin : begin + count]) | ||
| torch.testing.assert_close(got, want) | ||
| padding = sorted_ids[begin + count : end] | ||
| if padding.numel() and not bool((padding == sentinel).all()): | ||
| raise AssertionError(f"expert {expert}: non-sentinel padding") | ||
|
|
||
|
|
||
| def _bench_one(cfg: RouterConfig, case_index: int) -> float: | ||
| logits = _make_logits(cfg, case_index) | ||
| kwargs = { | ||
| "top_k": cfg.top_k, | ||
| "block_m": cfg.block_m, | ||
| "has_shared_expert": cfg.has_shared_expert, | ||
| } | ||
| reference = _alphamoe_fused_router_reference(logits, **kwargs) | ||
| candidate = alphamoe_fused_router(logits, backend="vibecuda", **kwargs) | ||
| _assert_matches_reference(cfg, candidate, reference) | ||
|
|
||
| plan = allocate_alphamoe_route_plan(logits, **kwargs) | ||
| planned_candidate = alphamoe_fused_router(logits, plan=plan, backend="vibecuda") | ||
| _assert_matches_reference(cfg, planned_candidate, reference) | ||
| torch.cuda.synchronize() | ||
|
|
||
| candidate_fn = functools.partial( | ||
| alphamoe_fused_router, plan=plan, backend="vibecuda" | ||
| ) | ||
| reference_fn = functools.partial(_alphamoe_fused_router_reference, **kwargs) | ||
| candidate_us = _timed_us(candidate_fn, (logits,)) | ||
| reference_us = _timed_us(reference_fn, (logits,)) | ||
| speedup = reference_us / candidate_us | ||
| print( | ||
| f"{cfg.name:28s} reference {reference_us:10.2f} us " | ||
| f"vibecuda {candidate_us:8.2f} us {speedup:8.2f}x" | ||
| ) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win Report direct and planned timings separately.
🤖 Prompt for AI Agents |
||
| return speedup | ||
|
|
||
|
|
||
| def main() -> None: | ||
| if not torch.cuda.is_available(): | ||
| raise RuntimeError("CUDA device required") | ||
| capability = torch.cuda.get_device_capability() | ||
| if capability not in {(10, 0), (10, 3)}: | ||
| raise RuntimeError(f"CC 10.0 or 10.3 required, got {capability}") | ||
|
|
||
| print( | ||
| "CUPTI, cold L2, eager replay, " | ||
| f"dry_run={DRY_RUN_ITERS}, repeats={REPEAT_ITERS}" | ||
| ) | ||
| speedups = np.asarray( | ||
| [_bench_one(config, index) for index, config in enumerate(CONFIGS)] | ||
| ) | ||
| print(f"arithmetic mean: {float(speedups.mean()):.4f}x") | ||
| print(f"geometric mean: {float(np.exp(np.log(speedups).mean())):.4f}x") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| /* | ||
| * 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. | ||
| */ | ||
| #include <cstdint> | ||
|
|
||
| #include "flashinfer/fused_moe/alphamoe_router.cuh" | ||
| #include "tvm_ffi_utils.h" | ||
|
|
||
| namespace flashinfer::alphamoe_router { | ||
|
|
||
| using tvm::ffi::TensorView; | ||
|
|
||
| /*! | ||
| * \brief TVM-FFI entry point for the fused AlphaMoE gating router. | ||
| * | ||
| * router_logits : [num_tokens, num_experts] float32 (input) | ||
| * topk_weights : [num_tokens, top_k] float32 (output) | ||
| * topk_ids : [num_tokens, top_k] int32 (output) | ||
| * sorted_token_ids : [max_blocks * block_m] int32 (output) | ||
| * expert_ids : [max_blocks] int32 (output) | ||
| * num_tokens_post_padded : [1] int32 (output) | ||
| * expert_counts : [num_experts] int32 (output) | ||
| * expert_offsets : [num_experts + 1] int32 (output) | ||
| * expert_scatter_offsets : [num_experts] int32 (output) | ||
| * scratch : [see alphamoe_router_scratch_ints] int32 (workspace) | ||
| * | ||
| * (top_k, block_m, has_shared_expert) come in as scalars; every output shape | ||
| * is derived from them and the input shape, so the launch is fixed under CUDA | ||
| * graph capture and no host synchronization happens anywhere on this path. | ||
| */ | ||
| void AlphaMoeFusedRouter(TensorView router_logits, TensorView topk_weights, | ||
| TensorView topk_ids, TensorView sorted_token_ids, | ||
| TensorView expert_ids, | ||
| TensorView num_tokens_post_padded, | ||
| TensorView expert_counts, TensorView expert_offsets, | ||
| TensorView expert_scatter_offsets, TensorView scratch, | ||
| int64_t top_k, int64_t block_m, | ||
| bool has_shared_expert) { | ||
| CHECK_INPUT_AND_TYPE(router_logits, dl_float32); | ||
| CHECK_INPUT_AND_TYPE(topk_weights, dl_float32); | ||
| CHECK_INPUT_AND_TYPE(topk_ids, dl_int32); | ||
| CHECK_INPUT_AND_TYPE(sorted_token_ids, dl_int32); | ||
| CHECK_INPUT_AND_TYPE(expert_ids, dl_int32); | ||
| CHECK_INPUT_AND_TYPE(num_tokens_post_padded, dl_int32); | ||
| CHECK_INPUT_AND_TYPE(expert_counts, dl_int32); | ||
| CHECK_INPUT_AND_TYPE(expert_offsets, dl_int32); | ||
| CHECK_INPUT_AND_TYPE(expert_scatter_offsets, dl_int32); | ||
| CHECK_INPUT_AND_TYPE(scratch, dl_int32); | ||
|
|
||
| CHECK_DEVICE(topk_weights, router_logits); | ||
| CHECK_DEVICE(topk_ids, router_logits); | ||
| CHECK_DEVICE(sorted_token_ids, router_logits); | ||
| CHECK_DEVICE(expert_ids, router_logits); | ||
| CHECK_DEVICE(num_tokens_post_padded, router_logits); | ||
| CHECK_DEVICE(expert_counts, router_logits); | ||
| CHECK_DEVICE(expert_offsets, router_logits); | ||
| CHECK_DEVICE(expert_scatter_offsets, router_logits); | ||
| CHECK_DEVICE(scratch, router_logits); | ||
|
|
||
| CHECK_DIM(2, router_logits); | ||
| CHECK_DIM(2, topk_weights); | ||
| CHECK_DIM(2, topk_ids); | ||
| CHECK_DIM(1, sorted_token_ids); | ||
| CHECK_DIM(1, expert_ids); | ||
| CHECK_DIM(1, num_tokens_post_padded); | ||
| CHECK_DIM(1, expert_counts); | ||
| CHECK_DIM(1, expert_offsets); | ||
| CHECK_DIM(1, expert_scatter_offsets); | ||
| CHECK_DIM(1, scratch); | ||
|
|
||
| const int64_t num_tokens = router_logits.sizes()[0]; | ||
| const int64_t num_experts = router_logits.sizes()[1]; | ||
|
|
||
| const auto params = flashinfer::fused_moe::make_alphamoe_router_params( | ||
| static_cast<int>(num_tokens), static_cast<int>(num_experts), | ||
| static_cast<int>(top_k), static_cast<int>(block_m), | ||
| has_shared_expert ? 1 : 0); | ||
|
|
||
| TVM_FFI_ICHECK(topk_weights.sizes()[0] == num_tokens && | ||
| topk_weights.sizes()[1] == top_k && | ||
| topk_ids.sizes()[0] == num_tokens && | ||
| topk_ids.sizes()[1] == top_k) | ||
| << "topk outputs must be [num_tokens, top_k]"; | ||
| TVM_FFI_ICHECK(expert_counts.numel() == num_experts && | ||
| expert_scatter_offsets.numel() == num_experts) | ||
| << "expert counts/scatter offsets must be [num_experts]"; | ||
| TVM_FFI_ICHECK(expert_offsets.numel() == num_experts + 1) | ||
| << "expert_offsets must be [num_experts + 1]"; | ||
| TVM_FFI_ICHECK(num_tokens_post_padded.numel() == 1) | ||
| << "num_tokens_post_padded must be [1]"; | ||
| TVM_FFI_ICHECK(sorted_token_ids.numel() == params.slots) | ||
| << "sorted_token_ids must be [max_blocks * block_m] = " << params.slots; | ||
| TVM_FFI_ICHECK(expert_ids.numel() == params.max_blocks) | ||
| << "expert_ids must be [max_blocks] = " << params.max_blocks; | ||
| TVM_FFI_ICHECK(scratch.numel() >= | ||
| flashinfer::fused_moe::alphamoe_router_scratch_ints(params)) | ||
| << "scratch too small for the generic path"; | ||
|
|
||
| auto stream = get_stream(router_logits.device()); | ||
|
|
||
| flashinfer::fused_moe::alphamoe_router_forward( | ||
| params, static_cast<const float*>(router_logits.data_ptr()), | ||
| static_cast<float*>(topk_weights.data_ptr()), | ||
| static_cast<int32_t*>(topk_ids.data_ptr()), | ||
| static_cast<int32_t*>(expert_counts.data_ptr()), | ||
| static_cast<int32_t*>(expert_offsets.data_ptr()), | ||
| static_cast<int32_t*>(expert_scatter_offsets.data_ptr()), | ||
| static_cast<int32_t*>(num_tokens_post_padded.data_ptr()), | ||
| static_cast<int32_t*>(expert_ids.data_ptr()), | ||
| static_cast<int32_t*>(sorted_token_ids.data_ptr()), | ||
| static_cast<int32_t*>(scratch.data_ptr()), stream); | ||
| } | ||
|
|
||
| } // namespace flashinfer::alphamoe_router |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| /* | ||
| * 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. | ||
| */ | ||
| #include "tvm_ffi_utils.h" | ||
|
|
||
| namespace flashinfer::alphamoe_router { | ||
| using tvm::ffi::TensorView; | ||
| void AlphaMoeFusedRouter(TensorView router_logits, TensorView topk_weights, | ||
| TensorView topk_ids, TensorView sorted_token_ids, | ||
| TensorView expert_ids, | ||
| TensorView num_tokens_post_padded, | ||
| TensorView expert_counts, TensorView expert_offsets, | ||
| TensorView expert_scatter_offsets, TensorView scratch, | ||
| int64_t top_k, int64_t block_m, | ||
| bool has_shared_expert); | ||
| } // namespace flashinfer::alphamoe_router | ||
|
|
||
| TVM_FFI_DLL_EXPORT_TYPED_FUNC(alphamoe_fused_router, | ||
| flashinfer::alphamoe_router::AlphaMoeFusedRouter); |
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 | 🟡 Minor | ⚡ Quick win
Validate trailing
sorted_token_idscapacity.The check validates only entries inside expert segments. It does not validate
sorted_ids[offsets[-1]:], which must be zero by the router contract. For example, thedecode-8tok-e257-sharedconfiguration has unused capacity after its padded expert segments. A nonzero value in that region passes this validation.Proposed fix
for expert, count in enumerate(counts): begin, end = offsets[expert], offsets[expert + 1] got, _ = torch.sort(sorted_ids[begin : begin + count]) want, _ = torch.sort(ref_sorted_ids[begin : begin + count]) torch.testing.assert_close(got, want) padding = sorted_ids[begin + count : end] if padding.numel() and not bool((padding == sentinel).all()): raise AssertionError(f"expert {expert}: non-sentinel padding") + torch.testing.assert_close( + sorted_ids[offsets[-1] :], ref_sorted_ids[offsets[-1] :] + )📝 Committable suggestion
🤖 Prompt for AI Agents