[Ops][Misc] Optimize split_qkv_rmsnorm_rope op#6827
[Ops][Misc] Optimize split_qkv_rmsnorm_rope op#6827whx-sjtu merged 35 commits intovllm-project:mainfrom
Conversation
|
👋 Hi! Thank you for contributing to the vLLM Ascend project. The following points will speed up your PR merge:
If CI fails, you can run linting and testing checks locally according Contributing and Testing. |
Summary of ChangesHello @guleo, 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 enhances the Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe 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 by creating a comment using either
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 Limitations & Feedback Gemini Code Assist 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. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. 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
|
There was a problem hiding this comment.
Code Review
This pull request introduces significant optimizations for the split_qkv_rmsnorm_rope operator by adding a dedicated prefill kernel for large batch sizes. The changes are substantial and aim to improve performance.
My review has identified a few critical issues that will cause the new kernels to fail during compilation due to incorrect indexing on scalar values. Additionally, there are opportunities to improve performance and maintainability by vectorizing a loop in the prefill kernel and by clarifying the logic used for auto-tuning batch sizes, which currently relies on undocumented magic numbers.
As the pull request description is empty, I've provided a suggestion for the title and summary below to align with the repository's contribution guidelines.
Suggested PR Title:
[Ops][Misc] Optimize split_qkv_rmsnorm_rope opSuggested PR Summary:
### What this PR does / why we need it?
This PR optimizes the `split_qkv_rmsnorm_rope` operator by introducing a new Triton kernel, `split_qkv_rmsnorm_rope_prefill_kernel`, for the prefill stage (i.e., large batch sizes). The implementation now dynamically selects between the existing decode kernel and the new prefill kernel based on the batch size, which improves performance for large batch scenarios.
Additionally, the RoPE implementation is updated to support partial rotation dimensions (`rope_dim`), making the operator more flexible.
### Does this PR introduce _any_ user-facing change?
No. This is a performance optimization and is not expected to introduce any user-facing changes.
### How was this patch tested?
CI should pass with existing tests. The new prefill path is triggered when the batch size is larger than the number of available vector cores. The partial RoPE feature can be tested by passing the `rope_dim` argument.| cos = (tl.load(cos_sin_ptr + cos_offsets)).reshape(1, HALF_HEAD_DIM) | ||
| sin = (tl.load(cos_sin_ptr + sin_offsets)).reshape(1, HALF_HEAD_DIM) | ||
| pos_values = tl.load(positions_gm_ptr + row_idx) | ||
| sin_cos_indices = ((pos_values[:, None] * ele_sin_cos_per_batch + tl.arange(0, ele_sin_cos_per_batch))).reshape(2, ROPE_DIM) |
There was a problem hiding this comment.
pos_values is loaded as a scalar value from positions_gm_ptr. Applying [:, None] indexing to a scalar is invalid in Triton and will cause a kernel compilation error. You should remove [:, None] to treat pos_values as a scalar in the multiplication.
| sin_cos_indices = ((pos_values[:, None] * ele_sin_cos_per_batch + tl.arange(0, ele_sin_cos_per_batch))).reshape(2, ROPE_DIM) | |
| sin_cos_indices = (pos_values * ele_sin_cos_per_batch + tl.arange(0, ele_sin_cos_per_batch)).reshape(2, ROPE_DIM) |
| cos = (tl.load(cos_sin_ptr + cos_offsets)).reshape(1, HALF_HEAD_DIM) | ||
| sin = (tl.load(cos_sin_ptr + sin_offsets)).reshape(1, HALF_HEAD_DIM) | ||
| pos_values = tl.load(positions_gm_ptr + row_idx) | ||
| sin_cos_indices = ((pos_values[:, None] * ele_sin_cos_per_batch + tl.arange(0, ele_sin_cos_per_batch))).reshape(2, ROPE_DIM) |
There was a problem hiding this comment.
pos_values is loaded as a scalar value from positions_gm_ptr. Applying [:, None] indexing to a scalar is invalid in Triton and will cause a kernel compilation error. You should remove [:, None] to treat pos_values as a scalar in the multiplication.
| sin_cos_indices = ((pos_values[:, None] * ele_sin_cos_per_batch + tl.arange(0, ele_sin_cos_per_batch))).reshape(2, ROPE_DIM) | |
| sin_cos_indices = (pos_values * ele_sin_cos_per_batch + tl.arange(0, ele_sin_cos_per_batch)).reshape(2, ROPE_DIM) |
| values_tmp3 = tl.zeros((batch_size_per_iter_per_vec, ele_sin_cos_per_batch), dtype=tl.bfloat16) | ||
| for i in tl.range(batch_size_per_iter_per_vec): | ||
| pos = tl.get_element( | ||
| x, (i,) | ||
| ) | ||
| values_tmp3 = tl.insert_slice( | ||
| values_tmp3.reshape(batch_size_per_iter_per_vec, ele_sin_cos_per_batch), | ||
| tl.load(pos * ele_sin_cos_per_batch + cos_sin_cache_offset[:, None]).reshape(1, ele_sin_cos_per_batch), | ||
| offsets=(i, 0), | ||
| sizes=(1, ele_sin_cos_per_batch), | ||
| strides=(1, 1), | ||
| ) |
There was a problem hiding this comment.
The for loop used here to gather sin and cos values processes elements serially, which is an anti-pattern in Triton and will lead to poor performance. This logic should be vectorized using a single tl.load with 2D indexing to leverage the parallelism of the hardware.
A vectorized implementation would look something like this:
# x is a 1D tensor of positions of shape (batch_size_per_iter_per_vec,)
indices = x[:, None] * ele_sin_cos_per_batch + tl.arange(0, ele_sin_cos_per_batch)[None, :]
# A mask should be applied to indices based on valid positions in x
mask = (pos_indices + pos_offset)[:, None] < input_batch_offset_end
values_tmp3 = tl.load(cos_sin_cache_gm_ptr + indices, mask=mask)This change is important for achieving the performance goals of this optimization.
| # 每次迭代、UB用满的情况input输入元素数量设为x: | ||
|
|
||
| # 2x + x/(kv_head_num+q_head_num) + x*(q_head_num/(q_head_num+kv_headnum))*1.75=85k | ||
| # 2x(kv_head_num+q_head_num) + x + 1.75*x*q_head_num =85k * (kv_head_num+q_head_num) | ||
| # x*(2*(kv_head_num+q_head_num) + 1 + 1.75*q_head_num) = 85k * (kv_head_num+q_head_num) | ||
| # x = 85k * (kv_head_num+q_head_num) / (2*(kv_head_num+q_head_num) + 1 + 1.75*q_head_num) | ||
|
|
||
| #2x*(q_head_num + kv_head_num)*HEAD_DIM*3+x*HEAD_DIM*(2+q_head_num*0.5) = 85*1024/2 | ||
| # input_values + normalized_values+normalized_values_tmp + x + sin and cos | ||
| # input.element_size() 此处为bfloat16,占用两个字节 | ||
| # batch_size_per_iter_per_vec = 85*1024/input.element_size()//(6 * head_dim * (q_head_num + kv_head_num) + head_dim * 2 + head_dim*q_head_num*0.5) | ||
| # 设:GM上原数据取X行元素(bfloat16) | ||
| # x*(q_head_num + kv_head_num)*HEAD_DIM: values_tmp | ||
| # 2x*(q_head_num + kv_head_num)*HEAD_DIM: normalized_values(float32) | ||
| # x*ROPE_DIM*2 : cos/sin | ||
| # x*q_head_num*HEAD_DIM*2: normalized_values_tmp | ||
| # x*q_head_num*ROPE_DIM*(0.5) x(not IS_PARTIAL_ROPE) | ||
|
|
||
| if IS_PARTIAL_ROPE: | ||
| factor = (5*q_head_num*head_dim + 3*kv_head_num*head_dim + rope_dim*4 +q_head_num*rope_dim) | ||
| batch_size_per_iter_per_vec = 85*1024/input.element_size()// factor | ||
| else: | ||
| factor = (5*q_head_num*head_dim + 3*kv_head_num*head_dim + rope_dim*2 +q_head_num*rope_dim*0.5) | ||
| batch_size_per_iter_per_vec = 85*1024/input.element_size()// factor | ||
| batch_size_per_iter_per_vec = min(batch_size_per_iter_per_vec, batch_size_per_vec) | ||
| qk_head_num_sum = int(q_head_num + kv_head_num) | ||
| qk_head_nums_per_iter_per_vec = batch_size_per_iter_per_vec * qk_head_num_sum | ||
|
|
||
| iter_num_per_vec = triton.cdiv(batch_size_per_vec, batch_size_per_iter_per_vec) | ||
|
|
||
| grid_prefill = (min(num_vectorcore,batch_size), 1)# | ||
| grid = grid_prefill | ||
|
|
||
| # v的分核 | ||
| v_batch_size_per_iter_per_vec = 85 * 1024 / torch.bfloat16.itemsize // (kv_hidden_size + 1) | ||
| v_batch_size_per_iter_per_vec = min(v_batch_size_per_iter_per_vec, batch_size_per_vec) | ||
| v_iter_num_per_vec = triton.cdiv(batch_size_per_vec, v_batch_size_per_iter_per_vec) |
There was a problem hiding this comment.
The calculation of batch_size_per_iter_per_vec and v_batch_size_per_iter_per_vec relies on magic numbers and complex, undocumented formulas. This makes the code difficult to understand, maintain, and adapt to different hardware or kernel changes.
Please consider the following improvements:
- Replace the magic number
85*1024with a named constant, e.g.,L1_CACHE_SIZE = 85 * 1024, and add a comment explaining its origin and why this specific value is used. - Add detailed comments explaining the derivation of the
factorand the formula forv_batch_size_per_iter_per_vec. The comments should break down how the memory usage of each intermediate tensor in the kernel contributes to the final formula. The existing Chinese comments are a start but are unclear and seem to have discrepancies with the code.
For example, for factor:
# Memory usage estimation for one row (x=1) in bytes:
# normalized_values (float32): (q_head_num + kv_head_num) * head_dim * 4
# values_tmp1 (bfloat16): (q_head_num + kv_head_num) * head_dim * 2
# ... and so on for other tensors
# The factor is the sum of these sizes per row.Improving clarity here is crucial for long-term maintainability.
| if IS_PARTIAL_ROPE: | ||
| factor = (5*q_head_num*head_dim + 3*kv_head_num*head_dim + rope_dim*4 +q_head_num*rope_dim) | ||
| batch_size_per_iter_per_vec = 85*1024/input.element_size()// factor | ||
| else: | ||
| factor = (5*q_head_num*head_dim + 3*kv_head_num*head_dim + rope_dim*2 +q_head_num*rope_dim*0.5) | ||
| batch_size_per_iter_per_vec = 85*1024/input.element_size()// factor |
There was a problem hiding this comment.
Do not use magic numbers. Replace with variables.
| grid_prefill = (min(num_vectorcore,batch_size), 1)# | ||
| grid = grid_prefill |
There was a problem hiding this comment.
| grid_prefill = (min(num_vectorcore,batch_size), 1)# | |
| grid = grid_prefill | |
| grid = (num_vectorcore, 1)# |
whx-sjtu
left a comment
There was a problem hiding this comment.
What's more, please make sure that the fusion pass of qkv_rmsnorm_rope takes effect for both normal rope (like Qwen3-30B) and partial rope (like GLM 4.7) scenarios.
|
The scenerio is included. |
71b7cfd to
392afd9
Compare
Signed-off-by: guzhiyong <guzhiyong5@h-partners.com>
| roped_k += normalized_values * cos | ||
| tl.store( | ||
| k_ptr + output_offset + col_indices, | ||
| roped_k.to(tl.bfloat16).reshape(KV_BLOCK_SIZE), |
There was a problem hiding this comment.
I'm confused here. Why hard-code tl.bfloat16 here?
There was a problem hiding this comment.
inherents old implement
| # get available vector core | ||
| num_vectorcore = get_vectorcore_num() | ||
| rope_dim = cos_sin_cache.shape[1] | ||
| cos_sin_cache = cos_sin_cache.view(-1, 2, rope_dim // 2).repeat(1, 1, 2) |
There was a problem hiding this comment.
this repeat of cos_sin_cache increase the overall execution time by 50% ~ 100%. If it is necessary, plz consider to move it to __init__ of AscendRotaryEmbedding
Signed-off-by: guzhiyong <guzhiyong5@h-partners.com>
Signed-off-by: guzhiyong <guzhiyong5@h-partners.com>
Signed-off-by: guzhiyong <guzhiyong5@h-partners.com>
|
This pull request has conflicts, please resolve those before we can evaluate the pull request. |
| pos_values = tl.load(positions_gm_ptr + row_idx) | ||
| sin_cos_indices = pos_values * ROPE_DIM + tl.arange(0, ROPE_DIM) | ||
| input_values = tl.load(cos_sin_cache_gm_ptr + sin_cos_indices).reshape(1, ROPE_DIM) | ||
| cos = tl.extract_slice( |
There was a problem hiding this comment.
Please refer to #6937, extract_slice, insert_slice and select_element are recommended to be imported from triton_utils.py at the beginning to keep compatibility between newest triton_ascend version.
Signed-off-by: guzhiyong <guzhiyong5@h-partners.com>
Signed-off-by: frank <2547457096@qq.com>
Signed-off-by: guzhiyong <guzhiyong5@h-partners.com>
### What this PR does / why we need it? This PR optimizes the `split_qkv_rmsnorm_rope` operator by introducing a new Triton kernel, `split_qkv_rmsnorm_rope_prefill_kernel`, for the prefill stage (i.e., large batch sizes). The implementation now dynamically selects between the existing decode kernel and the new prefill kernel based on the batch size, which improves performance for large batch scenarios. Additionally, the RoPE implementation is updated to support partial rotation dimensions (`rope_dim`), making the operator more flexible. ### Does this PR introduce _any_ user-facing change? No. This is a performance optimization and is not expected to introduce any user-facing changes. ### How was this patch tested? CI should pass with existing tests. The new prefill path is triggered when the batch size is larger than the number of available vector cores. The partial RoPE feature can be tested by passing the `rope_dim` argument. - vLLM version: v0.15.0 - vLLM main: vllm-project/vllm@83b47f6 --------- Signed-off-by: guzhiyong <guzhiyong5@h-partners.com> Signed-off-by: frank <2547457096@qq.com> Co-authored-by: guzhiyong <guzhiyong5@h-partners.com>
What this PR does / why we need it?
This PR optimizes the
split_qkv_rmsnorm_ropeoperator by introducing a new Triton kernel,split_qkv_rmsnorm_rope_prefill_kernel, for the prefill stage (i.e., large batch sizes). The implementation now dynamically selects between the existing decode kernel and the new prefill kernel based on the batch size, which improves performance for large batch scenarios.Additionally, the RoPE implementation is updated to support partial rotation dimensions (
rope_dim), making the operator more flexible.Does this PR introduce any user-facing change?
No. This is a performance optimization and is not expected to introduce any user-facing changes.
How was this patch tested?
CI should pass with existing tests. The new prefill path is triggered when the batch size is larger than the number of available vector cores. The partial RoPE feature can be tested by passing the
rope_dimargument.