Skip to content

feat: add "balance" option and implement for "--ep-dispatch-algorithm" - #6739

Closed
saltyfish66 wants to merge 1 commit into
sgl-project:mainfrom
saltyfish66:balance-dispatch
Closed

saltyfish66 wants to merge 1 commit into
sgl-project:mainfrom
saltyfish66:balance-dispatch

Conversation

@saltyfish66

@saltyfish66 saltyfish66 commented May 29, 2025 •

Copy link
Copy Markdown
Contributor

Motivation

When enabling --enable-deepep-moe --deepep-mode normal, I used nsys to analyze the performance bottleneck during the prefill stage and found that the expert workloads are highly imbalanced. This imbalance causes uneven workload across GPUs when computing deep GEMM operations, leading to GPUs with lighter workloads waiting at the cache_notify kernel for synchronization before proceeding to token combination.

Although sglang has introduced features like --eplb-rebalance-num-iterations to record expert usage frequency and perform hot updates, this indirect and non-intuitive update mechanism may pose risks in production environments. Therefore, I opted to use --ep-num-redundant-experts to introduce redundancy among experts to balance the workload on each GPU.

However, I found that the existing --ep-dispatch-algorithm does not effectively balance the workload when dispatching tokens. To address this, I designed a new dispatch algorithm that balances the number of tokens dispatched from a single GPU to all GPUs as evenly as possible.


Modifications

  • sgl-kernel: Added new kernels to implement workload-balanced token dispatching, along with corresponding test cases.
  • sglang: Added a new balance option for --ep-dispatch-algorithm and implemented the related logic.

Algorithm main idea

The main latency in DeepEP arises from the large disparity in the number of tokens dispatched to different GPUs. GPUs receiving fewer tokens must wait during the combine phase for those with more tokens to finish their computations.

The key optimization is to leverage redundant experts to dispatch tokens preferentially to GPUs with fewer tokens, thus balancing the workload.

Since collecting topk_ids from all GPUs for global workload balancing is difficult, our approach focuses on local balancing per GPU: each GPU analyzes its own topk_ids and tries to distribute tokens evenly across other GPUs.

For example, during the prefill stage, we enable --tp-size=16 (i.e., a total of 16 GPUs) and --ep-num-redundant-experts=256. The input prompt contains 16k tokens, and after MLA and scatter operations, each GPU gets 1k tokens.

