Skip to content

[Frontend] optimize beam_search code #19267

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 1 commit into
base: main
Choose a base branch
from

Conversation

zhanggzh
Copy link

@zhanggzh zhanggzh commented Jun 6, 2025

Purpose

In the source code of vllm's beam_search, a two-fold loop is used that will splice the generated tokens and compute the cumulative probabilities This splicing operation takes essentially the same order of magnitude of time as each execution of generate.

Code:

Time-Consuming:

Optimize the above logic into the following code, using sorting and then splicing to reduce the time complexity.

Test Plan

Set request parameters:

payload = {
    "model": MODEL,
    "messages": [
      {
        "role": "user",
        "content": prompt
      }
    ],
    "use_beam_search": True,
    "n": 30,
    "max_tokens": 8
}

Test Result

Copy link
Contributor

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

Choose a reason for hiding this comment

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

Hello @zhanggzh, 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! Gemini here, providing a summary of this pull request to help everyone get up to speed quickly.

This PR, titled "[Frontend] optimize beam_search code", aims to improve the performance of the beam search implementation within vLLM. According to the author, the previous approach involved a two-fold loop for processing generated tokens and computing cumulative probabilities, which included splicing operations that were computationally expensive, sometimes taking as much time as the generation step itself. The goal is to optimize this logic using sorting and splicing with NumPy to reduce time complexity.

The core changes involve refactoring the token processing loop within the beam_search function in vllm/engine/protocol.py. Instead of iterating through each beam and its generated tokens individually to build a new list of potential beams, the updated code collects all potential next tokens and their cumulative log probabilities into NumPy arrays. It then handles EOS tokens separately by identifying them using NumPy indexing and adding completed beams. For non-EOS tokens, it uses np.argpartition to efficiently find the indices corresponding to the top beam_width cumulative probabilities across all candidates, and then constructs the next set of beams from these top candidates. This replaces the previous approach of appending to a list and then sorting the entire list.

Highlights

  • Performance Optimization: The primary goal of this PR is to optimize the beam search algorithm's performance by improving the efficiency of processing generated tokens and calculating cumulative probabilities.
  • Beam Search Logic Refactor: The logic for selecting the top beams in each step of the beam search has been refactored to use NumPy operations (np.array, np.where, np.argpartition) for collecting, filtering (EOS), and selecting the top candidates based on cumulative log probabilities.
  • Reduced Time Complexity: The author states that the previous two-fold loop with splicing was time-consuming and that the new approach using sorting/partitioning is intended to reduce the time complexity of this step.

Changelog

  • vllm/engine/protocol.py
    • Added import for the numpy library.
    • Introduced a variable logprobs_num to explicitly store the required number of log probabilities (2 * beam_width).
    • Replaced the nested loop structure for processing beam outputs with a new logic that collects all potential next tokens and their cumulative log probabilities into NumPy arrays.
    • Implemented separate handling for End-of-Sentence (EOS) tokens using np.where to identify and finalize completed beams.
    • Used np.argpartition to efficiently find the indices of the top beam_width non-EOS candidates based on cumulative log probabilities.
    • Constructed the next set of active beams (new_beams) by iterating through the indices of the top candidates identified by np.argpartition.
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
Contributor

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

Choose a reason for hiding this comment

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

Code Review

The PR aims to optimize the beam search implementation, and the performance gains shown are promising. However, there are a couple of critical concerns regarding the correctness of the refactored logic for beam pruning and indexing that need to be addressed. Specifically, the handling of variable numbers of logprobs per beam and the change in criteria for pruning active beams (not using length penalty) could lead to different results compared to the original implementation.

Summary of Findings

  • Correctness of Beam Indexing: The method for mapping flattened indices back to original beam indices (idx // logprobs_num) might be incorrect if beams contribute a variable number of logprobs or if some beams have no logprobs. This could lead to incorrect beam propagation.
  • Beam Pruning Criterion Changed: The new beam pruning logic uses raw cumulative log probabilities, whereas the original implementation used a length-penalized score (sort_beams_key). This change in criterion can alter the set of active beams and potentially the final output of the beam search.
  • Comment Style: Minor inconsistency in comment style (double hash ## vs single hash #).

Merge Readiness

The optimization approach is promising for performance, but the identified critical issues regarding the correctness of beam indexing and the change in beam pruning criteria need to be addressed before this PR can be merged. I am unable to approve this pull request in its current state. Please ensure these points are resolved, and further testing might be beneficial to confirm behavioral equivalence with the original logic under various conditions (especially different length_penalty values).

Comment on lines +166 to +167
current_beam = all_beams[idx // logprobs_num]
result = output[idx // logprobs_num]
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The indexing idx // logprobs_num to retrieve current_beam and result assumes that each beam processed in the loop from line 151 consistently contributes logprobs_num items to all_beams_token_id and all_beams_logprob.

However, if result.outputs[0].logprobs is None (handled by the if on line 153) or if the logprobs dictionary contains fewer than logprobs_num items for some beams, the flattened arrays will not have a uniform structure. This would make idx // logprobs_num an incorrect way to map back to the original beam index for beams that appear after an irregularly sized or skipped beam.

Could you clarify if len(logprobs.keys()) is guaranteed to be logprobs_num for all beams that have logprobs? If not, this indexing could lead to incorrect beam assignments.

A more robust approach might involve storing the original beam index alongside each token and logprob when creating the flattened arrays, and then using that stored index. For example:

# When populating the lists:
all_beams_original_indices = []
for i, result in enumerate(output):
    current_beam = all_beams[i]
    if result.outputs[0].logprobs is not None:
        logprobs = result.outputs[0].logprobs[0]
        num_candidates_for_this_beam = len(logprobs.keys())
        all_beams_token_id.extend(list(logprobs.keys()))
        all_beams_logprob.extend([...])
        all_beams_original_indices.extend([i] * num_candidates_for_this_beam)

# Then, when retrieving:
original_beam_idx = all_beams_original_indices[idx]
current_beam = all_beams[original_beam_idx]
result = output[original_beam_idx]

Comment on lines +183 to +201
topn_idx = np.argpartition(-all_beams_logprob, beam_width)[:beam_width]

for idx in topn_idx:
current_beam = all_beams[idx // logprobs_num]
result = output[idx // logprobs_num]
token_id = int(all_beams_token_id[idx])
new_beams.append(
BeamSearchSequence(
tokens=current_beam.tokens + [token_id],
logprobs=current_beam.logprobs +
[result.outputs[0].logprobs[0]],
lora_request=current_beam.lora_request,
cum_logprob=float(all_beams_logprob[idx]),
multi_modal_data=current_beam.
multi_modal_data,
mm_processor_kwargs=current_beam.
mm_processor_kwargs))

all_beams = new_beams
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The beam pruning logic has changed. The original code (lines 176-177 in the 'before' view) used sorted(new_beams, key=sort_beams_key, reverse=True) to select the top beam_width beams for the next iteration. The sort_beams_key incorporates a length_penalty.

The new logic (line 183) uses np.argpartition(-all_beams_logprob, beam_width) to select the top beams. However, all_beams_logprob (calculated on line 156) contains raw cumulative log probabilities (current_beam.cum_logprob + logprob_obj.logprob) and does not include the length penalty.

This means that active beams are now pruned based on a different criterion (raw log probability) than what sort_beams_key (length-penalized score) would use. This is a significant change in the beam search behavior and could lead to different outcomes, especially if length_penalty is not 1.0.

Was this change in pruning criteria intentional? If the goal is to maintain the same beam search behavior while optimizing, the np.argpartition should operate on scores calculated using the length_penalty, similar to how sort_beams_key works.

Copy link

github-actions bot commented Jun 6, 2025

👋 Hi! Thank you for contributing to the vLLM project.

💬 Join our developer Slack at https://slack.vllm.ai to discuss your PR in #pr-reviews, coordinate on features in #feat- channels, or join special interest groups in #sig- channels.

Just a reminder: PRs would not trigger full CI run by default. Instead, it would only run fastcheck CI which starts running only a small and essential subset of CI tests to quickly catch errors. You can run other CI tests on top of those by going to your fastcheck build on Buildkite UI (linked in the PR checks section) and unblock them. If you do not have permission to unblock, ping simon-mo or khluu to add you in our Buildkite org.

Once the PR is approved and ready to go, your PR reviewer(s) can run CI to test the changes comprehensively before merging.

To run CI, PR reviewers can either: Add ready label to the PR or enable auto-merge.

🚀

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