Skip to content

[Diffusion][Refactor] Refactor and extract complex RoPE implementation to layers/rotary_embedding for MOVA DiT - #31453

Merged
sglang-npu-bot merged 15 commits into
sgl-project:mainfrom
Allor-maker:rope_mova_unification
Aug 18, 2026
Merged

sglang-npu-bot merged 15 commits into
sgl-project:mainfrom
Allor-maker:rope_mova_unification

Conversation

@Allor-maker

@Allor-maker Allor-maker commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

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=False and interleaved=True configurations. 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.py utility 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

  • Added the _apply_rotary_emb_complex function:
    • Inputs:
      • x of shape [batch, num_tokens, num_heads, head_size].
      • freqs of shape [num_tokens, 1, head_size // 2].
    • Outputs: Evaluated tensor of the same shape and dtype as x.
    • Optimization Details: It utilizes view() transformations to group activation dimensions and cast to float32. It then performs a single vectorized complex multiplication kernel. Calling torch.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 for torch.stack() and .contiguous() allocations.

2. sglang/multimodal_gen/runtime/layers/rotary_embedding/__init__.py

  • Registered the new _apply_rotary_emb_complex utility in the package exports: imported the function from .utils.py and 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.py and mova_audio_dit.py

Cleaned up the attention blocks and models:

  • Removed custom inline complex RoPE functions.
  • In SelfAttention.forward, reshape q, k, and v to [B, S, H, D] format using view() operations, and apply the _apply_rotary_emb_complex directly. This eliminates rearrange and flatten steps inside the attention loop.

Accuracy Tests

raccoon.mp4

Speed Tests and Profiling

1. SGLang Server Launch Command

sglang serve --model-path $(pwd)/mova_video_360p --pipeline-class-name MOVAPipeline --num-gpus 4 --ring-degree 1 --ulysses-degree 4 --performance-mode memory --dit-layerwise-offload --dit-offload-prefetch-size 0.1 --text-encoder-cpu-offload true --vae-cpu-offload true --enable-torch-compile --warmup-mode server --vae-tiling --vae-sp

2. Video Generation Request

curl -X POST "http://localhost:30000/v1/videos" -F "prompt=A curious raccoon" -F "input_reference=@/.../images/raccoon.png" -F "size=640x352"  -F "num_frames=49" -F "fps=24" -F "num_inference_steps=25" -F "guidance_scale=5.0" -o create_video.json

3. Offline Profiling Command

SGLANG_DIFFUSION_TORCH_PROFILER_DIR="/home/s60128115/profile_complex" sglang generate --model-path /home/s60128115/models/mova_video_360p --pipeline-class-name MOVAPipeline --prompt "A curious raccoon" --image-path /home/s60128115/images/raccoon.png --width 640 --height 352 --num-frames 49 --fps 24 --num-inference-steps 25 --guidance-scale 5.0 --profile --num-profiled-timesteps 10 --num-gpus 4 --ulysses-degree 4 --enable-torch-compile --warmup-mode request --dit-layerwise-offload --dit-offload-prefetch-size 0.1

4. Profiler Latency Results (Ascend NPU)

The table below compares the detailed execution times of the rope functions on NPU before and after modifications:

Implementation func_name time(%) total_time(us) num_calls Avg(us) Min(us) Max(us)
Baseline rope_apply_head_dim 100 8983898.08 3080 2916.85 2378.38 7904.13
Modified _apply_rotary_emb_complex 100 7139799.61 3080 2318.1168 2021.59 5624.96

Checklist

Review and Merge Process

  1. Ping Merge Oncalls to start the process. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR.

CI States

Latest PR Test (Base): ❌ Run #32064673694
Latest PR Test (Extra): ❌ Run #32064673343

@github-actions github-actions Bot added the diffusion SGLang Diffusion label Jul 16, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

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.

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))

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

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.

Suggested change
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)

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

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.

Suggested change
out = out.view(b, s, -1)
out = out.reshape(b, s, -1)

@Allor-maker
Allor-maker marked this pull request as ready for review August 3, 2026 14:12
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@Makcum888e Makcum888e left a comment

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.

LGTM

@Allor-maker Allor-maker changed the title Refactor and extract complex RoPE implementation to layers/rotary_embedding for MOVA DiT [Diffusion][Refactor] Refactor and extract complex RoPE implementation to layers/rotary_embedding for MOVA DiT Aug 3, 2026
@ping1jing2 ping1jing2 self-assigned this Aug 5, 2026
@ping1jing2

Copy link
Copy Markdown
Collaborator

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.py utility module. This enables other models within SGLang using interleaved RoPE to easily inherit and reuse this optimization.

do you test other models with complex RoPE, and can we get performance gain from it?

  1. Profiler Latency Results (Ascend NPU)

can you explain why we can get performance gain if we just move such RoPE from model to common dir?

@ping1jing2

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Aug 6, 2026
@Allor-maker

Copy link
Copy Markdown
Contributor Author

Thank you for the review!

  1. I also tested the QwenImage model, and the _apply_rotary_emb_complex function allowed for improved performance, as seen in the table. This function is relevant for models using the RoPE parameter with is_neox_style=False on NPU, as this implementation is faster than the current fallback for this type of device and argument. I am currently preparing a PR with a class that unifies the call to RoPE, which will be used in subsequent PRs to analyze performance on other DIT models.
Implementation func_name time(%) total_time(us) num_calls Avg(us) Min(us) Max(us)
Baseline apply_rotary_embedding_native 100 13628501.78 2448 5567.1984 4108.45 12372.26
Modified _apply_rotary_emb_complex 100 9655076.15 2448 3944.0671 2750.82 8124
  1. In the current implementation, the calls to rearrange and flatten have been replaced with view, which slightly improves performance.

@sglang-npu-bot
sglang-npu-bot merged commit 61600c9 into sgl-project:main Aug 18, 2026
127 of 141 checks passed
longxin9715 added a commit to longxin9715/sglang that referenced this pull request Aug 18, 2026
…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
@Allor-maker
Allor-maker deleted the rope_mova_unification branch October 14, 2026 12:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

diffusion SGLang Diffusion run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants