Skip to content

Use F.rms_norm in RMSNorm when there is no affine weight - #15458

Open
Shan2L wants to merge 1 commit into
huggingface:mainfrom
Shan2L:users/syliu/rmsnorm-no-affine-fused
Open

Shan2L wants to merge 1 commit into
huggingface:mainfrom
Shan2L:users/syliu/rmsnorm-no-affine-fused

Conversation

@Shan2L

@Shan2L Shan2L commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #15457.

RMSNorm(elementwise_affine=False) ran pow, mean, rsqrt, a multiply and a cast as separate kernels. When there is no weight, forward now calls F.rms_norm, which does the same computation in one kernel. The affine path and the NPU path are unchanged.

On a [1, 8160, 4096] input (960x544x121 LTX-2 video tokens), per call, torch 2.14.0+rocm10.1.0:

GPU dtype before after
Radeon AI PRO R9600D bf16 1.704 ms 0.259 ms
Radeon AI PRO R9600D fp16 1.699 ms 0.258 ms
Radeon AI PRO R9600D fp32 1.135 ms 0.452 ms
Radeon AI PRO R9700 bf16 1.701 ms 0.226 ms
Radeon AI PRO R9700 fp16 1.699 ms 0.228 ms

The output is not bitwise identical: for bf16, 165 of 33,423,360 elements differ, by one bf16 step at most (fp16: 1,207 elements, one fp16 step; fp32: 24.7% of elements, at most 9.5e-7). The error against an fp32 reference on the largest values is unchanged in bf16 and fp16. The output dtype is unchanged.

Tests:

  • New RMSNormTests in tests/models/test_layers_utils.py: the no-affine output matches the explicit fp32 formula in fp32, fp16 and bf16 and keeps the input dtype. It fails if eps is changed in the new call.
  • tests/models/transformers/test_models_transformer_ltx2.py (includes the torch.compile tests) and tests/models/test_layers_utils.py, torch 2.14.0+rocm10.1.0: on main (facc812ea, Radeon AI PRO R9600D) no failure or error; with this change (Radeon AI PRO R9700) the same results plus the new test, also no failure or error.
  • tests/pipelines/ltx2/test_ltx2.py was not run to completion. On main and on this branch the first 71 results are identical, including two errors at the same position, and the file takes more than an hour on this setup, so I stopped both runs.

