Skip to content

Fast rotary embedding#10527

Closed
AlienKevin wants to merge 22 commits intosgl-project:mainfrom
AlienKevin:rotary_emb_kernel_mick
Closed

Fast rotary embedding#10527
AlienKevin wants to merge 22 commits intosgl-project:mainfrom
AlienKevin:rotary_emb_kernel_mick

Conversation

@AlienKevin
Copy link
Copy Markdown
Contributor

@AlienKevin AlienKevin commented Sep 16, 2025

This PR updates @mickqian's #6530 with benchmarks on MMMU.

VisionAttention used by most VLMs, including Qwen 2.5 VL, relied on the slow apply_rotary_pos_emb_native
implementation written in PyTorch. After a series of optimizations (#8484, #9661), rotary embedding became one of the largest bottlenecks on the GPU side for Qwen 2.5 VL.

The main challenge in adapting existing SGL rotary kernels to VLMs was handling non-standard head sizes. Vision encoders often use head sizes like 80, which weren’t supported by the previous SGL rotary kernel. In those cases, the code had to fall back to vLLM’s kernel.

With @mickqian's improved rotary embedding kernel—now supporting flexible head sizes—SGL no longer needs to fall back, and performance has jumped significantly. On MMMU, SGL now outperforms vLLM by 12% in throughput 🥳

Framework Total tokens/s (per run) Best total tokens/s
SGL (before) 9,154 • 9,396 • 10,242 10,242
SGL (after) 12,450 • 12,097 • 11,949 12,450
vLLM 10,960 • 11,095 • 10,992 11,095
Run 1
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf       
Max request concurrency:                 not set   
Successful requests:                     505       
Benchmark duration (s):                  58.76     
Total input tokens:                      214424    
Total input text tokens:                 44483     
Total input vision tokens:               169941    
Total generated tokens:                  517120    
Total generated tokens (retokenized):    347603    
Request throughput (req/s):              8.59      
Input token throughput (tok/s):          3649.26   
Output token throughput (tok/s):         8800.81   
Total token throughput (tok/s):          12450.07  
Concurrency:                             395.43    
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   46009.82  
Median E2E Latency (ms):                 34093.57  
---------------Time to First Token----------------
Mean TTFT (ms):                          25322.23  
Median TTFT (ms):                        16112.75  
P99 TTFT (ms):                           40711.51  
---------------Inter-Token Latency----------------
Mean ITL (ms):                           25.89     
Median ITL (ms):                         18.33     
P95 ITL (ms):                            40.20     
P99 ITL (ms):                            43.38     
Max ITL (ms):                            6568.34   
==================================================
Run 2
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf       
Max request concurrency:                 not set   
Successful requests:                     505       
Benchmark duration (s):                  60.47     
Total input tokens:                      214424    
Total input text tokens:                 44483     
Total input vision tokens:               169941    
Total generated tokens:                  517120    
Total generated tokens (retokenized):    348896    
Request throughput (req/s):              8.35      
Input token throughput (tok/s):          3545.69   
Output token throughput (tok/s):         8551.03   
Total token throughput (tok/s):          12096.72  
Concurrency:                             395.19    
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   47324.28  
Median E2E Latency (ms):                 35243.66  
---------------Time to First Token----------------
Mean TTFT (ms):                          26849.12  
Median TTFT (ms):                        18134.65  
P99 TTFT (ms):                           41873.09  
---------------Inter-Token Latency----------------
Mean ITL (ms):                           25.58     
Median ITL (ms):                         17.77     
P95 ITL (ms):                            39.67     
P99 ITL (ms):                            42.62     
Max ITL (ms):                            7458.18   
==================================================
Run 3
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf       
Max request concurrency:                 not set   
Successful requests:                     505       
Benchmark duration (s):                  61.22     
Total input tokens:                      214424    
Total input text tokens:                 44483     
Total input vision tokens:               169941    
Total generated tokens:                  517120    
Total generated tokens (retokenized):    349378    
Request throughput (req/s):              8.25      
Input token throughput (tok/s):          3502.47   
Output token throughput (tok/s):         8446.81   
Total token throughput (tok/s):          11949.28  
Concurrency:                             397.90    
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   48237.17  
Median E2E Latency (ms):                 36097.51  
---------------Time to First Token----------------
Mean TTFT (ms):                          27178.01  
Median TTFT (ms):                        17816.48  
P99 TTFT (ms):                           42843.47  
---------------Inter-Token Latency----------------
Mean ITL (ms):                           26.29     
Median ITL (ms):                         18.25     
P95 ITL (ms):                            41.32     
P99 ITL (ms):                            44.41     
Max ITL (ms):                            7549.05   
==================================================

Accuracy verified on 7B and 3B

Accuracy preserved on Qwen2.5-VL-7B-Instruct (before: 0.519, after: 0.516)
Overall accuracy: 0.516

{'Accounting': {'acc': 0.433, 'num': 30},
 'Agriculture': {'acc': 0.533, 'num': 30},
 'Architecture_and_Engineering': {'acc': 0.433, 'num': 30},
 'Art': {'acc': 0.667, 'num': 30},
 'Art_Theory': {'acc': 0.833, 'num': 30},
 'Basic_Medical_Science': {'acc': 0.6, 'num': 30},
 'Biology': {'acc': 0.367, 'num': 30},
 'Chemistry': {'acc': 0.367, 'num': 30},
 'Clinical_Medicine': {'acc': 0.633, 'num': 30},
 'Computer_Science': {'acc': 0.433, 'num': 30},
 'Design': {'acc': 0.7, 'num': 30},
 'Diagnostics_and_Laboratory_Medicine': {'acc': 0.467, 'num': 30},
 'Economics': {'acc': 0.5, 'num': 30},
 'Electronics': {'acc': 0.3, 'num': 30},
 'Energy_and_Power': {'acc': 0.267, 'num': 30},
 'Finance': {'acc': 0.4, 'num': 30},
 'Geography': {'acc': 0.4, 'num': 30},
 'History': {'acc': 0.667, 'num': 30},
 'Literature': {'acc': 0.8, 'num': 30},
 'Manage': {'acc': 0.367, 'num': 30},
 'Marketing': {'acc': 0.467, 'num': 30},
 'Materials': {'acc': 0.4, 'num': 30},
 'Math': {'acc': 0.533, 'num': 30},
 'Mechanical_Engineering': {'acc': 0.5, 'num': 30},
 'Music': {'acc': 0.467, 'num': 30},
 'Overall': {'acc': 0.516, 'num': 900},
 'Overall-Art and Design': {'acc': 0.667, 'num': 120},
 'Overall-Business': {'acc': 0.433, 'num': 150},
 'Overall-Health and Medicine': {'acc': 0.593, 'num': 150},
 'Overall-Humanities and Social Science': {'acc': 0.675, 'num': 120},
 'Overall-Science': {'acc': 0.42, 'num': 150},
 'Overall-Tech and Engineering': {'acc': 0.41, 'num': 210},
 'Pharmacy': {'acc': 0.633, 'num': 30},
 'Physics': {'acc': 0.433, 'num': 30},
 'Psychology': {'acc': 0.7, 'num': 30},
 'Public_Health': {'acc': 0.633, 'num': 30},
 'Sociology': {'acc': 0.533, 'num': 30}}

Before PR (python3 -m sglang.launch_server --model-path Qwen/Qwen2.5-VL-7B-Instruct --mm-attention-backend sdpa):

Overall accuracy: 0.519

{'Accounting': {'acc': 0.433, 'num': 30},
 'Agriculture': {'acc': 0.533, 'num': 30},
 'Architecture_and_Engineering': {'acc': 0.467, 'num': 30},
 'Art': {'acc': 0.667, 'num': 30},
 'Art_Theory': {'acc': 0.8, 'num': 30},
 'Basic_Medical_Science': {'acc': 0.6, 'num': 30},
 'Biology': {'acc': 0.367, 'num': 30},
 'Chemistry': {'acc': 0.367, 'num': 30},
 'Clinical_Medicine': {'acc': 0.633, 'num': 30},
 'Computer_Science': {'acc': 0.433, 'num': 30},
 'Design': {'acc': 0.7, 'num': 30},
 'Diagnostics_and_Laboratory_Medicine': {'acc': 0.467, 'num': 30},
 'Economics': {'acc': 0.467, 'num': 30},
 'Electronics': {'acc': 0.367, 'num': 30},
 'Energy_and_Power': {'acc': 0.267, 'num': 30},
 'Finance': {'acc': 0.367, 'num': 30},
 'Geography': {'acc': 0.4, 'num': 30},
 'History': {'acc': 0.667, 'num': 30},
 'Literature': {'acc': 0.8, 'num': 30},
 'Manage': {'acc': 0.333, 'num': 30},
 'Marketing': {'acc': 0.5, 'num': 30},
 'Materials': {'acc': 0.433, 'num': 30},
 'Math': {'acc': 0.567, 'num': 30},
 'Mechanical_Engineering': {'acc': 0.5, 'num': 30},
 'Music': {'acc': 0.5, 'num': 30},
 'Overall': {'acc': 0.519, 'num': 900},
 'Overall-Art and Design': {'acc': 0.667, 'num': 120},
 'Overall-Business': {'acc': 0.42, 'num': 150},
 'Overall-Health and Medicine': {'acc': 0.593, 'num': 150},
 'Overall-Humanities and Social Science': {'acc': 0.675, 'num': 120},
 'Overall-Science': {'acc': 0.427, 'num': 150},
 'Overall-Tech and Engineering': {'acc': 0.429, 'num': 210},
 'Pharmacy': {'acc': 0.633, 'num': 30},
 'Physics': {'acc': 0.433, 'num': 30},
 'Psychology': {'acc': 0.7, 'num': 30},
 'Public_Health': {'acc': 0.633, 'num': 30},
 'Sociology': {'acc': 0.533, 'num': 30}}
Accuracy preserved on Qwen2.5-VL-3B-Instruct (before: 0.454, after: 0.456)
Overall accuracy: 0.456

{'Accounting': {'acc': 0.467, 'num': 30},
 'Agriculture': {'acc': 0.533, 'num': 30},
 'Architecture_and_Engineering': {'acc': 0.367, 'num': 30},
 'Art': {'acc': 0.533, 'num': 30},
 'Art_Theory': {'acc': 0.7, 'num': 30},
 'Basic_Medical_Science': {'acc': 0.633, 'num': 30},
 'Biology': {'acc': 0.367, 'num': 30},
 'Chemistry': {'acc': 0.267, 'num': 30},
 'Clinical_Medicine': {'acc': 0.4, 'num': 30},
 'Computer_Science': {'acc': 0.3, 'num': 30},
 'Design': {'acc': 0.667, 'num': 30},
 'Diagnostics_and_Laboratory_Medicine': {'acc': 0.433, 'num': 30},
 'Economics': {'acc': 0.3, 'num': 30},
 'Electronics': {'acc': 0.133, 'num': 30},
 'Energy_and_Power': {'acc': 0.367, 'num': 30},
 'Finance': {'acc': 0.3, 'num': 30},
 'Geography': {'acc': 0.333, 'num': 30},
 'History': {'acc': 0.733, 'num': 30},
 'Literature': {'acc': 0.833, 'num': 30},
 'Manage': {'acc': 0.3, 'num': 30},
 'Marketing': {'acc': 0.5, 'num': 30},
 'Materials': {'acc': 0.433, 'num': 30},
 'Math': {'acc': 0.333, 'num': 30},
 'Mechanical_Engineering': {'acc': 0.4, 'num': 30},
 'Music': {'acc': 0.233, 'num': 30},
 'Overall': {'acc': 0.456, 'num': 900},
 'Overall-Art and Design': {'acc': 0.533, 'num': 120},
 'Overall-Business': {'acc': 0.373, 'num': 150},
 'Overall-Health and Medicine': {'acc': 0.527, 'num': 150},
 'Overall-Humanities and Social Science': {'acc': 0.692, 'num': 120},
 'Overall-Science': {'acc': 0.347, 'num': 150},
 'Overall-Tech and Engineering': {'acc': 0.362, 'num': 210},
 'Pharmacy': {'acc': 0.6, 'num': 30},
 'Physics': {'acc': 0.433, 'num': 30},
 'Psychology': {'acc': 0.6, 'num': 30},
 'Public_Health': {'acc': 0.567, 'num': 30},
 'Sociology': {'acc': 0.6, 'num': 30}}

Before PR (python3 -m sglang.launch_server --model-path Qwen/Qwen2.5-VL-3B-Instruct --mm-attention-backend sdpa):

Overall accuracy: 0.454

{'Accounting': {'acc': 0.467, 'num': 30},
 'Agriculture': {'acc': 0.533, 'num': 30},
 'Architecture_and_Engineering': {'acc': 0.367, 'num': 30},
 'Art': {'acc': 0.567, 'num': 30},
 'Art_Theory': {'acc': 0.7, 'num': 30},
 'Basic_Medical_Science': {'acc': 0.667, 'num': 30},
 'Biology': {'acc': 0.367, 'num': 30},
 'Chemistry': {'acc': 0.267, 'num': 30},
 'Clinical_Medicine': {'acc': 0.4, 'num': 30},
 'Computer_Science': {'acc': 0.3, 'num': 30},
 'Design': {'acc': 0.633, 'num': 30},
 'Diagnostics_and_Laboratory_Medicine': {'acc': 0.433, 'num': 30},
 'Economics': {'acc': 0.3, 'num': 30},
 'Electronics': {'acc': 0.133, 'num': 30},
 'Energy_and_Power': {'acc': 0.367, 'num': 30},
 'Finance': {'acc': 0.3, 'num': 30},
 'Geography': {'acc': 0.333, 'num': 30},
 'History': {'acc': 0.733, 'num': 30},
 'Literature': {'acc': 0.867, 'num': 30},
 'Manage': {'acc': 0.3, 'num': 30},
 'Marketing': {'acc': 0.5, 'num': 30},
 'Materials': {'acc': 0.433, 'num': 30},
 'Math': {'acc': 0.367, 'num': 30},
 'Mechanical_Engineering': {'acc': 0.367, 'num': 30},
 'Music': {'acc': 0.233, 'num': 30},
 'Overall': {'acc': 0.454, 'num': 900},
 'Overall-Art and Design': {'acc': 0.533, 'num': 120},
 'Overall-Business': {'acc': 0.373, 'num': 150},
 'Overall-Health and Medicine': {'acc': 0.533, 'num': 150},
 'Overall-Humanities and Social Science': {'acc': 0.692, 'num': 120},
 'Overall-Science': {'acc': 0.34, 'num': 150},
 'Overall-Tech and Engineering': {'acc': 0.357, 'num': 210},
 'Pharmacy': {'acc': 0.6, 'num': 30},
 'Physics': {'acc': 0.367, 'num': 30},
 'Psychology': {'acc': 0.567, 'num': 30},
 'Public_Health': {'acc': 0.567, 'num': 30},
 'Sociology': {'acc': 0.6, 'num': 30}}

Tested using #9812
Server cmd:

SGLANG_VLM_CACHE_SIZE_MB=0 python -m sglang.launch_server \
    --model-path Qwen/Qwen2.5-VL-7B-Instruct \
    --mem-fraction-static 0.8 \
    --chat-template 'qwen2-vl' \
    --tp 1 \
    --disable-radix-cache \
    --cuda-graph-bs 256 \
    --cuda-graph-max-bs 256 \
    --chunked-prefill-size 8192 \
    --max-prefill-tokens 8192 \
    --max-running-requests 256 \
    --enable-multimodal

Client cmd:

python3 -m sglang.bench_serving \
    --backend sglang-oai-chat \
    --dataset-name mmmu \
    --num-prompts 1000 \
    --apply-chat-template

Copy link
Copy Markdown
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 @AlienKevin, 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 addresses a critical performance bottleneck in SGLang's VisionAttention layer, particularly for Vision-Language Models like Qwen 2.5 VL. The previous reliance on a slow PyTorch-native rotary embedding implementation and the inability to handle non-standard head sizes led to performance degradation and forced fallbacks to external kernels. The core of this change is the integration of a new, highly optimized CUDA rotary embedding kernel that supports flexible head sizes. This enhancement not only resolves the head size compatibility issue but also delivers a substantial throughput improvement, making SGLang more efficient for VLM workloads without compromising accuracy.

Highlights

  • New Rotary Embedding Kernel: Introduced a new, optimized CUDA kernel for rotary embedding, specifically designed to address performance bottlenecks in Vision-Language Models (VLMs).
  • Flexible Head Size Support: The new kernel supports flexible head sizes, such as 80, which were previously unsupported by SGLang's native kernels. This eliminates the need to fall back to vLLM's rotary embedding kernel for such configurations.
  • Significant Performance Improvement: Achieved a 12% increase in throughput on the MMMU benchmark compared to vLLM, with SGLang (after) reaching 12,450 total tokens/s from 10,242 total tokens/s (before).
  • Accuracy Preservation: Verified that the new rotary embedding kernel preserves model accuracy on Qwen2.5-VL-7B-Instruct and Qwen2.5-VL-3B-Instruct models.
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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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 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

  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
Copy Markdown
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 introduces a new CUDA kernel for rotary embeddings to improve performance for Vision-Language Models, especially those with non-standard head sizes. The changes are well-supported by performance benchmarks and accuracy checks. My review focuses on ensuring the changes are robust and maintainable. I've found a critical regression that could affect text models, an issue with the new CUDA operator's schema definition, and a suggestion to improve the configurability of the vision attention layer. Overall, this is a great performance enhancement, and with these fixes, it will be a solid contribution.

Comment on lines +247 to +264
cos, sin = positions
assert cos.dtype == torch.float and cos.is_contiguous()
assert sin.dtype == torch.float and sin.is_contiguous()
orig_q_dtype = query.dtype
orig_k_dtype = key.dtype
query, key = query.float(), key.float()

self.sglang_rotary_embedding(
cos,
sin,
query,
key,
self.head_size,
self.cos_sin_cache,
self.is_neox_style,
)

query = query.to(dtype=orig_q_dtype)
key = key.to(dtype=orig_k_dtype)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

critical

The else block in forward_cuda now assumes that the positions argument is a tuple of (cos, sin), which is true for the new vision model use case. However, this breaks existing functionality for text-based models that have a head_size not in the optimized list [64, 128, 256, 512]. For those models, positions is a tensor of indices, and cos, sin = positions will raise an exception. This is a regression that needs to be fixed.

The logic should handle both cases: when positions is a tensor of indices and when it's a pre-computed (cos, sin) tuple.

            if isinstance(positions, torch.Tensor):
                # Handle tensor of position indices for text models
                if offsets is not None:
                    positions = positions + offsets
                positions = positions.flatten()
                cos_sin = self.cos_sin_cache.index_select(0, positions)
                cos, sin = cos_sin.chunk(2, dim=-1)
            else:
                # Handle pre-computed (cos, sin) tuple for vision models
                cos, sin = positions

            # Ensure tensors are float and contiguous for the kernel
            if cos.dtype != torch.float or not cos.is_contiguous():
                cos = cos.float().contiguous()
            if sin.dtype != torch.float or not sin.is_contiguous():
                sin = sin.float().contiguous()

            orig_q_dtype = query.dtype
            orig_k_dtype = key.dtype
            query, key = query.float(), key.float()

            self.sglang_rotary_embedding(
                cos,
                sin,
                query,
                key,
                self.head_size,
                self.is_neox_style,
            )

            query = query.to(dtype=orig_q_dtype)
            key = key.to(dtype=orig_k_dtype)

Comment on lines +431 to +438
self.rotary_emb = RotaryEmbedding(
head_size=self.head_size,
rotary_dim=self.head_size,
max_position_embeddings=2048,
base=10000,
is_neox_style=False,
dtype=torch.get_default_dtype(),
)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The RotaryEmbedding is initialized with hardcoded values for max_position_embeddings (2048) and base (10000). This reduces the reusability of the VisionAttention class for other models that may have different rotary embedding configurations. Consider passing these values as arguments to the __init__ method to make the component more flexible.

@AlienKevin AlienKevin changed the title Rotary emb kernel mick Fast rotary embedding Sep 16, 2025
Copy link
Copy Markdown
Collaborator

@FlamingoPg FlamingoPg left a comment

Choose a reason for hiding this comment

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

Over all LGTM

@FlamingoPg
Copy link
Copy Markdown
Collaborator

Looks some rope test failed.

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Copy link
Copy Markdown
Collaborator

@yuan-luo yuan-luo Sep 24, 2025

Choose a reason for hiding this comment

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

@JustinTong0323 JustinTong0323 added high priority ready-to-merge The PR is ready to merge after the CI is green. labels Sep 28, 2025
@mickqian
Copy link
Copy Markdown
Collaborator

mickqian commented Oct 1, 2025

@AlienKevin Do you have time to look into the failed Rope tests?

return q_embed, k_embed


class RotaryEmbedding(torch.nn.Module):
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I don't think this file is for mm_rotary_embedding.

@AlienKevin AlienKevin closed this by deleting the head repository Oct 11, 2025
@yuan-luo
Copy link
Copy Markdown
Collaborator

May I know why this PR was closed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

high priority ready-to-merge The PR is ready to merge after the CI is green. run-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants