Skip to content

Conversation

@sufubao
Copy link
Collaborator

@sufubao sufubao commented Jan 22, 2026

No description provided.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @sufubao, 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 new capability, R3 (Rollout Router Replay), designed to capture the routing decisions made by Mixture of Experts (MoE) models during the inference process. This feature is particularly valuable for subsequent Reinforcement Learning (RL) post-training, allowing for the replay and analysis of how tokens were routed to specific experts. The implementation involves changes across the model's core components, memory management, and API interfaces to seamlessly integrate this data capture and expose it to users.

Highlights

  • R3 Feature Introduction: Introduced the R3 (Rollout Router Replay) feature, enabling the capture of Mixture of Experts (MoE) routing decisions during inference for use in RL post-training.
  • Configurable Data Capture: Added a server-side command-line argument --enable_return_routed_experts and a client-side request parameter return_routed_experts: true to activate the routing data capture.
  • Dedicated Routing Buffers: Implemented specialized GPU and CPU pinned buffers within the MemoryManager to efficiently store and manage expert routing indices across MoE layers and tokens.
  • API Integration: Extended the API request and response models to allow clients to request and receive base64-encoded routing data in the response metadata.
  • Model-Specific Adaptations: Updated various model-specific inference layers (e.g., DeepSeek2, Mixtral, Qwen3-MoE) to correctly pass and capture routing information during their forward passes.
  • Comprehensive Documentation and Testing: Included new documentation (docs/r3_routing_capture.md) detailing the feature's usage and provided new unit and client-side test cases to ensure correctness and demonstrate functionality.

🧠 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.

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 introduces the R3 feature, which enables capturing and replaying MoE routing decisions. The implementation is comprehensive, touching the base model, memory manager, specific model layers, and the API. The addition of documentation and tests is also a great contribution. My review focuses on ensuring the correctness and maintainability of this new feature. I've identified a critical bug in the Mixtral implementation that could cause runtime errors, along with a few medium-severity issues related to code duplication, configuration robustness, and documentation clarity. Overall, this is a solid feature addition with a few areas that need attention.

Comment on lines 31 to 38
routing_buffer = infer_state.mem_manager.routing_buffer
if (
routing_buffer is not None
and layer_weight.experts.tp_rank_ == 0
and layer_weight.experts.moe_layer_index is not None
and infer_state.mem_index is not None
):
routing_buffer[layer_weight.experts.moe_layer_index, infer_state.mem_index, :] = topk_ids.to(torch.int32)
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

There appears to be a bug in how the routing decisions are captured for Mixtral models:

  1. The code uses infer_state.mem_index to index the routing_buffer. However, routing_buffer is a temporary GPU buffer for the current batch, indexed from 0 to num_tokens - 1. mem_index contains global indices for the KV cache, which can be much larger than the routing_buffer's dimensions, likely leading to an out-of-bounds error. The indexing should be a slice, e.g., [:num_tokens], similar to other MoE implementations in this PR.
  2. The code converts topk_ids to torch.int32, but the routing_buffer is created with torch.int8 or torch.int16 to save memory. This type mismatch should be corrected by converting to routing_buffer.dtype.

This is a critical issue that will likely cause runtime errors.

Suggested change
routing_buffer = infer_state.mem_manager.routing_buffer
if (
routing_buffer is not None
and layer_weight.experts.tp_rank_ == 0
and layer_weight.experts.moe_layer_index is not None
and infer_state.mem_index is not None
):
routing_buffer[layer_weight.experts.moe_layer_index, infer_state.mem_index, :] = topk_ids.to(torch.int32)
routing_buffer = infer_state.mem_manager.routing_buffer
if (
routing_buffer is not None
and layer_weight.experts.tp_rank_ == 0
and layer_weight.experts.moe_layer_index is not None
):
num_tokens = topk_ids.shape[0]
routing_buffer[layer_weight.experts.moe_layer_index, :num_tokens, :] = topk_ids.to(routing_buffer.dtype)

Comment on lines 64 to 66
routing = response["routed_experts"]
data = np.frombuffer(base64.b64decode(routing["data"]), dtype=np.int32)
data = data.reshape(routing["shape"])
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The code example for decoding routing data is slightly misleading. The response variable from requests.post is a Response object, and you need to call .json() to get the dictionary. The example will fail if copied directly. Please clarify this to make the example runnable and avoid confusion for users.

Suggested change
routing = response["routed_experts"]
data = np.frombuffer(base64.b64decode(routing["data"]), dtype=np.int32)
data = data.reshape(routing["shape"])
import base64
import numpy as np
# response is the `requests.Response` object from the previous example
response_json = response.json()
routing = response_json["routed_experts"]
data = np.frombuffer(base64.b64decode(routing["data"]), dtype=np.int32)
data = data.reshape(routing["shape"])

Comment on lines 149 to 152
# R3: Capture routing decisions to GPU buffer using compact indexing (CUDA graph compatible)
if routing_buffer is not None and self.global_rank_ == 0 and self.moe_layer_index is not None:
num_tokens = topk_ids.shape[0]
routing_buffer[self.moe_layer_index, :num_tokens, :top_k] = topk_ids.to(routing_buffer.dtype)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This block of code for capturing routing decisions is repeated in low_latency_dispatch (lines 204-209) and select_experts_and_quant_input (lines 253-258). To improve maintainability and reduce code redundancy, consider extracting this logic into a private helper method. For example:

def _capture_routing(self, routing_buffer, topk_ids, top_k):
    if routing_buffer is not None and self.global_rank_ == 0 and self.moe_layer_index is not None:
        num_tokens = topk_ids.shape[0]
        routing_buffer[self.moe_layer_index, :num_tokens, :top_k] = topk_ids.to(routing_buffer.dtype)

This would make the code cleaner and less prone to inconsistencies if changes are needed in the future.

Comment on lines 136 to 139
# R3: Capture routing decisions to GPU buffer using compact indexing (CUDA graph compatible)
if routing_buffer is not None and self.tp_rank_ == 0 and self.moe_layer_index is not None:
num_tokens = topk_ids.shape[0]
routing_buffer[self.moe_layer_index, :num_tokens, :top_k] = topk_ids.to(routing_buffer.dtype)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This routing capture logic is duplicated in FusedAWQMARLINMoeWeightTP.experts (lines 413-416). To avoid code duplication and improve maintainability, you could extract this logic into a shared helper function within the module.

@ModelTC ModelTC deleted a comment from gemini-code-assist bot Jan 22, 2026
@sufubao sufubao closed this Jan 22, 2026
@sufubao sufubao reopened this Jan 22, 2026
This commit adds R3 (Rollout Router Replay) support to LightLLM, enabling
capture and replay of MoE routing decisions for improved performance and
debugging capabilities.

Key changes:
- Add routing_manager module for centralized routing capture/export
- Implement routing buffer management with CPU pinned memory
- Add R3 support to all MoE models (Mixtral, DeepSeek2, Qwen3-MoE, GPT-OSS)
- Refactor MoE layer indexing to use auto-increment counters
- Add API endpoints for routing capture control and export
- Add comprehensive unit tests for R3 functionality

The implementation uses a model-agnostic approach with explicit microbatch
indexing passed through the call chain, eliminating reliance on global state.
…data

The routing_manager was incorrectly accessed as an attribute of mem_manager,
but it's a module-level global accessed via get_routing_capture_manager().
This caused routing data extraction to silently fail.
Keep R3 routing capture feature only on /generate endpoint to maintain
OpenAI API compatibility. The /v1/chat/completions endpoint should not
have non-standard fields like return_routed_experts or routed_experts.
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