For GPU0, it needs to dispatch its 1k tokens to GPUs 0-15 according to the `topk_ids``. The question is: how should GPU0 dispatch these tokens so that, from GPU0’s perspective (without considering GPUs 1 to 15), the number of tokens dispatched to GPU 0-15 is as balanced as possible?

Formally, suppose after balancing, the number of tokens processed by each GPU is x_1, x_2, ..., x_n. Define x = max(x_1, x_2, ..., x_n). The smaller x is, the more balanced the workload.

However, solving for the exact x requires a dynamic programming-like approach with high overhead. Instead, we approximate x by searching within a feasible range.

For example, if dispatching 1024 tokens across 16 GPUs, and each expert has 1 redundant copy (1 logical expert load on 2 GPUs), the upper bound of x is 1024 / 2 = 512 (all tokens dispatched to only 2 GPUs), and the lower bound is 1024 / 16 = 64 (perfect balance).

We search for an approximate x' within this range by incrementing in strides (e.g., start with x' = 64, check feasibility; if not feasible, increase x' by 16(search stride) and repeat until a feasible solution is found).

Finally, we rewrite the topk_ids based on the found x' to achieve balanced token dispatch.

Comparation

baseline launch command:

SGL_ENABLE_JIT_DEEPGEMM=1 python -u -m sglang.launch_server \
--model-path /sgl-workspace/DeepSeek-R1 \
--nnodes 2 --trust-remote-code  \
--served-model-name deepseek-r1 \
--dist-init-addr 29.226.64.238:5000 \
--node-rank ${NODE_RANK} \
--host 0.0.0.0 --port 8000 \
--tp 16 \
--node-rank ${NODE_RANK} \
--schedule-policy fcfs \
--chunked-prefill-size 32768 \
--max-prefill-tokens 32768 \
--disable-overlap-schedule \
--mem-fraction-static 0.90 \
--disable-radix-cache  \
--disable-cuda-graph \
--enable-deepep-moe --deepep-mode normal --ep-size 16 \
--ep-num-redundant-experts 256 --ep-dispatch-algorithm static

balanced launch command: similar to baseline launch, change --ep-dispatch-algorithm static to --ep-dispatch-algorithm balance

Correctness

python3 benchmark/gsm8k/bench_sglang.py --num-shots 8 --num-questions 200 --parallel 16 \
--data-path /geminicephfs/mm-base-tfcc/yuethe/projects/test_data/gsm8k.jsonl \
--host http://127.0.0.1 --port 8000

baseline:
Accuracy: 0.965
Invalid: 0.000
Latency: 497.245 s
Output throughput: 40.883 token/s

balanced:
Accuracy: 0.970
Invalid: 0.000
Latency: 483.616 s
Output throughput: 40.997 token/s

benchmark

benchmark on 2x8xH20.

prefill stage (6~8% throughput improvement)

prompt len = 14k, 8.4% throughput improvement

## set the random seed to 42 before benchmark
python3 -m sglang.bench_one_batch_server --model None --skip-warmup --base-url http://127.0.0.1:8000 --batch-size 1 --input-len 14000 --output-len 1 --model-path /sgl-workspace/DeepSeek-R1

baseline:
#Input tokens: 14000
#Output tokens: 1
input_requests[0].prompt[:10]=[15795, 860, 5390, 13418, 5191, 11964, 11284, 5734, 6265, 466]
batch size: 1
input_len: 14000
output_len: 1
latency: 1.18 s
ttft: 1.18 s
Last generation throughput: 0.00 tok/s
Input throughput: 11827.43 tok/s

balanced:
#Input tokens: 14000
#Output tokens: 1
input_requests[0].prompt[:10]=[15795, 860, 5390, 13418, 5191, 11964, 11284, 5734, 6265, 466]
batch size: 1
input_len: 14000
output_len: 1
latency: 1.09 s
ttft: 1.09 s
Last generation throughput: 0.00 tok/s
Input throughput: 12827.63 tok/s

prompt len = 16384, 6.18% throughput improvement

python3 -m sglang.bench_serving --backend sglang-oai --num-prompts 50 --request-rate 10 --dataset-name random --random-input-len 16384 --random-output-len 0 --random-range-ratio 1 --port 8000 --model /sgl-workspace/DeepSeek-R1 --dataset-path /geminicephfs/mm-base-tfcc/yuethe/projects/tune/ShareGPT_V3_unfiltered_cleaned_split.json

baseline:
============ Serving Benchmark Result ============
Backend:                                 sglang-oai
Traffic request rate:                    10.0      
Max request concurrency:                 not set   
Successful requests:                     50        
Benchmark duration (s):                  63.65     
Total input tokens:                      819200    
Total generated tokens:                  0         
Total generated tokens (retokenized):    50        
Request throughput (req/s):              0.79      
Input token throughput (tok/s):          12870.77  
Output token throughput (tok/s):         0.00      
Total token throughput (tok/s):          12870.77  
Concurrency:                             25.56     
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   32533.92  
Median E2E Latency (ms):                 32922.46  
---------------Time to First Token----------------
Mean TTFT (ms):                          32533.91  
Median TTFT (ms):                        32922.45  
P99 TTFT (ms):                           58941.45  
---------------Inter-Token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P95 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
Max ITL (ms):                            0.00      
==================================================

balanced:
============ Serving Benchmark Result ============
Backend:                                 sglang-oai
Traffic request rate:                    10.0      
Max request concurrency:                 not set   
Successful requests:                     50        
Benchmark duration (s):                  59.94     
Total input tokens:                      819200    
Total generated tokens:                  0         
Total generated tokens (retokenized):    50        
Request throughput (req/s):              0.83      
Input token throughput (tok/s):          13666.92  
Output token throughput (tok/s):         0.00      
Total token throughput (tok/s):          13666.92  
Concurrency:                             25.56     
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   30641.85  
Median E2E Latency (ms):                 31194.94  
---------------Time to First Token----------------
Mean TTFT (ms):                          30641.84  
Median TTFT (ms):                        31194.93  
P99 TTFT (ms):                           55243.41  
---------------Inter-Token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P95 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
Max ITL (ms):                            0.00      
==================================================

prompt len = 10240, 6.15% throughput improvement

python3 -m sglang.bench_serving --backend sglang-oai --num-prompts 50 --request-rate 10 --dataset-name random --random-input-len 10240 --random-output-len 0 --random-range-ratio 1 --port 8000 --model /sgl-workspace/DeepSeek-R1 --dataset-path /geminicephfs/mm-base-tfcc/yuethe/projects/tune/ShareGPT_V3_unfiltered_cleaned_split.json

baseline:
============ Serving Benchmark Result ============
Backend:                                 sglang-oai
Traffic request rate:                    10.0      
Max request concurrency:                 not set   
Successful requests:                     50        
Benchmark duration (s):                  46.95     
Total input tokens:                      512000    
Total generated tokens:                  0         
Total generated tokens (retokenized):    50        
Request throughput (req/s):              1.06      
Input token throughput (tok/s):          10904.92  
Output token throughput (tok/s):         0.00      
Total token throughput (tok/s):          10904.92  
Concurrency:                             24.71     
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   23200.74  
Median E2E Latency (ms):                 23323.82  
---------------Time to First Token----------------
Mean TTFT (ms):                          23200.73  
Median TTFT (ms):                        23323.81  
P99 TTFT (ms):                           42252.33  
---------------Inter-Token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P95 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
Max ITL (ms):                            0.00      
==================================================

balanced:
============ Serving Benchmark Result ============
Backend:                                 sglang-oai
Traffic request rate:                    10.0      
Max request concurrency:                 not set   
Successful requests:                     50        
Benchmark duration (s):                  44.23     
Total input tokens:                      512000    
Total generated tokens:                  0         
Total generated tokens (retokenized):    50        
Request throughput (req/s):              1.13      
Input token throughput (tok/s):          11576.38  
Output token throughput (tok/s):         0.00      
Total token throughput (tok/s):          11576.38  
Concurrency:                             24.39     
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   21576.91  
Median E2E Latency (ms):                 21494.61  
---------------Time to First Token----------------
Mean TTFT (ms):                          21576.90  
Median TTFT (ms):                        21494.59  
P99 TTFT (ms):                           39526.78  
---------------Inter-Token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P95 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
Max ITL (ms):                            0.00      
==================================================

prompt len = 4096, 7.4% throughput improvement

python3 -m sglang.bench_serving --backend sglang-oai --num-prompts 50 --request-rate 10 --dataset-name random --random-input-len 4096 --random-output-len 0 --random-range-ratio 1 --port 8000 --model /sgl-workspace/DeepSeek-R1 --dataset-path /geminicephfs/mm-base-tfcc/yuethe/projects/tune/ShareGPT_V3_unfiltered_cleaned_split.json

baseline
============ Serving Benchmark Result ============
Backend:                                 sglang-oai
Traffic request rate:                    10.0      
Max request concurrency:                 not set   
Successful requests:                     50        
Benchmark duration (s):                  14.56     
Total input tokens:                      204800    
Total generated tokens:                  0         
Total generated tokens (retokenized):    50        
Request throughput (req/s):              3.43      
Input token throughput (tok/s):          14065.61  
Output token throughput (tok/s):         0.00      
Total token throughput (tok/s):          14065.61  
Concurrency:                             21.63     
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   6299.79   
Median E2E Latency (ms):                 6714.27   
---------------Time to First Token----------------
Mean TTFT (ms):                          6299.78   
Median TTFT (ms):                        6714.27   
P99 TTFT (ms):                           10259.76  
---------------Inter-Token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P95 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
Max ITL (ms):                            0.00      
==================================================
balanced:
============ Serving Benchmark Result ============
Backend:                                 sglang-oai
Traffic request rate:                    10.0      
Max request concurrency:                 not set   
Successful requests:                     50        
Benchmark duration (s):                  13.56     
Total input tokens:                      204800    
Total generated tokens:                  0         
Total generated tokens (retokenized):    50        
Request throughput (req/s):              3.69      
Input token throughput (tok/s):          15106.92  
Output token throughput (tok/s):         0.00      
Total token throughput (tok/s):          15106.92  
Concurrency:                             21.67     
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   5876.49   
Median E2E Latency (ms):                 6307.98   
---------------Time to First Token----------------
Mean TTFT (ms):                          5876.48   
Median TTFT (ms):                        6307.97   
P99 TTFT (ms):                           9384.40   
---------------Inter-Token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P95 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
Max ITL (ms):                            0.00      
==================================================

decode stage(2.3% throughput reduction)

Note that:
When the number of tokens is small, the balance dispatch algorithm will be downgraded to a static dispatch algorithm to avoid the additional overhead brought by the balance algorithm.
Actually, balance algorithm is not suitable for the decoding stage because the number of tokens that each GPU needs to dispatch in the decoding stage is too small.

Please note that --deepep-mode normal is used here, setting -deepep-mode=auto/low_latency will cause program errors (both baseline and balance)

python3 -m sglang.bench_serving --backend sglang-oai --num-prompts 64 --request-rate 10 --dataset-name random --random-input-len 1 --random-output-len 256 --random-range-ratio 1 --port 8000 --model /sgl-workspace/DeepSeek-R1 --dataset-path /geminicephfs/mm-base-tfcc/yuethe/projects/tune/ShareGPT_V3_unfiltered_cleaned_split.json

baseline:
============ Serving Benchmark Result ============
Backend:                                 sglang-oai
Traffic request rate:                    10.0      
Max request concurrency:                 not set   
Successful requests:                     64        
Benchmark duration (s):                  87.53     
Total input tokens:                      64        
Total generated tokens:                  16384     
Total generated tokens (retokenized):    16384     
Request throughput (req/s):              0.73      
Input token throughput (tok/s):          0.73      
Output token throughput (tok/s):         187.18    
Total token throughput (tok/s):          187.91    
Concurrency:                             61.32     
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   83866.92  
Median E2E Latency (ms):                 83517.38  
---------------Time to First Token----------------
Mean TTFT (ms):                          1090.81   
Median TTFT (ms):                        1124.44   
P99 TTFT (ms):                           1967.67   
---------------Inter-Token Latency----------------
Mean ITL (ms):                           326.17    
Median ITL (ms):                         296.30    
P95 ITL (ms):                            424.50    
P99 ITL (ms):                            640.93    
Max ITL (ms):                            5364.63   
==================================================
balanced:
============ Serving Benchmark Result ============
Backend:                                 sglang-oai
Traffic request rate:                    10.0      
Max request concurrency:                 not set   
Successful requests:                     64        
Benchmark duration (s):                  89.67     
Total input tokens:                      64        
Total generated tokens:                  16384     
Total generated tokens (retokenized):    16384     
Request throughput (req/s):              0.71      
Input token throughput (tok/s):          0.71      
Output token throughput (tok/s):         182.72    
Total token throughput (tok/s):          183.44    
Concurrency:                             61.39     
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   86010.38  
Median E2E Latency (ms):                 85660.04  
---------------Time to First Token----------------
Mean TTFT (ms):                          2102.41   
Median TTFT (ms):                        1975.33   
P99 TTFT (ms):                           3602.40   
---------------Inter-Token Latency----------------
Mean ITL (ms):                           330.51    
Median ITL (ms):                         301.62    
P95 ITL (ms):                            418.52    
P99 ITL (ms):                            720.71    
Max ITL (ms):                            6060.71   
==================================================

Algorithm restriction

assert num_physical_expert % num_logical_expert == 0
assert num_logical_expert % num_gpu == 0

For deepseek-671B (which has 256 routed_experts), --ep-num-redundant-experts can only be set to a multiple of 256.

Checklist

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hello @saltyfish66, 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!

Summary of Changes

Hello team, Gemini here with a summary of this pull request from @saltyfish66.

This PR introduces a new expert dispatch algorithm called "balance" for DeepEP MoE configurations, specifically targeting the workload imbalance observed during the prefill stage when using redundant experts (--ep-num-redundant-experts). The author identified that uneven token distribution across GPUs leads to performance bottlenecks due to synchronization waits.

The core idea of the new algorithm is to leverage redundant experts to redistribute tokens from GPUs with higher workloads to those with lower workloads, aiming for a more balanced distribution from each GPU's perspective. This is achieved by analyzing the topk_ids locally on each GPU and strategically remapping them to physical experts on different GPUs.

The changes involve adding a new CUDA kernel (balance_topk_ids) to implement the balancing logic and integrating this new algorithm into the SGLang framework as a new option for the --ep-dispatch-algorithm command-line argument. The PR includes benchmark results demonstrating significant prefill throughput improvements (6-8%) with the new algorithm compared to the static dispatch. It also notes that the balance algorithm falls back to static for small token counts (like in the decode stage) to avoid overhead, and shows a minor throughput reduction in decode, indicating its primary benefit is for larger prefill workloads.

Highlights

  • New Dispatch Algorithm: Adds a new balance option to the --ep-dispatch-algorithm for DeepEP MoE, designed to address workload imbalance across GPUs.
  • Workload Balancing: The new algorithm leverages redundant experts to redistribute tokens, aiming to balance the number of tokens dispatched from each GPU to all GPUs as evenly as possible.
  • CUDA Kernel Implementation: Implements the core balancing logic in a new CUDA kernel (balance_topk_ids) within the sgl-kernel module.
  • Performance Improvement: Demonstrates 6-8% throughput improvement during the prefill stage compared to the static dispatch algorithm, particularly for larger prompt lengths.
  • Decode Stage Handling: Includes a fallback to the static algorithm for small token counts (typical in decode) to avoid overhead, acknowledging that the balance algorithm is less suitable for this stage.
  • Unit Tests: Adds a new unit test file (test_balance_topk_ids.py) to verify the correctness of the new CUDA kernel under various configurations.

Changelog

Click here to see the changelog
  • python/sglang/srt/managers/expert_location.py
    • Modified init_trivial to handle the balance dispatch algorithm, ensuring physical experts are mapped to logical experts in a way compatible with the new balancing logic when --ep-dispatch-algorithm balance is used (lines 90-109).
    • Added an assertion to ensure num_physical_experts is a multiple of num_logical_experts for the balance algorithm (lines 91-93).
  • python/sglang/srt/managers/expert_location_dispatch.py
    • Added balance to the Literal type hint for ep_dispatch_algorithm in the ExpertLocationDispatchInfo dataclass (line 26).
    • Added ep_size field to the ExpertLocationDispatchInfo dataclass (line 34).
    • Passed ep_size when initializing ExpertLocationDispatchInfo (line 56).
    • Added a conditional branch in topk_ids_logical_to_physical to call the new _topk_ids_logical_to_physical_balance function when the algorithm is balance (lines 82-83).
    • Implemented the _topk_ids_logical_to_physical_balance function, which calls the balance_topk_ids kernel from sgl_kernel and includes a fallback to static dispatch for small token counts (<= 32) (lines 110-143).
  • python/sglang/srt/server_args.py
    • Added balance as a valid option for the ep_dispatch_algorithm command-line argument (lines 175-177).
  • sgl-kernel/CMakeLists.txt
    • Added the new CUDA source file csrc/moe/balance_topk_ids.cu to the list of sources to be compiled (line 227).
  • sgl-kernel/csrc/common_extension.cc
    • Registered the new CUDA function balance_topk_ids with the PyTorch extension mechanism (lines 163-166).
  • sgl-kernel/csrc/moe/balance_topk_ids.cu
    • Added the CUDA kernel implementation for the balance_topk_ids function, including kernels for counting workloads (gpu_workloads_count_kernel), searching for the optimal balance mapping (search_balance_mapping_kernel), and rewriting topk_ids based on the mapping (rewrite_topk_ids_by_balance_mapping_kernel) (lines 1-415).
  • sgl-kernel/include/sgl_kernel_ops.h
    • Declared the C++ function signature for balance_topk_ids (lines 243-250).
  • sgl-kernel/python/sgl_kernel/init.py
    • Imported the balance_topk_ids function from the sgl_kernel.moe module (line 49).
  • sgl-kernel/python/sgl_kernel/moe.py
    • Defined the Python wrapper function balance_topk_ids that calls the registered C++ CUDA function (lines 131-148).
  • sgl-kernel/tests/test_balance_topk_ids.py
    • Added a new test file with a parameterized test function test_balance_topk_ids to verify the correctness of the balance_topk_ids CUDA kernel (lines 1-94).
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

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 issue 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 is currently in preview and 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 to provide feedback.

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.


Experts spread wide,
Workloads collide.
Balance the load,
On CUDA's road.
Faster prefill, side by side.

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

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

Copy link
Copy Markdown
Contributor

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 a new "balance" dispatch algorithm for DeepEP MoE, aiming to improve performance during the prefill stage by distributing token workloads more evenly across GPUs. The changes include new CUDA kernels for the balancing logic, modifications to the expert location and dispatch mechanisms in Python, and corresponding tests.

Overall, this is a well-motivated and thoughtfully implemented feature. The PR description provides excellent context and detailed benchmark results, demonstrating significant throughput improvements in the prefill stage. The core algorithm for balancing seems sound, and the new CUDA kernels are accompanied by Python-level tests that cover key aspects of correctness.

I have a few suggestions, primarily related to the new CUDA kernel, that would further enhance the robustness and usability of this feature.

Documentation Update Needed:
The PR checklist indicates that documentation updates are pending. Could you please ensure that user-facing documentation (e.g., command-line argument help, guides on expert parallelism) is updated to include details about the new --ep-dispatch-algorithm balance option? This should cover:

  • When to use this algorithm (primarily for prefill stages with imbalanced expert workloads).
  • How it interacts with --ep-num-redundant-experts.
  • The requirement that num_physical_experts must be a multiple of num_logical_experts, and num_logical_experts must be a multiple of ep_size (as enforced by assertions and TORCH_CHECKs).
  • Any potential impact on decode performance (though the fallback mechanism for small token counts is a good mitigation).

This will help users understand how to effectively leverage this new feature.

Summary of Findings

  • CUDA Kernel Safety: MAX_EXPERT_COPIES_MULTIPLE Limit: The CUDA kernel balance_topk_ids.cu defines a constant MAX_EXPERT_COPIES_MULTIPLE = 8. There is no runtime check to ensure that num_physical_experts / num_logical_experts does not exceed this. This could lead to out-of-bounds shared memory access if a user configures high expert redundancy. A TORCH_CHECK should be added.
  • CUDA Kernel Usability: MAX_EXPERT_COPIES_MULTIPLE Value: The value of MAX_EXPERT_COPIES_MULTIPLE (currently 8) might be too restrictive for scenarios requiring very high expert redundancy (e.g., >8x copies per logical expert). This limit should be re-evaluated.
  • Documentation Update: User-facing documentation for the new --ep-dispatch-algorithm balance option and its usage (e.g., interaction with --ep-num-redundant-experts, prerequisites) needs to be updated as indicated by the unchecked item in the PR checklist.

Merge Readiness

This pull request introduces a valuable performance optimization. However, there are high-severity issues related to the safety and limits of the new CUDA kernel that need to be addressed. Specifically, a runtime check for expert_copies_multiple against MAX_EXPERT_COPIES_MULTIPLE should be added to prevent potential memory corruption. The value of MAX_EXPERT_COPIES_MULTIPLE itself should also be reconsidered for broader applicability. Additionally, user-facing documentation needs to be updated.

I recommend that these changes be made before merging. I am unable to approve the pull request myself; please ensure other reviewers approve it after these concerns are addressed.

Comment thread sgl-kernel/csrc/moe/balance_topk_ids.cu Resolved
Comment thread sgl-kernel/csrc/moe/balance_topk_ids.cu Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The constant MAX_EXPERT_COPIES_MULTIPLE is set to 8. This limits the maximum redundancy factor (i.e., num_physical_experts / num_logical_experts) that the balancing algorithm can handle to 8x.

Given that expert_copies_multiple = 1 + (ep_num_redundant_experts / num_logical_experts), if a user, for instance, has num_logical_experts = 16 and wants to achieve 16x redundancy, they would set ep_num_redundant_experts = 15 * 16 = 240. This would result in expert_copies_multiple = 16, exceeding the current limit of 8 and potentially leading to issues (see related comment on missing runtime check).

Could you evaluate if this limit of 8 is sufficient for all anticipated use cases or if it might be too restrictive? If higher redundancy is a plausible scenario, consider increasing this constant. A comment here explaining this limitation would also be beneficial for future maintainers.

@FlamingoPg FlamingoPg self-assigned this May 29, 2025
@fzyzcjy fzyzcjy self-assigned this May 29, 2025
@fzyzcjy

fzyzcjy commented May 29, 2025 •

Copy link
Copy Markdown
Collaborator

The approach looks reasonable. Indeed I also want to optimize EPLB, but currently I have written only the most naive version, because I find that EPLB is strongly related to data distribution, and since I cannot get production data I cannot optimize :(

Thus, I wonder have you tried it in real datasets and does it improve? (that bench_one_batch_server uses a repeated & truncated sharegpt, thus is quite fake) Theoretically speaking I feel it should be good at least under some distributions.
Btw, a somehow similar approach is mentioned in DeepSeek's paper.

Some thoughts:

  • More redundant experts will take more memory, thus wondering whether this will be a disadvantage.
  • The baseline may need to be changed: you need to either use --enable-eplb for a dynamic EPLB, or --init-expert-distribution for a static one. With none of them, there is no EPLB happening indeed.
  • Also, maybe use dynamic instead of static for baseline, since the former is more balanced than the latter and I picked it in the blog commands

I will review the code in detail after ensuring the high-level things are done.

@saltyfish66

saltyfish66 commented May 29, 2025 •

Copy link
Copy Markdown
Contributor Author

The approach looks reasonable. Indeed I also want to optimize EPLB, but currently I have written only the most naive version, because I find that EPLB is strongly related to data distribution, and since I cannot get production data I cannot optimize :(

Thus, I wonder have you tried it in real datasets and does it improve? (that bench_one_batch_server uses a repeated & truncated sharegpt, thus is quite fake) Theoretically speaking I feel it should be good at least under some distributions. Btw, a somehow similar approach is mentioned in DeepSeek's paper.

Some thoughts:

  • More redundant experts will take more memory, thus wondering whether this will be a disadvantage.
  • The baseline may need to be changed: you need to either use --enable-eplb for a dynamic EPLB, or --init-expert-distribution for a static one. With none of them, there is no EPLB happening indeed.
  • Also, maybe use dynamic instead of static for baseline, since the former is more balanced than the latter and I picked it in the blog commands

I will review the code in detail after ensuring the high-level things are done.

hank you for your reply; it has been very helpful. First, I would like to clarify the purpose of this pull request by starting from the ways to use redundant experts feature.

As I understand, there are currently three ways to use redundant experts to improve throughput:

  1. Simply increase the number of redundant experts:
    In the worst case, all tokens are processed by one expert on a single GPU. By redundantly loading experts across multiple GPUs, we can achieve load balancing and improve throughput.

  2. Use --init-expert-distribution without hot updates:
    In this case, the expert frequency distribution must be known in advance and remain unchanged (which is very difficult to guarantee).

  3. Use --enable-eplb for hot updates:
    The expert distribution is periodically updated based on online requests. During updates, the service is unavailable. Theoretically (assuming zero latency to update expert weights), this method can provide the highest throughput.

My PR mainly aims to optimize the first approach.

Why don’t we use the third approach to achieve the highest throughput?

For a service with strict SLOs (such as TTFT, TPOT) and high availability requirements (a customer-facing service that must guarantee at least 99.9% successful requests), our primary need is stability.

  • Using the second approach, we cannot guarantee a stable request distribution at all times. Changes in distribution can negatively impact key business metrics like TTFT.
  • Using the third approach, we cannot reliably know which instances in the cluster are truly available (immediately accepting and processing requests) versus those that are currently rebalancing. Moreover, if a rebalance bug occurs (e.g., updating incorrect expert weights causing wrong outputs), we have no way to detect it until customers report issues(We couldn't even reproduce it to fix the problem).

As you mentioned, "More redundant experts will take more memory, thus wondering whether this will be a disadvantage." Our optimization targets the prefill stage. After implementing PD separation, the prefill nodes have ample GPU memory because they do not need to store any KV cache.

After the prefill node finishes computing the MLA for one layer of the model, it can send the computed KV states to the corresponding decoder nodes or other storage.

More specifically, our PR focuses on optimizing the prefill nodes under PD separation.

Honestly, we cannot guarantee that our PR can achieve higher throughput than the second and third methods. We just provide an option so that users with higher stability requirements can get higher performance through the first method.

Finally,below are the benchmark results:
baseline launch cmd:

python -u -m sglang.launch_server \
--model-path /sgl-workspace/DeepSeek-R1 \
--nnodes 2 --trust-remote-code  \
--served-model-name deepseek-r1 \
--dist-init-addr 29.226.64.238:5000 \
--node-rank ${NODE_RANK} \
--host 0.0.0.0 --port 8000 \
--tp 16 \
--node-rank ${NODE_RANK} \
--schedule-policy fcfs \
--chunked-prefill-size 32768 \
--max-prefill-tokens 32768 \
--disable-overlap-schedule \
--mem-fraction-static 0.90 \
--disable-radix-cache  \
--disable-cuda-graph \
--enable-deepep-moe --deepep-mode normal --ep-size 16 \
--ep-num-redundant-experts 256 --ep-dispatch-algorithm dynamic

We have a real online dataset consisting of 300 prompts, with prompt lengths ranging from 6k to 32k tokens and an average length of 14k tokens. Each prompt includes a system prompt, user question, and RAG content. Since only the prefill stage is considered, the number of output tokens is set to 1 during benchmark.

Maximum request concurrency: 1 
process request one by one, 3.08% throughput improvement
baseline:
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  331.06    
Total input tokens:                      4066503   
Total generated tokens:                  300       
Request throughput (req/s):              0.91      
Output token throughput (tok/s):         0.91      
Total Token throughput (tok/s):          12284.14  
---------------Time to First Token----------------
Mean TTFT (ms):                          1102.96   
Median TTFT (ms):                        961.44    
P90 TTFT (ms):                           2054.94   
P99 TTFT (ms):                           2584.05   
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          1102.98   
Median E2EL (ms):                        961.46    
P90 E2EL (ms):                           2054.96   
P99 E2EL (ms):                           2584.06   
==================================================
balanced:
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  321.15    
Total input tokens:                      4066433   
Total generated tokens:                  300       
Request throughput (req/s):              0.93      
Output token throughput (tok/s):         0.93      
Total Token throughput (tok/s):          12662.88  
---------------Time to First Token----------------
Mean TTFT (ms):                          1069.95   
Median TTFT (ms):                        929.00    
P90 TTFT (ms):                           2024.23   
P99 TTFT (ms):                           2489.43   
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          1069.97   
Median E2EL (ms):                        929.02    
P90 E2EL (ms):                           2024.24   
P99 E2EL (ms):                           2489.45   
==================================================

Maximum request concurrency: 16, 3.96% throughput improvement
baseline
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  294.29    
Total input tokens:                      4066503   
Total generated tokens:                  300       
Request throughput (req/s):              1.02      
Output token throughput (tok/s):         1.02      
Total Token throughput (tok/s):          13819.14  
---------------Time to First Token----------------
Mean TTFT (ms):                          15413.30  
Median TTFT (ms):                        15394.30  
P90 TTFT (ms):                           19544.60  
P99 TTFT (ms):                           22690.97  
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          15413.32  
Median E2EL (ms):                        15394.31  
P90 E2EL (ms):                           19544.62  
P99 E2EL (ms):                           22690.99  
==================================================
balance:
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  283.06    
Total input tokens:                      4066433   
Total generated tokens:                  300       
Request throughput (req/s):              1.06      
Output token throughput (tok/s):         1.06      
Total Token throughput (tok/s):          14366.96  
---------------Time to First Token----------------
Mean TTFT (ms):                          14823.09  
Median TTFT (ms):                        14746.34  
P90 TTFT (ms):                           19111.13  
P99 TTFT (ms):                           21305.41  
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          14823.10  
Median E2EL (ms):                        14746.35  
P90 E2EL (ms):                           19111.14  
P99 E2EL (ms):                           21305.42  
==================================================

Maximum request concurrency: 300(offline, send all requests at once)
3.81% throughput improvement
baseline
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  292.00    
Total input tokens:                      4066503   
Total generated tokens:                  300       
Request throughput (req/s):              1.03      
Output token throughput (tok/s):         1.03      
Total Token throughput (tok/s):          13927.41  
---------------Time to First Token----------------
Mean TTFT (ms):                          118528.24 
Median TTFT (ms):                        101493.06 
P90 TTFT (ms):                           260477.07 
P99 TTFT (ms):                           288380.27 
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          118528.26 
Median E2EL (ms):                        101493.07 
P90 E2EL (ms):                           260477.09 
P99 E2EL (ms):                           288380.28 
==================================================
balance:
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  281.29    
Total input tokens:                      4066433   
Total generated tokens:                  300       
Request throughput (req/s):              1.07      
Output token throughput (tok/s):         1.07      
Total Token throughput (tok/s):          14457.68  
---------------Time to First Token----------------
Mean TTFT (ms):                          134558.08 
Median TTFT (ms):                        142819.46 
P90 TTFT (ms):                           256887.87 
P99 TTFT (ms):                           278742.54 
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          134558.09 
Median E2EL (ms):                        142819.47 
P90 E2EL (ms):                           256887.89 
P99 E2EL (ms):                           278742.55 
==================================================

As you mentioned, the throughput improvement is closely related to the specific data set.

@fzyzcjy

fzyzcjy commented May 30, 2025 •

Copy link
Copy Markdown
Collaborator

Hi,

  • The second approach (static EPLB) should not be used in production. It is for testing, b/c it is more static across runs of tests. In real life we should use 3rd approach.
  • The third approach
    • The rebalance should not introduce large stop-the-world time. Currently it is suboptimal and I will need to update it. Theoretically it should be e.g. <20ms, because you can, to an extreme, pause and rebalance only one single layer, and then continue to next forward pass. And p2p transfer for one layer is pretty fast.
      • I am not sure about your use case. Does 20ms extra pause harm your case or is it OK for you?
    • There can exist ways to know which nodes are rebalancing if you need. Just add an API and done. Though I think it is not very much needed given the point above.
    • "if a rebalance bug occurs" - most naive approach is to add a canary weight to experts, and i-th expert has value i in it. Then after rebalancing we just check whether the weight value matches what we expect. And it is pretty easy to debug: just dump all metadata (which is small) on each rebalance or on failed rebalance. Btw I do random testing for tens of thousands of times and it looks OK.
      • Also, if you face any bug please create an issue and I will check it.
  • "We just provide an option so that users with higher stability requirements can get higher performance through the first method." Definitely - having one more choice is pretty good since it can be useful in some data distribution.
  • Since you have the dataset, I am curious, could you please have a try on the static EPLB and dynamic EPLB to see how it performs as well? (For dynamic EPLB ensure the rebalancing has happened, o/w we are not testing it).
    • Also, could you please try zero redundant experts as a most vanilla baseline? Curious how worse it will be than 256 redundant baseline.

@saltyfish66

saltyfish66 commented May 30, 2025 •

Copy link
Copy Markdown
Contributor Author

Hi,

  • The second approach (static EPLB) should not be used in production. It is for testing, b/c it is more static across runs of tests. In real life we should use 3rd approach.

  • The third approach

    • The rebalance should not introduce large stop-the-world time. Currently it is suboptimal and I will need to update it. Theoretically it should be e.g. <20ms, because you can, to an extreme, pause and rebalance only one single layer, and then continue to next forward pass. And p2p transfer for one layer is pretty fast.

      • I am not sure about your use case. Does 20ms extra pause harm your case or is it OK for you?
    • There can exist ways to know which nodes are rebalancing if you need. Just add an API and done. Though I think it is not very much needed given the point above.

    • "if a rebalance bug occurs" - most naive approach is to add a canary weight to experts, and i-th expert has value i in it. Then after rebalancing we just check whether the weight value matches what we expect. And it is pretty easy to debug: just dump all metadata (which is small) on each rebalance or on failed rebalance. Btw I do random testing for tens of thousands of times and it looks OK.

      • Also, if you face any bug please create an issue and I will check it.
  • "We just provide an option so that users with higher stability requirements can get higher performance through the first method." Definitely - having one more choice is pretty good since it can be useful in some data distribution.

  • Since you have the dataset, I am curious, could you please have a try on the static EPLB and dynamic EPLB to see how it performs as well? (For dynamic EPLB ensure the rebalancing has happened, o/w we are not testing it).

    • Also, could you please try zero redundant experts as a most vanilla baseline? Curious how worse it will be than 256 redundant baseline.

Thanks for your reply. I don't know much about expert rebalance. Thanks for your explanation.
I tested the performance of rebalance on my dataset.

Launch command(adapted from #6017)

python -u -m sglang.launch_server \
--model-path /sgl-workspace/DeepSeek-R1 \
--nnodes 2 --trust-remote-code  \
--served-model-name deepseek-r1 \
--dist-init-addr 29.226.64.238:5000 \
--node-rank ${NODE_RANK} \
--host 0.0.0.0 --port 8000 \
--tp 16 \
--node-rank ${NODE_RANK} \
--schedule-policy fcfs \
--chunked-prefill-size 32768 \
--max-prefill-tokens 32768 \
--disable-overlap-schedule \
--mem-fraction-static 0.70 \
--disable-radix-cache  \
--disable-cuda-graph \
--enable-deepep-moe --deepep-mode normal --ep-size 16 \
--ep-num-redundant-experts 128 --ep-dispatch-algorithm dynamic \
--enable-eplb --eplb-rebalance-num-iterations 100

Notice that I have to decrease --ep-num-redundant-experts from 256 to 128 and adjust --mem-fraction-static, because I got OOM when rebalance experts.
The dataset contains 300 prompts, so --eplb-rebalance-num-iterations 100 should be a reasonable value.
According to the server log, each expert rebalance takes about 1.8 seconds.

We first ran the entire dataset on the server to warm up the expert rebalance.

benchmark results:

max_conrency 1
relance 2 times, 4s 1st, 1.5s 2nd time
max_conrency 1
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  320.72    
Total input tokens:                      4066453   
Total generated tokens:                  300       
Request throughput (req/s):              0.94      
Output token throughput (tok/s):         0.94      
Total Token throughput (tok/s):          12680.13  (this pr 12662.88)
---------------Time to First Token----------------
Mean TTFT (ms):                          1068.60   
Median TTFT (ms):                        936.02    
P90 TTFT (ms):                           2015.85   
P99 TTFT (ms):                           2455.05   
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          1068.61   
Median E2EL (ms):                        936.04    
P90 E2EL (ms):                           2015.86   
P99 E2EL (ms):                           2455.07   
==================================================

max_conrency 16
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  278.42    
Total input tokens:                      4066532   
Total generated tokens:                  300       
Request throughput (req/s):              1.08      
Output token throughput (tok/s):         1.08      
Total Token throughput (tok/s):          14606.62   (this pr 14366.96  )
---------------Time to First Token----------------
Mean TTFT (ms):                          14530.74  
Median TTFT (ms):                        14226.93  
P90 TTFT (ms):                           18373.51  
P99 TTFT (ms):                           20090.91  
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          14530.75  
Median E2EL (ms):                        14226.94  
P90 E2EL (ms):                           18373.52  
P99 E2EL (ms):                           20090.93  
==================================================

max concurency 300
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  277.42    
Total input tokens:                      4066532   
Total generated tokens:                  300       
Request throughput (req/s):              1.08      
Output token throughput (tok/s):         1.08      
Total Token throughput (tok/s):          14659.47  (this pr 14457.68  )
---------------Time to First Token----------------
Mean TTFT (ms):                          112094.16 
Median TTFT (ms):                        97147.87  
P90 TTFT (ms):                           248132.19 
P99 TTFT (ms):                           275708.35 
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          112094.17 
Median E2EL (ms):                        97147.88  
P90 E2EL (ms):                           248132.20 
P99 E2EL (ms):                           275708.38 
==================================================

some server log

[2025-05-30 09:56:35 TP15] [EPLBManager] rebalance start
[2025-05-30 09:56:35 TP12] Resetting ExpertDistributionRecorder...
[2025-05-30 09:56:35 TP11] Resetting ExpertDistributionRecorder...
[2025-05-30 09:56:35 TP9] Resetting ExpertDistributionRecorder...
[2025-05-30 09:56:35 TP10] Resetting ExpertDistributionRecorder...
[2025-05-30 09:56:35 TP8] Resetting ExpertDistributionRecorder...
[2025-05-30 09:56:35 TP13] Resetting ExpertDistributionRecorder...
[2025-05-30 09:56:35 TP14] Resetting ExpertDistributionRecorder...
[2025-05-30 09:56:35 TP15] Resetting ExpertDistributionRecorder...
[2025-05-30 09:56:37 TP10] [EPLBManager] rebalance end time=1.767s
[2025-05-30 09:56:37 TP11] [EPLBManager] rebalance end time=1.772s
[2025-05-30 09:56:37 TP12] [EPLBManager] rebalance end time=1.772s
[2025-05-30 09:56:37 TP8] [EPLBManager] rebalance end time=1.772s
[2025-05-30 09:56:37 TP13] [EPLBManager] rebalance end time=1.772s
[2025-05-30 09:56:37 TP14] [EPLBManager] rebalance end time=1.774s
[2025-05-30 09:56:37 TP15] [EPLBManager] rebalance end time=1.775s
[2025-05-30 09:56:37 TP9] [EPLBManager] rebalance end time=1.775s
[2025-05-30 09:58:25 TP13] [EPLBManager] rebalance start
[2025-05-30 09:58:25 TP11] [EPLBManager] rebalance start
[2025-05-30 09:58:25 TP15] [EPLBManager] rebalance start
[2025-05-30 09:58:25 TP12] [EPLBManager] rebalance start
[2025-05-30 09:58:25 TP14] [EPLBManager] rebalance start
[2025-05-30 09:58:25 TP10] [EPLBManager] rebalance start
[2025-05-30 09:58:25 TP8] [EPLBManager] rebalance start
[2025-05-30 09:58:25 TP9] [EPLBManager] rebalance start
[2025-05-30 09:58:25 TP13] Resetting ExpertDistributionRecorder...
[2025-05-30 09:58:25 TP15] Resetting ExpertDistributionRecorder...
[2025-05-30 09:58:25 TP11] Resetting ExpertDistributionRecorder...
[2025-05-30 09:58:25 TP8] Resetting ExpertDistributionRecorder...
[2025-05-30 09:58:25 TP10] Resetting ExpertDistributionRecorder...
[2025-05-30 09:58:25 TP12] Resetting ExpertDistributionRecorder...
[2025-05-30 09:58:25 TP14] Resetting ExpertDistributionRecorder...
[2025-05-30 09:58:25 TP9] Resetting ExpertDistributionRecorder...
[2025-05-30 09:58:27 TP13] [EPLBManager] rebalance end time=1.753s
[2025-05-30 09:58:27 TP14] [EPLBManager] rebalance end time=1.755s

@saltyfish66

saltyfish66 commented May 30, 2025 •

Copy link
Copy Markdown
Contributor Author

vanilla baseline: no redundant experts and rebalance
Launch command

python -u -m sglang.launch_server \
--model-path /sgl-workspace/DeepSeek-R1 \
--nnodes 2 --trust-remote-code  \
--served-model-name deepseek-r1 \
--dist-init-addr 29.226.64.238:5000 \
--node-rank ${NODE_RANK} \
--host 0.0.0.0 --port 8000 \
--tp 16 \
--node-rank ${NODE_RANK} \
--schedule-policy fcfs \
--chunked-prefill-size 32768 \
--max-prefill-tokens 32768 \
--disable-overlap-schedule \
--mem-fraction-static 0.70 \
--disable-radix-cache  \
--disable-cuda-graph \
--enable-deepep-moe --deepep-mode normal --ep-size 16

results:

max concurency 1
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  340.18    
Total input tokens:                      4066538   
Total generated tokens:                  300       
Request throughput (req/s):              0.88      
Output token throughput (tok/s):         0.88      
Total Token throughput (tok/s):          11954.86   (this pr 12662.88)
---------------Time to First Token----------------
Mean TTFT (ms):                          1133.48   
Median TTFT (ms):                        982.56    
P90 TTFT (ms):                           2163.42   
P99 TTFT (ms):                           2718.90   
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          1133.50   
Median E2EL (ms):                        982.57    
P90 E2EL (ms):                           2163.43   
P99 E2EL (ms):                           2718.92   
==================================================

max concurency 16
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  301.34    
Total input tokens:                      4066538   
Total generated tokens:                  300       
Request throughput (req/s):              1.00      
Output token throughput (tok/s):         1.00      
Total Token throughput (tok/s):          13495.77   (this pr 14366.96  )
---------------Time to First Token----------------
Mean TTFT (ms):                          15786.06  
Median TTFT (ms):                        15726.09  
P90 TTFT (ms):                           19971.40  
P99 TTFT (ms):                           22760.10  
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          15786.07  
Median E2EL (ms):                        15726.10  
P90 E2EL (ms):                           19971.41  
P99 E2EL (ms):                           22760.11  
==================================================

max concurency 300
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  301.93    
Total input tokens:                      4066538   
Total generated tokens:                  300       
Request throughput (req/s):              0.99      
Output token throughput (tok/s):         0.99      
Total Token throughput (tok/s):          13469.31   (this pr 14457.68  )
---------------Time to First Token----------------
Mean TTFT (ms):                          151614.28 
Median TTFT (ms):                        154486.82 
P90 TTFT (ms):                           276300.65 
P99 TTFT (ms):                           299486.47 
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          151614.29 
Median E2EL (ms):                        154486.83 
P90 E2EL (ms):                           276300.66 
P99 E2EL (ms):                           299486.48 
==================================================

@saltyfish66

Copy link
Copy Markdown
Contributor Author

Here are the performance data for static expert balancing:
launch command:


python -u -m sglang.launch_server \
--model-path /sgl-workspace/DeepSeek-R1 \
--nnodes 2 --trust-remote-code  \
--served-model-name deepseek-r1 \
--dist-init-addr 29.226.64.238:5000 \
--node-rank ${NODE_RANK} \
--host 0.0.0.0 --port 8000 \
--tp 16 \
--node-rank ${NODE_RANK} \
--schedule-policy fcfs \
--chunked-prefill-size 32768 \
--max-prefill-tokens 32768 \
--disable-overlap-schedule \
--mem-fraction-static 0.80 \
--disable-radix-cache  \
--disable-cuda-graph \
--enable-deepep-moe --deepep-mode normal --ep-size 16 \
--ep-num-redundant-experts 128 --ep-dispatch-algorithm dynamic \
--init-expert-location /geminicephfs/mm-base-tfcc/yuethe/projects/expert_distribution_recorder_1748615132.2225502.pt

Note that --ep-num-redundant-experts was lowered from 256 to 128 because when I set --ep-num-redundant-experts 256 I got an error:

[2025-05-30 14:52:23] INFO:     127.0.0.1:55540 - "POST /v1/chat/completions HTTP/1.1" 200 OK
[2025-05-30 14:52:23] INFO:     127.0.0.1:55544 - "POST /v1/chat/completions HTTP/1.1" 200 OK
[2025-05-30 14:52:24 TP0] Input length (24480 tokens) exceeds the maximum allowed length (19563 tokens). Use a shorter input or enable --allow-auto-truncate.
[2025-05-30 14:52:24 TP4] Input length (24480 tokens) exceeds the maximum allowed length (19563 tokens). Use a shorter input or enable --allow-auto-truncate.
[2025-05-30 14:52:24 TP0] Prefill batch. #new-seq: 4, #new-token: 18987, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 11
[2025-05-30 14:52:24 TP6] Input length (24480 tokens) exceeds the maximum allowed length (19563 tokens). Use a shorter input or enable --allow-auto-truncate.
[2025-05-30 14:52:24 TP2] Input length (24480 tokens) exceeds the maximum allowed length (19563 tokens). Use a shorter input or enable --allow-auto-truncate.
[2025-05-30 14:52:24 TP1] Input length (24480 tokens) exceeds the maximum allowed length (19563 tokens). Use a shorter input or enable --allow-auto-truncate.
[2025-05-30 14:52:24 TP5] Input length (24480 tokens) exceeds the maximum allowed length (19563 tokens). Use a shorter input or enable --allow-auto-truncate.
[2025-05-30 14:52:24 TP3] Input length (24480 tokens) exceeds the maximum allowed length (19563 tokens). Use a shorter input or enable --allow-auto-truncate.
[2025-05-30 14:52:24 TP7] Input length (24480 tokens) exceeds the maximum allowed length (19563 tokens). Use a shorter input or enable --allow-auto-truncate.
[2025-05-30 14:52:24] INFO:     127.0.0.1:55548 - "POST /v1/chat/completions HTTP/1.1" 200 OKs

This error will cause some test cases in the dataset to be ignored by the model.

benchmark data:

Maximum request concurrency: 1
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 300/300 [05:23<00:00,  1.08s/it]
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  323.76    
Total input tokens:                      4066468   
Total generated tokens:                  300       
Request throughput (req/s):              0.93      
Output token throughput (tok/s):         0.93      
Total Token throughput (tok/s):          12561.22   (this pr 12662.88)
---------------Time to First Token----------------
Mean TTFT (ms):                          1078.73   
Median TTFT (ms):                        931.39    
P90 TTFT (ms):                           2003.38   
P99 TTFT (ms):                           2609.54   
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          1078.75   
Median E2EL (ms):                        931.41    
P90 E2EL (ms):                           2003.40   
P99 E2EL (ms):                           2609.55   
==================================================
Maximum request concurrency: 16
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 300/300 [04:41<00:00,  1.07it/s]
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  281.69    
Total input tokens:                      4066468   
Total generated tokens:                  300       
Request throughput (req/s):              1.07      
Output token throughput (tok/s):         1.07      
Total Token throughput (tok/s):          14437.25  (this pr 14366.96  )
---------------Time to First Token----------------
Mean TTFT (ms):                          14752.89  
Median TTFT (ms):                        14715.87  
P90 TTFT (ms):                           18664.37  
P99 TTFT (ms):                           21847.13  
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          14752.91  
Median E2EL (ms):                        14715.89  
P90 E2EL (ms):                           18664.38  
P99 E2EL (ms):                           21847.14  
==================================================
Maximum request concurrency: 300
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 300/300 [04:46<00:00,  1.05it/s]
============ Serving Benchmark Result ============
Successful requests:                     300       
Benchmark duration (s):                  286.23    
Total input tokens:                      4066468   
Total generated tokens:                  300       
Request throughput (req/s):              1.05      
Output token throughput (tok/s):         1.05      
Total Token throughput (tok/s):          14208.28  (this pr 14457.68  )
---------------Time to First Token----------------
Mean TTFT (ms):                          141337.86 
Median TTFT (ms):                        143017.46 
P90 TTFT (ms):                           262029.85 
P99 TTFT (ms):                           283894.49 
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          0.00      
Median TPOT (ms):                        0.00      
P90 TPOT (ms):                           0.00      
P99 TPOT (ms):                           0.00      
---------------Inter-token Latency----------------
Mean ITL (ms):                           0.00      
Median ITL (ms):                         0.00      
P90 ITL (ms):                            0.00      
P99 ITL (ms):                            0.00      
----------------End-to-end Latency----------------
Mean E2EL (ms):                          141337.87 
Median E2EL (ms):                        143017.47 
P90 E2EL (ms):                           262029.87 
P99 E2EL (ms):                           283894.51 
==================================================

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Thank you, @saltyfish66, for providing these comprehensive benchmark results comparing your proposed balance dispatch algorithm against the existing dynamic and static EPLB methods, as well as a vanilla baseline.

These results are very helpful in understanding the performance characteristics of the different approaches on your specific dataset, especially focusing on the prefill stage for long prompts, which is the primary target of this PR.

Here's a summary of the Total Token throughput (tok/s) across the different methods and concurrency levels based on the data you provided:

Concurrency Vanilla Baseline Static EPLB (128 experts) Dynamic EPLB (128 experts) This PR (Balance, 256 experts)
1 11954.86 12561.22 12680.13 12284.14 (256 experts) / 12662.88 (256 experts)
16 13495.77 14437.25 14606.62 13819.14 (256 experts) / 14366.96 (256 experts)
300 (offline) 13469.31 14208.28 14659.47 13927.41 (256 experts) / 14457.68 (256 experts)

(Note: For concurrency 1, 16, and 300, I've included both baseline and balance results from your initial comment (Comment 2) which used 256 redundant experts, and compared them against the static/dynamic results from Comments 4 and 6 which used 128 redundant experts due to OOM issues.)

Key observations from the data:

  1. Vanilla Baseline: As expected, the vanilla baseline (no redundant experts, no rebalance) shows the lowest throughput across all concurrency levels.
  2. Static/Dynamic EPLB (128 experts): Both static and dynamic EPLB at 128 redundant experts show improved throughput compared to the vanilla baseline. Dynamic EPLB seems slightly better than static at higher concurrency.
  3. This PR (Balance, 256 experts): Your balance method with 256 redundant experts shows throughput numbers that are competitive with, and in some cases slightly higher than, the static/dynamic EPLB tested at 128 redundant experts. This is particularly notable given the higher number of redundant experts used in your PR's tests.
  4. OOM with 256 experts: The OOM error you encountered when trying to run static/dynamic EPLB with 256 redundant experts highlights a potential memory trade-off with those methods compared to your balance approach, at least with the current implementation.
  5. Rebalance Time: The server logs showing rebalance times of ~1.8 seconds for dynamic EPLB reinforce your point about potential stability concerns and stop-the-world pauses for methods relying on hot updates, especially for services with strict SLOs.

Overall, the benchmarks support your motivation for this PR: providing a balance dispatch algorithm that leverages redundant experts for load balancing, offering a performance improvement over the vanilla baseline, and serving as a viable option for users prioritizing stability over dynamic rebalancing, particularly in prefill-heavy workloads with long contexts.

Thank you again for the detailed explanation and the benchmark data!

@fzyzcjy

fzyzcjy commented Jun 2, 2025 •

Copy link
Copy Markdown
Collaborator
  • "The dataset contains 300 prompts ... an average length of 14k tokens" - then looks like it can only fill 8 full batches if we use deepseek blog's settings (4 nodes and 16k tok per forward pass). Looks like a bit small since I personally think EPLB rebalance period may not be this frequent. But anyway this can be used as an approximate indicator.
  • "According to the server log, each expert rebalance takes about 1.8 seconds" - btw it should not stop the server for this long time (if that is bad to users) and I can optimize it later. And, 2 nodes is quite few and thus we need to copy a lot of weights and thus slow.
  • The results are interesting, both static and dynamic eplb only slightly improve compared with vanilla baseline. I am wondering whether it is because configurations, e.g. num redundant experts, etc. Also maybe check balancedness metrics to see how it improves. Also maybe use --init-expert-location with collected metrics as an estimated upper bound to debug. (optional, you can skip it if in a hurry, just being curious)
  • About the PR, as is mentioned above, I think it is good to merge it to provide more choices for users (code needs review and change some nits though but mainly trivial changes).

@saltyfish66
saltyfish66 force-pushed the balance-dispatch branch 3 times, most recently from c99a366 to 4ca60db Compare June 4, 2025 08:41
@saltyfish66

saltyfish66 commented Jun 4, 2025 •

Copy link
Copy Markdown
Contributor Author

"The results are interesting, both static and dynamic eplb only slightly improve compared with vanilla baseline."
First, let's explore where the theoretical performance ceiling is.

I modified some codes in _topk_ids_logical_to_physical_static to ensure that the topk_ids are perfectly balanced. After this modification, since the logical topk_ids is perfectly balanced, the model should reach the performance ceiling of using deepep.

_cached_selected_topk_idx = None

def _topk_ids_logical_to_physical_static(
    topk_ids: torch.Tensor, info: Optional[ExpertLocationDispatchInfo]
) -> torch.Tensor:
    global _cached_selected_topk_idx
    # topk_idx.shape = [num_token, 8], num_token是当前卡上的token数量
    if _cached_selected_topk_idx is None:
        _cached_selected_topk_idx = [(i % 256) for i in range(32768 * 8)] # 256 means num_logical_experts
        _cached_selected_topk_idx = torch.tensor(_cached_selected_topk_idx, dtype=torch.int, device=topk_ids.device)
        _cached_selected_topk_idx = _cached_selected_topk_idx.reshape(32768, 8).contiguous()
    
    assert len(topk_ids.shape) == 2 and topk_ids.shape[1] == 8, f"{topk_ids.shape=}"
    topk_ids = _cached_selected_topk_idx.narrow(0, 0, topk_ids.shape[0])
    return info.partial_logical_to_rank_dispatch_physical_map[topk_ids]

The topk_ids output by the function is wrong, but we don't care.
Then, launch server by.

python -u -m sglang.launch_server \
--model-path /sgl-workspace/DeepSeek-R1 \
--nnodes 2 --trust-remote-code  \
--served-model-name deepseek-r1 \
--dist-init-addr 29.226.64.238:5000 \
--node-rank ${NODE_RANK} \
--host 0.0.0.0 --port 8000 \
--tp 16 \
--node-rank ${NODE_RANK} \
--schedule-policy fcfs \
--chunked-prefill-size 32768 \
--max-prefill-tokens 32768 \
--disable-overlap-schedule \
--mem-fraction-static 0.90 \
--disable-radix-cache  \
--disable-cuda-graph \
--enable-deepep-moe --deepep-mode normal --ep-size 16 \
--ep-num-redundant-experts ... --ep-dispatch-algorithm static

Benchmark results on the dataset with 300 prompts:

set --ep-num-redundant-experts 0: (theoretical performance ceiling)
max concurrency 1:  13666.51 token/s
max concurrency 16:  15729.88  token/s
max concurrency 300:     15803.76 token/s

set --ep-num-redundant-experts 256:
max concurrency 1:13427.49 token/s
max concurrency 16:15405.14  token/s
max concurrency 300:15442.97  token/s

When --ep-num-redundant-experts 256 is used, the server throughput will be slightly reduced(compared with --ep-num-redundant-experts 0) because more expert weights need to be loaded during the deepgemm calculation in MOE part.

Then, we explore practical throughput ceil.

python -u -m sglang.launch_server \
--model-path /sgl-workspace/DeepSeek-R1 \
--nnodes 2 --trust-remote-code  \
--served-model-name deepseek-r1 \
--dist-init-addr 29.226.64.238:5000 \
--node-rank ${NODE_RANK} \
--host 0.0.0.0 --port 8000 \
--tp 16 \
--node-rank ${NODE_RANK} \
--schedule-policy fcfs \
--chunked-prefill-size 32768 \
--max-prefill-tokens 32768 \
--disable-overlap-schedule \
--mem-fraction-static 0.70 \
--disable-radix-cache  \
--disable-cuda-graph \
--enable-deepep-moe --deepep-mode normal --ep-size 16 \
--ep-num-redundant-experts ... --ep-dispatch-algorithm dynamic \
--enable-eplb --eplb-rebalance-num-iterations 400

Before starting the benchmark, warm up the expert rebalance function multiple times using all the data in the dataset (and make sure that we saw "expert rebalance" in the logs).
Set --eplb-rebalance-num-iterations 400(>num_prompts in dataset), this means that when rebalancing experts, we already recorded the expert distributions of all the data in the dataset(achieved similar effects as using --init-expert-location).
The benchmark result is shown as bellow.

set --ep-num-redundant-experts 16:
max concurrency 1:  12401.58 (90.7% of the theoretical ceil: 13666.51 token/s)
max concurrency 16:  14683.89 (93.3% of the theoretical  ceil: 15729.88  token/s)
max concurrency 300:     14448.92 (91.4% of the theoretical  ceil: 15803.76 token/s)

set --ep-num-redundant-experts 128:
max concurrency 1:  12655.09 (92.5% of the theoretical ceil: 13666.51 token/s)
max concurrency 16:  14824.93 (94.2% of the theoretical ceil: 15729.88  token/s)
max concurrency 300:     14785.44 (93.6% of the theoretical ceil: 15803.76 token/s)

If I have enough CUDA memory to set --ep-num-redundant-experts 256, perhaps we can reach the theoretical performance ceiling of around 95%, which I think is really high.

this pr:
max concurrency 1:12662.88 (92.6% of the theoretical ceil: 13666.51 token/s)
max concurrency 16:14366.96 (91.3% of the theoretical ceil: 15729.88 token/s)
max concurrency 300:14457.68 (91.5% of the theoretical ceil: 15803.76 token/s)
Without knowing any prior information about the expert distributions in dataset, we can achieve a performance ceiling of around 92~93%, which I think has met expectations.

@fzyzcjy fzyzcjy mentioned this pull request Jun 5, 2025
6 tasks
@saltyfish66

Copy link
Copy Markdown
Contributor Author

@fzyzcjy Hi, may I ask if this PR has any progress related to code review?
btw, thanks for your #6895

@fzyzcjy

fzyzcjy commented Jun 10, 2025

Copy link
Copy Markdown
Collaborator

@saltyfish66 too busy recently :(

@saltyfish66
saltyfish66 force-pushed the balance-dispatch branch 5 times, most recently from 4475e4d to 9287f0e Compare June 12, 2025 11:15
@saltyfish66
saltyfish66 requested a review from HaiShaw as a code owner June 12, 2025 11:15
@hnyls2002

Copy link
Copy Markdown
Collaborator

@saltyfish66, any updates?

@github-actions

Copy link
Copy Markdown
Contributor

Thanks @saltyfish66. Closing this because it has had no updates in 257 days.

Reopen it if the work is still relevant.

Some directories moved recently, so an older branch may need retargeting:
sgl-kernel/ -> python/sglang/kernels/aot/, python/sglang/jit_kernel/
-> python/sglang/kernels/jit/, docs/ -> docs/docs/ (.mdx),
bench_serving.py -> benchmark/serving.py, test/srt/ -> test/registered/.

@github-actions github-actions Bot closed this Aug 14, 2026
yyihuang pushed a commit to yyihuang/sglang that referenced this pull request Oct 19, 2026
…merge commit 816db6625da0 (round 9)

Move the FlashInfer contract pin from f41bfa18fcee (PR sgl-project#6746 merge,
round 8) to 816db6625da0, the merge commit of PR sgl-project#6775 (round 9),
which follows PR sgl-project#6739 (2c8f0e38f763).

python/sglang/kernels/cake_kernels/mamba.py: the contract paragraph
now describes what changed on the FlashInfer side between the two
pins (every statement checked against the loader at 816db6625da0 and
the two PR descriptions):
- Round 9 (PR sgl-project#6775), sm_107a (Rubin) only: the 13 varlen exact-scan
  programs are re-exported with the input stage passing each chunk's
  segment bounds to the consumer roles instead of a chunk-table
  reload; a two-kernel call whose balanced persistent grid is already
  the full device takes the tail-wave pair programs under a
  Rubin-measured rule (chunk floor 16 batched / 8 varlen; the pair
  makespan grown by the pair render's penalty plus the split item's
  hand-off step must stay below the persistent program's item waves;
  Blackwell never routes a full grid to the pair); the chunk-parallel
  workspace cap is 512 MiB on capability (10, 7) (256 MiB elsewhere).
  The sm_100a / sm_103a programs are byte-identical to round 8.
- PR sgl-project#6739: the nine _noring device sources no route selects (the
  two-kernel family's twins and the FP32 varlen ones) and their loader
  entries are gone, the two-kernel programs render the fused host
  launcher (the same two launches), and the selective-state-update
  stp_paired_rows_mb4 clone is folded into stp_paired_rows with a
  LAUNCH_MIN_BLOCKS define. No kernel of a kept program changes; the
  routes this adapter relies on (fused window, _noring windows,
  two-kernel family, promoted selective-state-update rows) are
  unchanged.
This adapter keeps admitting sm_100a / sm_103a only (ARCHS unchanged).

test/registered/kernels/ops/mamba/test_cake_ssd_combined.py:
unchanged. The pinned-family bitwise clause still closes the fused
window through fused_selected, which both PRs keep; the full-grid pair
rule exists only for capability (10, 7).

Tests against FlashInfer 816db6625da0:
- test/registered/unit/kernels/test_cake_mamba_sp_routes.py:
  47 passed (CPU, on x86_64 and on aarch64).
- test/registered/kernels/ops/mamba/test_cake_ssd_combined.py:
  42 passed on B200 (sm_100a) and 42 passed on GB300 (sm_103a).

Routing of this adapter and its public contract
(supports_ssd_combined, ssd_combined_fwd, run, prepare) are
unchanged.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
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.

4 participants