Skip to content
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

[Core] More-efficient cross-attention parallel QKV computation #7448

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

Conversation

afeldman-nm
Copy link
Contributor

@afeldman-nm afeldman-nm commented Aug 13, 2024

This PR makes QKV computation more efficient in the case of cross-attention layers.

QKVParallelLinear only performs self-attention QKV computation against a single hidden-state input from the previous decoder layer.

Cross-attention requires Q to be computed from the previous decoder layer output hidden state, and KV to be computed from the encoder output hidden state. Additionally,

  • During prefill phase, both Q and KV must be computed
  • During decode phase, only Q is compute because the encoder sequence is static so there are no new encoder KVs

The current, inefficient workaround is to construct a QKVParallelLinear layer & apply it up to twice, once to decoder_hidden_states to obtain Q, and (only during prefill) a second time to encoder_hidden_states to obtain KV:

# (afeldman-nm 2024/07/22) TODO:
# Need a more efficient solution for q/k/v
qkv_dec, _ = self.qkv_proj(decoder_hidden_states)
q, _, _ = qkv_dec.split([self.q_size, self.kv_size, self.kv_size],
                        dim=-1)
if encoder_hidden_states is None:
    k = None
    v = None
else:
    qkv_enc, _ = self.qkv_proj(encoder_hidden_states)
    _, k, v = qkv_enc.split([self.q_size, self.kv_size, self.kv_size],
                            dim=-1)

This PR introduces a cross-attention QKV parallel linear layer with the following characteristics

  • Identical to QKVParallelLinear in terms of weight loading behavior
  • Still distributes per-head computations across GPUs, like QKVParallelLinear
  • forward() takes a decoder hidden states argument, and an optional encoder hidden states argument
  • forward() always computes $(decoder\ hidden\ states) W_Q$
  • forward() computes $(encoder\ hidden\ states) [W_K W_V]$ conditionally: only if the encoder hidden states argument is not None

The forward method of this new QKV parallel linear layer will return:

return (
    q_output,
    kv_output,
    q_bias if skip_bias_add else None,
    kv_bias if skip_bias_add else None,
)

The cross-attention layer will construct this new QKV parallel linear layer in __init__() as follows

self.qkv_proj = QCrossKVParallelLinear(
    self.d_model,
    self.d_model // self.total_num_heads,
    self.total_num_heads,
    self.total_num_kv_heads,
    bias=bias,
    quant_config=quant_config,
)

and then compute Q,K,V in forward() as follows

(
    q,
    kv,
    _,
    _,
) = self.qkv_proj(decoder_hidden_states, encoder_hidden_states)

if kv is None:
    k = None
    v = None
else:
    k, v = kv.split([self.kv_size, self.kv_size], dim=-1)

Note:

  • This PR only impacts encoder/decoder models, not decoder-only models
  • tests/models/test_bart serves as an end-to-end encoder/decoder model test, implicitly testing QCrossKVParallelLinear

FIX #7397 (link existing issues this PR will resolve)

BEFORE SUBMITTING, PLEASE READ THE CHECKLIST BELOW AND FILL IN THE DESCRIPTION ABOVE


PR Checklist (Click to Expand)

Thank you for your contribution to vLLM! Before submitting the pull request, please ensure the PR meets the following criteria. This helps vLLM maintain the code quality and improve the efficiency of the review process.

PR Title and Classification

Only specific types of PRs will be reviewed. The PR title is prefixed appropriately to indicate the type of change. Please use one of the following:

  • [Bugfix] for bug fixes.
  • [CI/Build] for build or continuous integration improvements.
  • [Doc] for documentation fixes and improvements.
  • [Model] for adding a new model or improving an existing model. Model name should appear in the title.
  • [Frontend] For changes on the vLLM frontend (e.g., OpenAI API server, LLM class, etc.)
  • [Kernel] for changes affecting CUDA kernels or other compute kernels.
  • [Core] for changes in the core vLLM logic (e.g., LLMEngine, AsyncLLMEngine, Scheduler, etc.)
  • [Hardware][Vendor] for hardware-specific changes. Vendor name should appear in the prefix (e.g., [Hardware][AMD]).
  • [Misc] for PRs that do not fit the above categories. Please use this sparingly.

Note: If the PR spans more than one category, please include all relevant prefixes.

Code Quality

The PR need to meet the following code quality standards:

  • We adhere to Google Python style guide and Google C++ style guide.
  • Pass all linter checks. Please use format.sh to format your code.
  • The code need to be well-documented to ensure future contributors can easily understand the code.
  • Include sufficient tests to ensure the project to stay correct and robust. This includes both unit tests and integration tests.
  • Please add documentation to docs/source/ if the PR modifies the user-facing behaviors of vLLM. It helps vLLM user understand and utilize the new features or changes.

Notes for Large Changes

Please keep the changes as concise as possible. For major architectural changes (>500 LOC excluding kernel/data/config/test), we would expect a GitHub issue (RFC) discussing the technical design and justification. Otherwise, we will tag it with rfc-required and might not go through the PR.

What to Expect for the Reviews

The goal of the vLLM team is to be a transparent reviewing machine. We would like to make the review process transparent and efficient and make sure no contributor feel confused or frustrated. However, the vLLM team is small, so we need to prioritize some PRs over others. Here is what you can expect from the review process:

  • After the PR is submitted, the PR will be assigned to a reviewer. Every reviewer will pick up the PRs based on their expertise and availability.
  • After the PR is assigned, the reviewer will provide status update every 2-3 days. If the PR is not reviewed within 7 days, please feel free to ping the reviewer or the vLLM team.
  • After the review, the reviewer will put an action-required label on the PR if there are changes required. The contributor should address the comments and ping the reviewer to re-review the PR.
  • Please respond to all comments within a reasonable time frame. If a comment isn't clear or you disagree with a suggestion, feel free to ask for clarification or discuss the suggestion.

Thank You

Finally, thank you for taking the time to read these guidelines and for your interest in contributing to vLLM. Your contributions make vLLM a great tool for everyone!

Copy link

👋 Hi! Thank you for contributing to the vLLM project.
Just a reminder: PRs would not trigger full CI run by default. Instead, it would only run fastcheck CI which consists a small and essential subset of CI tests to quickly catch errors. You can run other CI tests on top of default ones by unblocking the steps in your fast-check build on Buildkite UI.

Once the PR is approved and ready to go, please make sure to run full CI as it is required to merge (or just use auto-merge).

To run full CI, you can do one of these:

  • Comment /ready on the PR
  • Add ready label to the PR
  • Enable auto-merge.

🚀

Copy link
Collaborator

@sroy745 sroy745 left a comment

Choose a reason for hiding this comment

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

LGTM. Left a couple of small comments. Thanks for the pr.

@@ -303,7 +304,7 @@ def __init__(
f" and `num_heads`: {num_heads}).")
self.scaling = self.head_dim**-0.5

self.qkv_proj = QKVParallelLinear(
self.qkv_proj = QCrossKVParallelLinear(
Copy link
Collaborator

Choose a reason for hiding this comment

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

Was wondering if in the encoder-decode e2e test (e.g. test_bart.py) did you observe any increase in the input token/s or the output token/s with this change?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good question. I ran a very informal test to prove to myself that QCrossKVParallelLinear improved the total runtime of the encoder/decoder example script. I should run an actual benchmark in order compare tokens/s

@afeldman-nm
Copy link
Contributor Author

Perf test:

Server:

Note the use of eager mode & the lack of tensor-/pipeline-parallelism.

The key change in QCrossKVParallelLinear has to do with skipping extra work involved in QKV computation & does not require parallelism to test effectively.

python  -m vllm.entrypoints.openai.api_server     --model facebook/bart-large-cnn --swap-space 16 --enforce-eager     --disable-log-requests   --tensor-parallel-size 1  --pipeline-parallel-siz
e 1  --gpu-memory-utilization 0.90  --worker-use-ray 2>&1 | tee output.log

Client:

python benchmarks/benchmark_serving.py     --backend vllm      --model facebook/bart-large-cnn     --dataset-name sharegpt     --dataset-path ../sharegpt.json

Testbench:

4x NVIDIA A4000 RTX 16GB

Baseline perf benchmark result (main, 029c71d)

============ Serving Benchmark Result ============
Successful requests:                     945       
Benchmark duration (s):                  39.58     
Total input tokens:                      197519    
Total generated tokens:                  18272     
Request throughput (req/s):              23.88     
Input token throughput (tok/s):          4990.44   
Output token throughput (tok/s):         461.65    
---------------Time to First Token----------------
Mean TTFT (ms):                          7176.60   
Median TTFT (ms):                        5528.61   
P99 TTFT (ms):                           19099.46  
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          194.47    
Median TPOT (ms):                        208.84    
P99 TPOT (ms):                           303.55    
---------------Inter-token Latency----------------
Mean ITL (ms):                           151.25    
Median ITL (ms):                         188.21    
P99 ITL (ms):                            362.17    
==================================================

PR branch result (after merging in 029c71d)

============ Serving Benchmark Result ============
Successful requests:                     945       
Benchmark duration (s):                  38.30     
Total input tokens:                      197519    
Total generated tokens:                  18307     
Request throughput (req/s):              24.67     
Input token throughput (tok/s):          5156.99   
Output token throughput (tok/s):         477.97    
---------------Time to First Token----------------
Mean TTFT (ms):                          6972.37   
Median TTFT (ms):                        5344.80   
P99 TTFT (ms):                           18775.37  
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          192.98    
Median TPOT (ms):                        205.76    
P99 TPOT (ms):                           328.27    
---------------Inter-token Latency----------------
Mean ITL (ms):                           148.30    
Median ITL (ms):                         186.53    
P99 ITL (ms):                            371.48    
==================================================

@afeldman-nm
Copy link
Contributor Author

Based on the benchmarks it is not clear this change improves performance.

@heheda12345
Copy link
Collaborator

I'm trying mllama with QCrossKVParallelLinear. For batch_size 16 & H100 & Llama-3.2-11B-Vision-Instruct , this layer can reduce the time for preparing QKV from 46.5279ms to 21.7249ms. But it have negelible impact to the end to end performace compared with the thousands of ms to process such a batch, which is similar to the experiments in bart model.
The code is here

And I have a question: as you compute $wq$ and $w[k,v]$ sequentially, why not choosing QLinear + KVParallelLinear?

        q_output_parallel = self._apply_w_conditional_bias(
            self._cached_q_weights_wrapper, decoder_input_,
            self._cached_q_bias)
        kv_output_parallel = None if is_decode_phase else (
            self._apply_w_conditional_bias(self._cached_kv_weights_wrapper,
                                           encoder_input_,
                                           self._cached_kv_bias))

Copy link

This pull request has been automatically marked as stale because it has not had any activity within 90 days. It will be automatically closed if no further activity occurs within 30 days. Leave a comment if you feel this pull request should remain open. Thank you!

@github-actions github-actions bot added the stale label Feb 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Misc]: Cross-attention QKV computation is inefficient
3 participants