Repository navigation
feat: add "balance" option and implement for "--ep-dispatch-algorithm" - #6739
saltyfish66 wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
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
balanceoption to the--ep-dispatch-algorithmfor 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 thesgl-kernelmodule. - Performance Improvement: Demonstrates 6-8% throughput improvement during the prefill stage compared to the
staticdispatch algorithm, particularly for larger prompt lengths. - Decode Stage Handling: Includes a fallback to the
staticalgorithm for small token counts (typical in decode) to avoid overhead, acknowledging that thebalancealgorithm 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_trivialto handle thebalancedispatch algorithm, ensuring physical experts are mapped to logical experts in a way compatible with the new balancing logic when--ep-dispatch-algorithm balanceis used (lines 90-109). - Added an assertion to ensure
num_physical_expertsis a multiple ofnum_logical_expertsfor thebalancealgorithm (lines 91-93).
- Modified
- python/sglang/srt/managers/expert_location_dispatch.py
- Added
balanceto theLiteraltype hint forep_dispatch_algorithmin theExpertLocationDispatchInfodataclass (line 26). - Added
ep_sizefield to theExpertLocationDispatchInfodataclass (line 34). - Passed
ep_sizewhen initializingExpertLocationDispatchInfo(line 56). - Added a conditional branch in
topk_ids_logical_to_physicalto call the new_topk_ids_logical_to_physical_balancefunction when the algorithm isbalance(lines 82-83). - Implemented the
_topk_ids_logical_to_physical_balancefunction, which calls thebalance_topk_idskernel fromsgl_kerneland includes a fallback tostaticdispatch for small token counts (<= 32) (lines 110-143).
- Added
- python/sglang/srt/server_args.py
- Added
balanceas a valid option for theep_dispatch_algorithmcommand-line argument (lines 175-177).
- Added
- sgl-kernel/CMakeLists.txt
- Added the new CUDA source file
csrc/moe/balance_topk_ids.cuto the list of sources to be compiled (line 227).
- Added the new CUDA source file
- sgl-kernel/csrc/common_extension.cc
- Registered the new CUDA function
balance_topk_idswith the PyTorch extension mechanism (lines 163-166).
- Registered the new CUDA function
- sgl-kernel/csrc/moe/balance_topk_ids.cu
- Added the CUDA kernel implementation for the
balance_topk_idsfunction, including kernels for counting workloads (gpu_workloads_count_kernel), searching for the optimal balance mapping (search_balance_mapping_kernel), and rewritingtopk_idsbased on the mapping (rewrite_topk_ids_by_balance_mapping_kernel) (lines 1-415).
- Added the CUDA kernel implementation for the
- sgl-kernel/include/sgl_kernel_ops.h
- Declared the C++ function signature for
balance_topk_ids(lines 243-250).
- Declared the C++ function signature for
- sgl-kernel/python/sgl_kernel/init.py
- Imported the
balance_topk_idsfunction from thesgl_kernel.moemodule (line 49).
- Imported the
- sgl-kernel/python/sgl_kernel/moe.py
- Defined the Python wrapper function
balance_topk_idsthat calls the registered C++ CUDA function (lines 131-148).
- Defined the Python wrapper function
- sgl-kernel/tests/test_balance_topk_ids.py
- Added a new test file with a parameterized test function
test_balance_topk_idsto verify the correctness of thebalance_topk_idsCUDA kernel (lines 1-94).
- Added a new test file with a parameterized test function
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
-
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. ↩
There was a problem hiding this comment.
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_expertsmust be a multiple ofnum_logical_experts, andnum_logical_expertsmust be a multiple ofep_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.cudefines a constantMAX_EXPERT_COPIES_MULTIPLE = 8. There is no runtime check to ensure thatnum_physical_experts / num_logical_expertsdoes not exceed this. This could lead to out-of-bounds shared memory access if a user configures high expert redundancy. ATORCH_CHECKshould 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 balanceoption 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.
There was a problem hiding this comment.
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.
e29fd0b to
1093966
Compare
|
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. Some thoughts:
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:
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.
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: 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. As you mentioned, the throughput improvement is closely related to the specific data set. |
|
Hi,
|
Thanks for your reply. I don't know much about expert rebalance. Thanks for your explanation. Launch command(adapted from #6017) Notice that I have to decrease We first ran the entire dataset on the server to warm up the expert rebalance. benchmark results: some server log |
|
vanilla baseline: no redundant experts and rebalance results: |
|
Here are the performance data for static expert balancing: Note that This error will cause some test cases in the dataset to be ignored by the model. benchmark data: |
|
Thank you, @saltyfish66, for providing these comprehensive benchmark results comparing your proposed 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:
(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:
Overall, the benchmarks support your motivation for this PR: providing a Thank you again for the detailed explanation and the benchmark data! |
|
c99a366 to
4ca60db
Compare
|
"The results are interesting, both static and dynamic eplb only slightly improve compared with vanilla baseline." I modified some codes in The topk_ids output by the function is wrong, but we don't care. Benchmark results on the dataset with 300 prompts: When Then, we explore practical throughput ceil. 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). If I have enough CUDA memory to set this pr: |
4ca60db to
9f342f1
Compare
9f342f1 to
ab048c6
Compare
|
@saltyfish66 too busy recently :( |
4475e4d to
9287f0e
Compare
9287f0e to
aff32c4
Compare
aff32c4 to
14947cc
Compare
|
@saltyfish66, any updates? |
|
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: |
…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]>
Motivation
When enabling
--enable-deepep-moe --deepep-mode normal, I usednsysto 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 thecache_notifykernel for synchronization before proceeding to token combination.Although
sglanghas introduced features like--eplb-rebalance-num-iterationsto 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-expertsto introduce redundancy among experts to balance the workload on each GPU.However, I found that the existing
--ep-dispatch-algorithmdoes 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
balanceoption for--ep-dispatch-algorithmand 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_idsfrom all GPUs for global workload balancing is difficult, our approach focuses on local balancing per GPU: each GPU analyzes its owntopk_idsand 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. Definex = max(x_1, x_2, ..., x_n). The smallerxis, the more balanced the workload.However, solving for the exact
xrequires a dynamic programming-like approach with high overhead. Instead, we approximatexby 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
xis 1024 / 2 = 512 (all tokens dispatched to only 2 GPUs), and the lower bound is1024 / 16 = 64(perfect balance).We search for an approximate
x'within this range by incrementing in strides (e.g., start withx' = 64, check feasibility; if not feasible, increasex'by 16(search stride) and repeat until a feasible solution is found).Finally, we rewrite the
topk_idsbased on the foundx'to achieve balanced token dispatch.Comparation
baseline launch command:
balanced launch command: similar to baseline launch, change
--ep-dispatch-algorithm staticto--ep-dispatch-algorithm balanceCorrectness
benchmark
benchmark on 2x8xH20.
prefill stage (6~8% throughput improvement)
prompt len = 14k, 8.4% throughput improvement
prompt len = 16384, 6.18% throughput improvement
prompt len = 10240, 6.15% throughput improvement
prompt len = 4096, 7.4% throughput improvement
decode stage(2.3% throughput reduction)
Note that:
When the number of tokens is small, the
balancedispatch algorithm will be downgraded to astaticdispatch algorithm to avoid the additional overhead brought by thebalancealgorithm.Actually,
balancealgorithm 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 normalis used here, setting-deepep-mode=auto/low_latencywill cause program errors (bothbaselineandbalance)Algorithm restriction
For deepseek-671B (which has 256 routed_experts),
--ep-num-redundant-expertscan only be set to a multiple of 256.Checklist