Skip to content

Conversation

@wangxiyuan
Copy link
Contributor

@wangxiyuan wangxiyuan commented Jul 14, 2025

Essential Elements of an Effective PR Description Checklist

  • The purpose of the PR, such as "Fix some issue (link existing issues this PR will resolve)".
  • The test plan, such as providing test command.
  • The test results, such as pasting the results comparison before and after, or e2e results
  • (Optional) The necessary documentation update, such as updating supported_models.md and examples for a new model.

Purpose

When vLLM is setup by called from vllm import LLM, SamplingParams, a lots of useless import is called. One main step is from vllm.model_executor.models.utils import extract_layer_index in vllm.v1.utils. It will import much files in model_executor which won't be used in process0.

This PR move bind_kv_cache to vllm.v1.worker.utils to skip useless import when initialize LLM.

Test Plan

Just a code cleanup. No new test is needed.

Test Result

All test should pass

(Optional) Documentation Update

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.

Summary of Changes

Hello @wangxiyuan, 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 focuses on optimizing the vLLM initialization process by strategically relocating the bind_kv_cache function. By moving this function and its associated model_executor dependencies from a general utility module to a worker-specific one, the PR aims to prevent the loading of unnecessary modules during the initial LLM import, thereby improving startup efficiency.

Highlights

  • Code Relocation: The bind_kv_cache function, along with its related imports, has been moved from vllm/v1/utils.py to vllm/v1/worker/utils.py.
  • Import Optimization: This refactoring allows for the removal of model_executor related imports (such as extract_layer_index and Attention type hints) from the general vllm.v1.utils module. These dependencies are now only loaded within the worker context where bind_kv_cache is actually utilized.
  • Startup Performance Improvement: The primary benefit of this change is to reduce unnecessary module imports during the initial LLM setup, which is expected to lead to a leaner and potentially faster initialization of process0.
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.

@mergify mergify bot added v1 tpu Related to Google TPUs labels Jul 14, 2025
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

This pull request refactors the bind_kv_cache function by moving it from vllm.v1.utils to vllm.v1.worker.utils, improving import efficiency. I've identified one area for improvement in the newly moved function to enhance its API and efficiency for one of its callers. My feedback is focused on making runner_kv_caches an optional parameter.

Comment on lines +120 to +162
def bind_kv_cache(
kv_caches: dict[str, torch.Tensor],
forward_context: dict[str, "Attention"],
runner_kv_caches: list[torch.Tensor],
) -> None:
"""
Bind the allocated KV cache to both ModelRunner and forward context so
that the KV cache can be used in the forward pass.
This function:
1) Fills the ModelRunner's kv cache list (`runner_kv_caches`) with
kv_caches.
2) Associates each attention layer in the `forward_context` with its
corresponding KV cache in kv_caches.
Args:
kv_caches: The allocated kv_caches with layer names as keys.
forward_context: The global forward context containing all Attention
layers with layer names as keys.
runner_kv_caches: The kv_cache declared by ModelRunner.
"""
# Bind kv_caches to ModelRunner
assert len(runner_kv_caches) == 0

# Convert kv_caches dict to a list of tensors in the order of layer_index.
index2name = defaultdict(list)
for layer_name in kv_caches:
index2name[extract_layer_index(layer_name)].append(layer_name)

for layer_index in sorted(index2name.keys()):
layer_names = index2name[layer_index]
if len(layer_names) > 1:
# One typical case is encoder-decoder model, e.g., bart.
# The cross attention and self attention in the same decoder layer
# has different layer_name but the same layer_index.
raise NotImplementedError
layer_name = layer_names[0]
runner_kv_caches.append(kv_caches[layer_name])

# Bind kv_caches to forward context
for layer_name, kv_cache in kv_caches.items():
# NOTE: Use list because of v0 PP virtual engine.
forward_context[layer_name].kv_cache = [kv_cache]
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Consider making runner_kv_caches an optional parameter to avoid unnecessary computation when the caller doesn't need it. This improves the function's cohesion and efficiency.

