Skip to content

Add fake balance for EP mode #962

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open

Add fake balance for EP mode #962

wants to merge 3 commits into from

Conversation

STwangyingrui
Copy link
Collaborator

Add fake balance for EP mode, which is controled by option of --enable_ep_fake_balance.
Cost: EP8 batch128 input64 (40+ different seqlens) totally cost about 5 seconds.
Benefit: prefill throughput increase 35%, decoding throughput increase 15%, and the overheads become stable.

baishihao added 2 commits July 7, 2025 17:44
more robust balance management, from env control to option control, better logger info control, better format
Copy link

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

Choose a reason for hiding this comment

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

Summary of Changes

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

This pull request introduces an experimental feature to improve the performance and stability of Expert Parallelism (EP) mode by implementing a 'fake balance' strategy for expert selection. This strategy, enabled via a new command-line flag, aims to distribute the workload more evenly across experts, leading to notable gains in both prefill and decoding throughput.

Highlights

  • New Feature: Expert Balancing for EP Mode: Introduced a 'fake balance' mechanism specifically for Expert Parallelism (EP) mode. This aims to improve throughput and stabilize overheads by artificially balancing the distribution of tokens to experts.
  • Configurable via Command Line: The new fake balance feature is controlled by a new command-line argument, --enable_ep_fake_balance, allowing users to enable or disable this optimization.
  • Performance Improvements: Enabling this feature is reported to significantly increase prefill throughput by 35% and decoding throughput by 15%, while also stabilizing overheads.
  • Expert Assignment Override: When enabled, the system will override the dynamically selected top-k experts with a pre-generated, balanced distribution of expert IDs, ensuring a more even load across experts.
  • Conditional Logging for Debugging: Added logging in both prefill and decode stages to show the distribution of tokens to experts when the fake balance is active. Note that decode stage logging is only active when cudagraph is disabled.
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.

Footnotes

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

Copy link

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

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a "fake balance" mode for expert parallelism. My main feedback is on the performance of the generate_balanced_tensor function in lightllm/utils/balance_utils.py. The current implementation has a performance bottleneck that can be addressed with a more efficient approach. I've provided a code suggestion for this improvement.

Comment on lines 38 to 61
tensor = torch.zeros((num_tokens, self.num_selected), dtype=torch.int, device="cuda")
expert_load = torch.zeros(self.num_experts, dtype=torch.int, device="cuda")

for i in range(num_tokens):
available_experts = torch.arange(self.num_experts, device="cuda")
selected = []
for _ in range(self.num_selected):
current_load = expert_load[available_experts]
min_load_indices = torch.where(current_load == current_load.min())[0]
if len(min_load_indices) > 1:
# If there are multiple least-loaded experts, select one randomly
chosen_index = torch.randint(0, len(min_load_indices), (1,), device="cuda").item()
chosen_expert_index = min_load_indices[chosen_index]
else:
chosen_expert_index = min_load_indices[0]
chosen_expert = available_experts[chosen_expert_index]
selected.append(chosen_expert)
# Remove the selected expert from the list of available experts
available_experts = torch.cat(
[available_experts[:chosen_expert_index], available_experts[chosen_expert_index + 1 :]]
)
expert_load[chosen_expert] += 1

tensor[i] = torch.tensor(selected, dtype=torch.int, device="cuda")

Choose a reason for hiding this comment

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

high

The current implementation of generate_balanced_tensor is inefficient due to the use of torch.cat inside a loop. This creates a new tensor and copies data in every iteration, which can be slow for large num_tokens or num_experts. A more performant approach would be to use a boolean mask to keep track of selected experts, avoiding the expensive torch.cat operation. This can significantly reduce the overhead.

        tensor = torch.empty((num_tokens, self.num_selected), dtype=torch.int, device="cuda")
        expert_load = torch.zeros(self.num_experts, dtype=torch.int, device="cuda")

        for i in range(num_tokens):
            selected_mask = torch.zeros(self.num_experts, dtype=torch.bool, device="cuda")
            for j in range(self.num_selected):
                # Use a large value for already selected experts to exclude them
                load_view = torch.where(selected_mask, torch.iinfo(expert_load.dtype).max, expert_load)

                min_load_indices = torch.where(load_view == load_view.min())[0]

                if len(min_load_indices) > 1:
                    # If there are multiple least-loaded experts, select one randomly
                    rand_idx = torch.randint(0, len(min_load_indices), (1,), device="cuda").item()
                    chosen_expert = min_load_indices[rand_idx]
                else:
                    chosen_expert = min_load_indices[0]

                tensor[i, j] = chosen_expert
                expert_load[chosen_expert] += 1
                selected_mask[chosen_expert] = True

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.

1 participant