Skip to content

Expose a fused_topk_raw_logits API#2682

Closed
zianglih wants to merge 1 commit intoflashinfer-ai:mainfrom
zianglih:agent-flashinfer-raw-logits-topk-api
Closed

Expose a fused_topk_raw_logits API#2682
zianglih wants to merge 1 commit intoflashinfer-ai:mainfrom
zianglih:agent-flashinfer-raw-logits-topk-api

Conversation

@zianglih
Copy link
Contributor

@zianglih zianglih commented Mar 4, 2026

📌 Description

Expose a raw logits topk api for existing code in trtllm fused moe.
Currently the implementation is not optimized and perf is wrose than a naive torch implementation here sgl-project/sglang@6ed9c53

🔍 Related Issues

#2676
sgl-project/sglang#19537

🚀 Pull Request Checklist

Thank you for contributing to FlashInfer! Before we review your pull request, please make sure the following items are complete.

✅ Pre-commit Checks

  • I have installed pre-commit by running pip install pre-commit (or used your preferred method).
  • I have installed the hooks with pre-commit install.
  • I have run the hooks manually with pre-commit run --all-files and fixed any reported issues.

If you are unsure about how to set up pre-commit, see the pre-commit documentation.

🧪 Tests

  • Tests have been added or updated as needed.
  • All tests are passing (unittest, etc.).

Reviewer Notes

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 4, 2026

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e3ed8be7-1f48-46a9-8b82-fe186fbcf253

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a specialized fused_topk_raw_logits API within FlashInfer's fused MoE utilities. The API is designed to efficiently compute top-k expert weights and IDs directly from raw gating logits, leveraging an existing TRTLLM kernel. While it provides a low-level interface for MoE routing, the initial performance is acknowledged to be less optimal than a basic PyTorch implementation, indicating a foundation for future optimization.

Highlights

  • New API Exposure: A new fused_topk_raw_logits API has been exposed for Mixture-of-Experts (MoE) routing.
  • TRTLLM Kernel Integration: This API utilizes the routingRenormalize kernel from TRTLLM for computing top-k scores and weights from raw routing logits.
  • Performance Note: The current implementation is noted to be unoptimized compared to a naive PyTorch equivalent, serving as a foundation for future improvements.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • csrc/moe_utils_binding.cu
    • Added a new FFI binding flashinfer_fused_topk_raw_logits_trtllm_renormalize for the TRTLLM routingRenormalize CUDA kernel.
  • flashinfer/fused_moe/init.py
    • Imported and exposed the new fused_topk_raw_logits function.
  • flashinfer/fused_moe/raw_logits_topk.py
    • Added a new Python module that defines the fused_topk_raw_logits API, including argument validation, dynamic workspace allocation, and the invocation of the C++ kernel.
  • flashinfer/jit/moe_utils.py
    • Included the trtllm_fused_moe_routing_renormalize.cu source file in the JIT compilation process for MoE utilities.
  • tests/utils/test_topk.py
    • Added new parameterized tests for fused_topk_raw_logits to compare its output against a PyTorch reference, specifically targeting SM100 and SM103 GPUs.
Activity
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request exposes a new fused_topk_raw_logits API which leverages the TRTLLM routingRenormalize kernel, including a new Python module, C++ bindings, JIT compilation updates, and tests. However, a critical thread-safety issue has been identified: a race condition in the management of the global workspace pool. This shared use of intermediate buffers across different threads and CUDA streams on the same device can lead to data corruption and information leakage between concurrent requests. My review includes a suggestion to address this race condition.

from flashinfer.utils import device_support_pdl

_ROUTING_TILE_TOKENS_DIM = 128
_workspace_pool: dict[tuple[str, int | None], "_RawLogitsTopkWorkspace"] = {}
Copy link
Contributor

Choose a reason for hiding this comment

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

security-high high

The _workspace_pool global dictionary and the _get_workspace function implement a shared workspace pool that is not thread-safe or stream-safe. The _RawLogitsTopkWorkspace instance is shared across all threads and CUDA streams using the same GPU device. This workspace contains pre-allocated tensors (e.g., topk_weights_bf16, topk_packed, expert_counts) used as intermediate buffers and outputs by the CUDA kernels. Concurrent calls to fused_topk_raw_logits from different threads or streams on the same device will result in multiple kernels writing to the same memory locations simultaneously. This leads to data corruption and potential information leakage between different requests or users in a multi-tenant environment (e.g., an LLM serving platform). To remediate this, consider making the workspace pool key include the CUDA stream ID, or using thread-local storage, or implementing a locking mechanism to ensure exclusive access to the workspace during kernel execution.

Comment on lines +112 to +118
def _get_workspace(device: torch.device) -> _RawLogitsTopkWorkspace:
key = (device.type, device.index)
ws = _workspace_pool.get(key)
if ws is None:
ws = _RawLogitsTopkWorkspace(device)
_workspace_pool[key] = ws
return ws
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The current implementation of _get_workspace is not thread-safe because it accesses the global _workspace_pool without synchronization. This can lead to a race condition where multiple threads create a workspace for the same device simultaneously, causing unpredictable behavior. To fix this, a lock should be used to protect the creation and insertion of new workspaces into the pool.

Suggested change
def _get_workspace(device: torch.device) -> _RawLogitsTopkWorkspace:
key = (device.type, device.index)
ws = _workspace_pool.get(key)
if ws is None:
ws = _RawLogitsTopkWorkspace(device)
_workspace_pool[key] = ws
return ws
def _get_workspace(device: torch.device) -> _RawLogitsTopkWorkspace:
if not hasattr(_get_workspace, "lock"):
import threading
_get_workspace.lock = threading.Lock()
key = (device.type, device.index)
ws = _workspace_pool.get(key)
if ws is not None:
return ws
with _get_workspace.lock:
ws = _workspace_pool.get(key)
if ws is None:
ws = _RawLogitsTopkWorkspace(device)
_workspace_pool[key] = ws
return ws

// - This function computes top-k scores/weights from raw routing logits (mPtrScores path).
// - mPtrTopKIds is intentionally left nullptr to force score-driven routing selection.
// - topk_packed_ptr is required by routing kernels for large-token paths.
void fused_topk_raw_logits_trtllm_renormalize(
Copy link
Collaborator

Choose a reason for hiding this comment

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

I have some concern about the API name, can we make it simpler? (and why do we call it fused?)

@ziang-and ziang-and force-pushed the agent-flashinfer-raw-logits-topk-api branch from 1a4e0de to b418e50 Compare March 5, 2026 23:03
@zianglih zianglih closed this Mar 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants