Repository navigation
[Diffusion][Refactor] Refactor and extract complex RoPE implementation to layers/rotary_embedding for MOVA DiT - #31453
Conversation
There was a problem hiding this comment.
Code Review
This pull request refactors the rotary positional embedding logic in the MOVA audio and video DiT models to use the unified NDRotaryEmbedding class and a new complex rotary embedding utility, replacing manual precomputation and sharding routines. In the sequence parallelism pipeline, frequencies are now computed dynamically per rank based on local token offsets. The review feedback suggests improving robustness against non-contiguous tensors by calling .contiguous() before torch.view_as_complex in the new utility and using .reshape instead of .view on the attention output.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| b, s, h, d = x.shape | ||
| dtype_c = torch.float32 | ||
|
|
||
| x_complex = torch.view_as_complex(x.to(dtype_c).reshape(b, s, h, d // 2, 2)) |
There was a problem hiding this comment.
To ensure robustness and prevent potential runtime errors when _apply_rotary_emb_complex is reused with non-contiguous inputs, it is safer to call .contiguous() on the reshaped tensor before passing it to torch.view_as_complex. torch.view_as_complex requires the input tensor to have a stride of 1 along its last dimension, which is not guaranteed for non-contiguous tensors.
| x_complex = torch.view_as_complex(x.to(dtype_c).reshape(b, s, h, d // 2, 2)) | |
| x_complex = torch.view_as_complex(x.to(dtype_c).reshape(b, s, h, d // 2, 2).contiguous()) |
| # SP padding out of the softmax. | ||
| out = self.attn(q, k, v, attn_mask_meta=attn_mask_meta) | ||
| out = rearrange(out, "b s n d -> b s (n d)") | ||
| out = out.view(b, s, -1) |
There was a problem hiding this comment.
Using .reshape(b, s, -1) instead of .view(b, s, -1) is safer here. The output of the attention block (self.attn) might be non-contiguous depending on the underlying attention backend or sequence parallelism communication, which would cause .view() to raise a runtime error.
| out = out.view(b, s, -1) | |
| out = out.reshape(b, s, -1) |
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
do you test other models with complex RoPE, and can we get performance gain from it?
can you explain why we can get performance gain if we just move such RoPE from model to common dir? |
|
/tag-and-rerun-ci |
|
Thank you for the review!
|
…n-transport1 * 'main' of https://github.com/sgl-project/sglang: (255 commits) [Perf] Hoist DSv4 draft-extend SWA write locs; unify SWA graph buffer naming (sgl-project#34890) [Chore] Move version tag helper to release scripts (sgl-project#35196) [DSV4] Turn on mhc post pre fusion by default (sgl-project#35214) [diffusion] Per-section LoRA adapters on fused linear layers (sgl-project#34933) [XPU] Fix decode graph runner is_current_stream_capturing on non-CUDA devices (sgl-project#35050) [AMD] Update amd k3 cookbook for PR#34580 (sgl-project#35263) [Diffusion][Refactor] Refactor and extract complex RoPE implementation to layers/rotary_embedding for MOVA DiT (sgl-project#31453) refactor: rename chat response token IDs (sgl-project#35225) [mem_cache][8/N] refactor: move MambaPoolHost to pool_host.mamba (sgl-project#31180) [AMD] Fix Quark Shared Experts Fusion Gate after load-time-override Removal (sgl-project#35200) [AMD] Scope the EAGLE greedy-verify TP broadcast to ROCm only (sgl-project#35195) [AMD] Add the Kimi-K3 MI35x perf benchmarks in nightly (sgl-project#34985) Skip inkling sheared bias under batch invariance (sgl-project#35161) [AMD] Optimize KIMI-K3 with Triton MLA decode kernel by tuning the stage-1 geometry for gfx950 (sgl-project#34580) [Docs] Enable PD disaggregation for DSV4 low-latency recipes (sgl-project#35224) [DCP] Drop the prefill index-selection syncs by taking each rank's rows by stride (sgl-project#35084) [Feature] Optimize TP LMHead with All-to-All (sgl-project#32313) [XPU] Enable fused GDN QKV split Triton kernel on XPU (sgl-project#30144) [CPU] Explicitly import sgl_kernel in CPU kernel tests (sgl-project#35119) [diffusion] feat: load quantized H3 text encoder checkpoints (sgl-project#34986) ... # Conflicts: # python/sglang/srt/multimodal/processors/base_processor.py
Motivation
SGLang has a dedicated directory (
layers/rotary_embedding) designed to house unified, high-performance Rotary Positional Embedding implementations.Was observed that a complex-valued RoPE representation is highly efficient for the
neox_style=Falseandinterleaved=Trueconfigurations. However, implementing this complex multiplication logic directly within model-specific code leads to duplication and limits its reusability.Since this optimized complex RoPE path is generic, mathematically clean, and performant, it is logical to extract the implementation out of the model code and move it into the shared
layers/rotary_embedding/utils.pyutility module. This enables other models within SGLang using interleaved RoPE to easily inherit and reuse this optimization.Modifications
Were modified 4 key files to implement this refactoring and optimization:
1.
sglang/multimodal_gen/runtime/layers/rotary_embedding/utils.py_apply_rotary_emb_complexfunction:xof shape[batch, num_tokens, num_heads, head_size].freqsof shape[num_tokens, 1, head_size // 2].x.view()transformations to group activation dimensions and cast tofloat32. It then performs a single vectorized complex multiplication kernel. Callingtorch.view_as_real()on the result natively lays out the real and imaginary elements sequentially in memory, producing the interleaved layout. This excludes the need fortorch.stack()and.contiguous()allocations.2.
sglang/multimodal_gen/runtime/layers/rotary_embedding/__init__.py_apply_rotary_emb_complexutility in the package exports: imported the function from.utils.pyand added it to the__all__list to expose it cleanly to the rest of the codebase.3.
sglang/multimodal_gen/runtime/models/dits/mova_video_dit.pyandmova_audio_dit.pyCleaned up the attention blocks and models:
SelfAttention.forward, reshapeq,k, andvto[B, S, H, D]format usingview()operations, and apply the_apply_rotary_emb_complexdirectly. This eliminatesrearrangeandflattensteps inside the attention loop.Accuracy Tests
raccoon.mp4
Speed Tests and Profiling
1. SGLang Server Launch Command
2. Video Generation Request
3. Offline Profiling Command
4. Profiler Latency Results (Ascend NPU)
The table below compares the detailed execution times of the rope functions on NPU before and after modifications:
Checklist
Review and Merge Process
/tag-and-rerun-ci,/tag-run-ci-label,/rerun-failed-ciCI States
Latest PR Test (Base): ❌ Run #32064673694
Latest PR Test (Extra): ❌ Run #32064673343