def bind_kv_cache(
    kv_caches: dict[str, torch.Tensor],
    forward_context: dict[str, "Attention"],
    runner_kv_caches: Optional[list[torch.Tensor]] = None,
) -> None:
    """
    Bind the allocated KV cache to both ModelRunner and forward context so
    that the KV cache can be used in the forward pass.

    This function:
      1) Fills the ModelRunner's kv cache list (`runner_kv_caches`) with
         kv_caches.
      2) Associates each attention layer in the `forward_context` with its
         corresponding KV cache in kv_caches.

    Args:
        kv_caches: The allocated kv_caches with layer names as keys.
        forward_context: The global forward context containing all Attention
        layers with layer names as keys.
        runner_kv_caches: The kv_cache declared by ModelRunner.
    """
    if runner_kv_caches is not None:
        # Bind kv_caches to ModelRunner
        assert len(runner_kv_caches) == 0

        # Convert kv_caches dict to a list of tensors in the order of layer_index.
        index2name = defaultdict(list)
        for layer_name in kv_caches:
            index2name[extract_layer_index(layer_name)].append(layer_name)

        for layer_index in sorted(index2name.keys()):
            layer_names = index2name[layer_index]
            if len(layer_names) > 1:
                # One typical case is encoder-decoder model, e.g., bart.
                # The cross attention and self attention in the same decoder layer
                # has different layer_name but the same layer_index.
                raise NotImplementedError
            layer_name = layer_names[0]
            runner_kv_caches.append(kv_caches[layer_name])

    # Bind kv_caches to forward context
    for layer_name, kv_cache in kv_caches.items():
        # NOTE: Use list because of v0 PP virtual engine.
        forward_context[layer_name].kv_cache = [kv_cache]

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This suggested change is out of the PR scope, we can do it in the next PR.

@github-actions
Copy link

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

🚀

Copy link
Collaborator

@Yikun Yikun left a comment

Choose a reason for hiding this comment

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

LGTM, just move bind_kv_cache from utils to worker.utils to avoid useless import, this is reasonable.

This PR also resolve the vllm-ascend downstream bug: vllm-project/vllm-ascend#1773 , the broken happened after #20061 (but it's a reasonable PR just had some impact on import order which impacts on vllm ascend patch order and make the patch no longer working indirectly.)

This issue will be resolved on vllm-ascend after torch deps upgrade to 2.7.1 vllm-project/vllm-ascend#1562 , but for now we need this PR.

This PR just move utils to reasonable postion, so I'm +1 on it.

@Yikun
Copy link
Collaborator

Yikun commented Jul 14, 2025

cc @heheda12345 Would you mind taking a look?

Copy link
Collaborator

@heheda12345 heheda12345 left a comment

Choose a reason for hiding this comment

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

LGTM! Thanks for finding this problem.

@heheda12345
Copy link
Collaborator

Does v0 bind_kv_cache cause similar problem?

@heheda12345 heheda12345 enabled auto-merge (squash) July 14, 2025 07:28
@github-actions github-actions bot added the ready ONLY add when PR is ready to merge/full CI is needed label Jul 14, 2025
@wangxiyuan
Copy link
Contributor Author

@heheda12345 I assume v0 code will be removed soon. So I did not change it.

@heheda12345 heheda12345 merged commit 1e9438e into vllm-project:main Jul 14, 2025
78 checks passed
Yikun pushed a commit to vllm-project/vllm-ascend that referenced this pull request Jul 14, 2025
This PR fixed the broken CI. It require
vllm-project/vllm#20900 merged first.

- vLLM version: v0.9.2
- vLLM main:
vllm-project/vllm@e8cc53a

Signed-off-by: wangxiyuan <[email protected]>
@wangxiyuan wangxiyuan mentioned this pull request Jul 17, 2025
4 tasks
x22x22 pushed a commit to x22x22/vllm that referenced this pull request Aug 5, 2025
Pradyun92 pushed a commit to Pradyun92/vllm that referenced this pull request Aug 6, 2025
npanpaliya pushed a commit to odh-on-pz/vllm-upstream that referenced this pull request Aug 6, 2025
yiliu30 pushed a commit to HabanaAI/vllm-fork that referenced this pull request Aug 8, 2025
jinzhen-lin pushed a commit to jinzhen-lin/vllm that referenced this pull request Aug 9, 2025
paulpak58 pushed a commit to paulpak58/vllm that referenced this pull request Aug 13, 2025
diegocastanibm pushed a commit to diegocastanibm/vllm that referenced this pull request Aug 15, 2025
epwalsh pushed a commit to epwalsh/vllm that referenced this pull request Aug 27, 2025
chopper0126 pushed a commit to chopper0126/vllm-ascend that referenced this pull request Oct 16, 2025
This PR fixed the broken CI. It require
vllm-project/vllm#20900 merged first.

- vLLM version: v0.9.2
- vLLM main:
vllm-project/vllm@e8cc53a

Signed-off-by: wangxiyuan <[email protected]>
Angazenn pushed a commit to Angazenn/vllm-ascend that referenced this pull request Oct 21, 2025
This PR fixed the broken CI. It require
vllm-project/vllm#20900 merged first.

- vLLM version: v0.9.2
- vLLM main:
vllm-project/vllm@e8cc53a

Signed-off-by: wangxiyuan <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready ONLY add when PR is ready to merge/full CI is needed tpu Related to Google TPUs v1

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants