[Diffusion] safe fallback for fused QK-norm#16329
[Diffusion] safe fallback for fused QK-norm#16329RubiaCx wants to merge 2 commits intosgl-project:mainfrom
Conversation
Summary of ChangesHello @RubiaCx, 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 significantly enhances the stability and compatibility of the fused QK-norm kernel by implementing a robust fallback mechanism. It ensures that the QK-norm operation functions reliably across various hardware and tensor configurations, specifically addressing issues with non-NVIDIA CUDA environments and non-applicable tensor layouts. The changes streamline the execution flow by conditionally applying the optimized fused kernel and reverting to standard PyTorch normalization when the fused path is not viable, thereby preventing runtime errors and maintaining consistent behavior. Additionally, it includes minor cleanups and optimizations in the Qwen image transformer model. 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. 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 a safe fallback for the fused QK-norm kernel, enhancing its robustness on different hardware and layouts. The changes correctly add a try-except block to fall back to a standard PyTorch RMSNorm implementation when the fused kernel is not applicable. Additionally, there are good optimizations in qwen_image.py that move computations from CPU to GPU. My review includes suggestions to improve maintainability by reducing code duplication and making the error handling more robust. I've also pointed out a small opportunity for code simplification in the fallback logic.
| def can_view_as_bnhd(x: torch.Tensor) -> bool: | ||
| """Whether `x` can be viewed as [batch, *, head_dim] without a copy.""" | ||
| if ( | ||
| x.dim() < 2 | ||
| or x.size(0) != batch_size | ||
| or x.size(-1) != head_dim | ||
| or x.stride(-1) != 1 | ||
| or x.stride(-2) != head_dim | ||
| ): | ||
| return False | ||
| try: | ||
| x.view(batch_size, -1, head_dim) | ||
| return True | ||
| except RuntimeError: | ||
| return False |
| except RuntimeError as e: | ||
| if "QK-norm is not applicable" not in str(e): | ||
| raise |
There was a problem hiding this comment.
The fallback logic relies on checking for the substring "QK-norm is not applicable" in the RuntimeError message. This is fragile and could break if the error message from the underlying JIT kernel changes in the future. It would be more robust to catch a custom, specific exception type raised by the kernel. If that's not feasible, this is an accepted risk, but worth noting.
| if allow_inplace and q.is_contiguous() and q_out.shape == q.shape: | ||
| q.copy_(q_out) | ||
| q_out = q | ||
| if allow_inplace and k.is_contiguous() and k_out.shape == k.shape: | ||
| k.copy_(k_out) | ||
| k_out = k |
There was a problem hiding this comment.
The shape checks q_out.shape == q.shape and k_out.shape == k.shape are likely redundant. RMSNorm preserves the tensor shape, so the output shape of q_norm(q) and k_norm(k) should always be the same as their respective inputs. You could simplify this by removing these shape checks for clarity.
| if allow_inplace and q.is_contiguous() and q_out.shape == q.shape: | |
| q.copy_(q_out) | |
| q_out = q | |
| if allow_inplace and k.is_contiguous() and k_out.shape == k.shape: | |
| k.copy_(k_out) | |
| k_out = k | |
| if allow_inplace and q.is_contiguous(): | |
| q.copy_(q_out) | |
| q_out = q | |
| if allow_inplace and k.is_contiguous(): | |
| k.copy_(k_out) | |
| k_out = k |
| def can_view_as_bnhd(x: torch.Tensor) -> bool: | ||
| """Whether `x` can be viewed as [batch, *, head_dim] without a copy.""" | ||
| if ( | ||
| x.dim() < 2 | ||
| or x.size(0) != batch_size | ||
| or x.size(-1) != head_dim | ||
| or x.stride(-1) != 1 | ||
| or x.stride(-2) != head_dim | ||
| ): | ||
| return False | ||
| try: | ||
| x.view(batch_size, -1, head_dim) | ||
| return True | ||
| except RuntimeError: | ||
| return False |
| except RuntimeError as e: | ||
| if "QK-norm is not applicable" not in str(e): | ||
| raise |
There was a problem hiding this comment.
The fallback logic relies on checking for the substring "QK-norm is not applicable" in the RuntimeError message. This is fragile and could break if the error message from the underlying JIT kernel changes in the future. It would be more robust to catch a custom, specific exception type raised by the kernel. This same issue exists in python/sglang/multimodal_gen/runtime/layers/layernorm.py.
|
Already sloved by #16287, closed. |
Motivation
The fused QK-norm kernel used here was introduced in #16062, and this PR ensures it does not break on non-applicable layouts or ROCm (AMD CI) while keeping QK-norm behavior consistent when enabled.

Modifications
Remove
_is_cuda()gating at callsites; always callapply_qk_normwhenself.qk_normis enabled.In
apply_qk_norm, only call the fused kernel on NVIDIA CUDA (q.is_cuda and torch.version.cuda is not None) and valid layouts; if it raises "QK-norm is not applicable", fall back to the RMSNorm path; re-raise other errors.Checklist