-
Notifications
You must be signed in to change notification settings - Fork 296
feat(R3) : Support recording expert indices for rollout router replay #1190
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?
Conversation
Summary of ChangesHello @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
🧠 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 AssistThe 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
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 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
|
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.
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.
| 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) |
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.
There appears to be a bug in how the routing decisions are captured for Mixtral models:
- The code uses
infer_state.mem_indexto index therouting_buffer. However,routing_bufferis a temporary GPU buffer for the current batch, indexed from 0 tonum_tokens - 1.mem_indexcontains global indices for the KV cache, which can be much larger than therouting_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. - The code converts
topk_idstotorch.int32, but therouting_bufferis created withtorch.int8ortorch.int16to save memory. This type mismatch should be corrected by converting torouting_buffer.dtype.
This is a critical issue that will likely cause runtime errors.
| 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) |
docs/r3_routing_capture.md
Outdated
| routing = response["routed_experts"] | ||
| data = np.frombuffer(base64.b64decode(routing["data"]), dtype=np.int32) | ||
| data = data.reshape(routing["shape"]) |
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.
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.
| 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"]) |
| # 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) |
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.
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.
| # 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) |
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.
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.
No description provided.