Self-review notes (diffusers self-review skill)

  • Rubric from .ai/references/review-rules.md, read against the whole diff (two source lines and one test class).
  • Blocking issues: none. utils/check_copies.py passes (no # Copied from copy of RMSNorm exists); ruff 0.17.5 reports no issue on the changed files (the repo pins 0.9.10, which I did not install).
  • Non-blocking, left for review:
    • the output differs from the current implementation by one rounding step on rare elements (numbers above);
    • the affine path is still the multi-kernel version;
    • the NPU branch is unchanged and I did not run on NPU; F.rms_norm is used only where the previous code already took the pure-PyTorch route.
  • Dead code: none.
  • Verdict: READY.

Before submitting

  • Did you use an AI agent (Claude Code, Codex, Cursor, etc.) to help with this PR? If so:
    • Did you read the Coding with AI agents guide?
    • Did you run the self-review skill on the diff?
    • Did you share the final self-review notes in the PR description or a comment?
  • Did you read the contributor guideline?
  • Did you read our philosophy doc? (important for complex PRs)
  • Was this discussed/approved via a GitHub issue or GitHub Discussions? Please add a link to it if that's the case.
  • Did you make sure to update the documentation with your changes? No documentation change is needed.
  • Did you write any new necessary tests?
  • Are you the author (or part of the team we work with) of the model/pipeline this PR relates to?

Who can review?

@yiyixuxu @sayakpaul

Signed-off-by: Sylvan Liu <Sylvan.Liu@amd.com>

@sayakpaul sayakpaul left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the PR! How does the CUDA runtime get affected for this? Also, should this change be propagated to other RMS norm layers (model-specific) that we have under src/diffusers/models?

@yiyixuxu WDYT?

@sayakpaul
sayakpaul requested a review from yiyixuxu December 3, 2026 04:01
@Shan2L

Shan2L commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @sayakpaul.

CUDA: F.rms_norm goes through the same dispatch on CUDA as on ROCm. When there is no weight (or the weight has the input dtype), rms_norm calls at::_fused_rms_norm, which has a CUDA kernel, so CUDA gets one kernel instead of the five it runs today (pow, mean, rsqrt, multiply, cast). I could not measure it: I have no NVIDIA GPU. The numerics are the same as on ROCm: fp32 accumulation, so results can differ from the current path by one ulp of the output dtype, as listed in the description. If someone can run the snippet in #15457 on a CUDA card, that would confirm the speedup there.

Other RMS norms: there are 8 model-specific RMSNorm classes under src/diffusers/models (LTX-2 VAE, Mochi, Cosmos3, Krea2, QwenImage 2.1, Stable Audio 3, Kandinsky 6 SR and its latent upscaler). Each has its own dtype handling and, for some, checkpoint-specific numerics, so I would keep this PR to the shared RMSNorm and handle the others in a separate PR if you and @yiyixuxu want that.

@sayakpaul

Copy link
Copy Markdown
Member

CUDA: F.rms_norm goes through the same dispatch on CUDA as on ROCm. When there is no weight (or the weight has the input dtype), rms_norm calls at::_fused_rms_norm, which has a CUDA kernel, so CUDA gets one kernel instead of the five it runs today (pow, mean, rsqrt, multiply, cast). I could not measure it: I have no NVIDIA GPU. The numerics are the same as on ROCm: fp32 accumulation, so results can differ from the current path by one ulp of the output dtype, as listed in the description. If someone can run the snippet in #15457 on a CUDA card, that would confirm the speedup there.

Which snippet are you referring to?

@Shan2L

Shan2L commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Sorry, that was wrong: #15457 has no snippet. Here is a standalone one that compares the elementwise_affine=False path on main with this PR (no diffusers import needed):

import torch
import torch.nn.functional as F


def old_no_affine(x, eps=1e-6):
    # RMSNorm.forward on main when weight is None
    variance = x.to(torch.float32).pow(2).mean(-1, keepdim=True)
    return (x * torch.rsqrt(variance + eps)).to(x.dtype)


def new_no_affine(x, eps=1e-6):
    # this PR
    return F.rms_norm(x, x.shape[-1:], eps=eps)


def bench(fn, x, iters=50):
    for _ in range(5):
        fn(x)
    torch.cuda.synchronize()
    start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
    start.record()
    for _ in range(iters):
        fn(x)
    end.record()
    torch.cuda.synchronize()
    return start.elapsed_time(end) / iters


print(torch.__version__, torch.cuda.get_device_name(0))
for dtype in (torch.bfloat16, torch.float16, torch.float32):
    x = torch.randn(1, 8160, 4096, device="cuda", dtype=dtype)  # LTX-2 960x544x121 video tokens
    old, new = old_no_affine(x), new_no_affine(x)
    print(
        f"{dtype}: old {bench(old_no_affine, x):.3f} ms, new {bench(new_no_affine, x):.3f} ms, "
        f"max |new - old| {(new.float() - old.float()).abs().max().item():.3e}"
    )

Output on a Radeon AI PRO R9700, torch 2.14.0+rocm10.1.0:

torch.bfloat16: old 1.698 ms, new 0.225 ms, max |new - old| 1.562e-02
torch.float16: old 1.698 ms, new 0.225 ms, max |new - old| 1.953e-03
torch.float32: old 1.141 ms, new 0.460 ms, max |new - old| 9.537e-07

The bf16/fp16 differences are one step of the output dtype at the largest values, as in the description.

@sayakpaul

Copy link
Copy Markdown
Member

Do you have a suggestion on which NVIDIA card I should try it out on?

@Shan2L

Shan2L commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Any CUDA card you have handy works; the input is 1 x 8160 x 4096, so under 1 GB of memory. The op is memory-bound, so one datacenter card (A100 or H100) and, if you have one, a consumer card (for example an RTX 4090) would cover the range. Please include the torch version in the output: I have not checked which release first dispatches F.rms_norm to the fused CUDA kernel, so an older torch may still run the composite path.

@sayakpaul

Copy link
Copy Markdown
Member

Ran the snippet on A100 and L40 using HF Jobs:

image

Used Torch 2.14.0+cu126

@Shan2L

Shan2L commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for running it, @sayakpaul. A100 and L40S show the same picture as the R9700: about 8x for bf16 and fp16, about 2x for fp32, and the same max differences.

This branch has not been deployed

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RMSNorm without affine weight runs as five or six kernels; F.rms_norm is 2.5-7.5x faster (not bitwise identical)

2 participants