Skip to content

Vulkan: fuse aten.rms_norm's decomposition into et_vk.rms_norm - #24119

Open
msluszniak wants to merge 6 commits into
pytorch:mainfrom
msluszniak:ms/vulkan-rms-norm-aten-decomp
Open

msluszniak wants to merge 6 commits into
pytorch:mainfrom
msluszniak:ms/vulkan-rms-norm-aten-decomp

Conversation

@msluszniak

@msluszniak msluszniak commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

F.rms_norm / nn.RMSNorm decompose to mean(dim=[ndim - 1]) and add.Scalar, but the RMSNorm pattern only matched dim=[-1] and add.Tensor. The norm stayed decomposed (fp16 sum of squares overflows on large activations) and add.Scalar split the delegate. Both spellings are now accepted. The weight must be a constant, and fp16 casts are looked through so fp16 RMSNorm fuses too. Weightless RMSNorm still splits on add.Scalar (follow-up).

Test plan

python -m unittest backends.vulkan.test.test_vulkan_passes (new rms_norm fusion, lowering and non-constant weight tests fail without the fix).

cc @SS-JIA @manuelcandales @digantdesai @cbilgin @nil-is-all

F.rms_norm and nn.RMSNorm decompose to mean(dim=[ndim - 1]) and add.Scalar,
while the pattern only accepted dim=[-1] and add.Tensor. The norm then ran
decomposed (fp16 overflow on large activations) and add.Scalar fell back to CPU,
splitting the delegate.
@msluszniak
msluszniak requested a review from SS-JIA as a code owner October 23, 2026 15:28
@pytorch-bot pytorch-bot Bot added the module: vulkan Issues related to the Vulkan delegate and code under backends/vulkan/ label Oct 23, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/24119

Note: Links to docs will display an error until the docs builds have been completed.

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Oct 23, 2026
@nil-is-all nil-is-all added the release notes: vulkan Changes to the Vulkan backend delegate label Oct 23, 2026
@executorch-triage executorch-triage Bot added the community: contribution PRs coming from community (excluding hardware partners) label Oct 23, 2026

@SS-JIA SS-JIA 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.

Requesting changes based on an independent, AI-assisted static review (Claude) of the current head, which I've gone through and agree with. Each finding is posted as an inline comment with a suggested fix; where a finding is about code outside this PR's diff, the comment sits on the closest related line and its Where line gives the actual location.

Summary

  • Change: widens RmsNormMatch to accept add.Scalar (in addition to add.Tensor), and mean dims [ndim - 1] (in addition to [-1]). Purpose: the aten.rms_norm decomposition (F.rms_norm, nn.RMSNorm) now fuses. Adds one fp32 graph-level test.
  • fp32 is correct: fused graph matches eager. The partitioner yields a single delegate, and the weight is a constant placeholder.
  • fp16 is broken. The decomposition casts the weight to fp32 via _to_dim_order_copy. That op is not in _CAST_OPS, so the fused op's weight is a runtime tensor _to_dim_order_copy(prepack(w)). RmsNorm.cpp calls prepack_standard(..., passthrough=false), which VK_CHECK_COND(graph.val_is_tref(...))-fails. Before this PR the same model stayed decomposed and ran.
  • The widened match also fuses F.rms_norm with a computed or runtime weight (e.g. 1 + w, adaptive scale), and chains of weightless F.rms_norm. Both hit the same non-tref-weight abort. Open PRs #22777 and #23808 add exactly the missing "weight must be a constant" guard. Neither has landed.
  • Merges cleanly with origin/main. Nothing under patterns/, partitioner/, op_registry.py or the test file changed since the PR's merge base. add.Scalar still has no standalone Vulkan implementation on main. WebGPU reuses VulkanPartitioner/vulkan_preprocess and will now receive et_vk.rms_norm for nn.RMSNorm. Its RmsNorm.cpp is fp32-only and reads the weight as a dense buffer.

# add.Scalar is what aten.rms_norm (F.rms_norm, nn.RMSNorm) decomposes to.
if add_node is None or add_node.target not in (
exir_ops.edge.aten.add.Tensor,
exir_ops.edge.aten.add.Scalar,

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.

A1 (High): fp16 nn.RMSNorm / F.rms_norm fuse with a non-constant weight, so the delegate aborts at init

  • Where: backends/vulkan/patterns/rms_norm.py:21-24 (_CAST_OPS), :193 (raw weight returned), :86-91 (new add.Scalar acceptance enables the match); runtime backends/vulkan/runtime/graph/ops/impl/RmsNorm.cpp:56, Staging.cpp:243.
  • Issue: For an fp16 model, the edge graph is copy(x→f32) → pow → mean([ndim-1]) → add.Scalar → rsqrt → mul → mul(·, copy(w→f32)) → copy(→f16). All casts are dim_order_ops._to_dim_order_copy, which _skip_casts does not unwrap. The match is found with weight_node = _to_dim_order_copy(w). After insert_prepack_nodes, the serialized et_vk.rms_norm weight arg is _to_dim_order_copy(et_vk.prepack(w)), a Tensor, not a TensorRef. add_rms_norm_node calls prepack_standard(graph, weight_data, ...) with passthrough=false, which hits VK_CHECK_COND(graph.val_is_tref(tensor_data)) and throws during graph build. Before this PR, add.Scalar blocked the match, and the decomposed ops ran correctly in split delegates. This is the PR's own motivating case (fp16 overflow).
  • Evidence (executed): spy on VkGraphBuilder during to_edge_transform_and_lower(..., [VulkanPartitioner()]).to_executorch():
    == fp16 nn.RMSNorm
    SERIALIZED rms_norm weight arg: call_function dim_order_ops._to_dim_order_copy.default is_constant= False
       weight producer input: [('call_function', 'et_vk.prepack.default')]
    == fp32 nn.RMSNorm
    SERIALIZED rms_norm weight arg: placeholder p_weight is_constant= True
    
    AOT lowering succeeds, so no Python-level test can catch this. The abort itself was not executed (no Vulkan runtime available). It follows directly from RmsNorm.cpp:56 and Staging.cpp:240-243.
  • Suggested fix: Minimum fix: reject matches whose weight is not a constant placeholder (the guard from Only fuse an RMS norm whose weight can be prepacked #22777, using utils.is_param_node(ep, weight) in the replacement). Land that first or fold it into this PR. Then fp16 stays unfused but correct. A better fix fuses the fp16 case properly. Add dim_order_ops._to_dim_order_copy.default to _CAST_OPS. Anchor on the trailing copy(→orig dtype) when present. Pass the un-cast x and w so the op is fp16-in/fp16-out; the shader already accumulates in fp32 (rms_norm_buffer.glsl:86-97). Add an fp16 test that checks the fused weight arg is a param node.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 416ea65: dtype casts are looked through and the trailing cast is fused, so fp16 nn.RMSNorm lowers to one fp16 et_vk.rms_norm with a constant weight. One side effect: WebGPU's RmsNorm is fp32-only, so fp16 RMSNorm now fails at WebGPU init with a clear error. Should I skip the pattern on WebGPU, like #24082 does?

Comment thread backends/vulkan/patterns/rms_norm.py Outdated
mean_dims = mean_node.args[1]
if mean_dims != [-1]:
ndim = len(mean_node.meta["val"].shape)
if mean_dims != [-1] and mean_dims != [ndim - 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.

A2 (Medium): widened match fuses computed / runtime / non-dense weights that the runtime cannot handle

  • Where: backends/vulkan/patterns/rms_norm.py:86-91, 116-117 (scope widening); _identify_norm_mul_and_weight (:180-195) never validates the weight.
  • Issue: The match now accepts every F.rms_norm spelling. That includes F.rms_norm(x, (D,), 1.0 + w) (Gemma-style), F.rms_norm(x, (D,), scale_input) (adaptive norm), and F.rms_norm(F.rms_norm(x, (D,)), (D,)). In the last case, the outer mul(inner_norm, rsqrt2) is mis-identified: rsqrt2 (shape [..., 1]) becomes the "weight". All three fuse, and the partitioner accepts fusable nodes unconditionally (vulkan_partitioner.py:300-301). At runtime, all three pass a non-TensorRef weight to prepack_standard and abort. The chained case would also index a [...,1] tensor as a dense [D] array (rms_norm_buffer.glsl:103). The bug class existed for hand-written add.Tensor patterns. This PR extends it to the standard PyTorch API.
  • Evidence (executed): ad-hoc FusePatternsPass runs: computed weight: fused=1, adaptive weight: fused=1, chained weightless: fused=1 (the fused graph's reference CPU impl is numerically equal, since it broadcasts the weight, so graph-level allclose does not catch it). Lowering computed weight via VulkanPartitioner puts aten.add.Tensor (for 1 + w) and et_vk.rms_norm in the same delegate.
  • Suggested fix: Same guard as A1: the weight must be a constant param (Only fuse an RMS norm whose weight can be prepacked #22777 / [vulkan][examples] Enable native Kev decision model inference on Vulkan backend #23808). Optionally also require weight.meta["val"].numel() == x.shape[-1].

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 416ea65: the weight must be a constant [hidden] param of the output dtype, enforced in the partitioner too, so computed, input and chained weights stay unfused with no add.Scalar in the delegate.

)
self.assertTrue(torch.allclose(fused_out, eager_ref, atol=1e-3, rtol=1e-3))

def test_fuse_aten_rms_norm(self):

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.

A3 (Medium): test coverage misses the dtype and pipeline the PR targets

  • Where: backends/vulkan/test/test_vulkan_passes.py:1081-1121.
  • Issue: The test only covers fp32 and calls FusePatternsPass directly on an edge program. It never covers fp16 (the stated motivation, and the broken case, A1). It never runs VulkanPartitioner, although the PR's second claim is that add.Scalar no longer splits the delegate. It never asserts the fused weight is a constant (A1/A2). There is no runtime correctness case (e.g. a test_vulkan_delegate model test or an etvk_ops_bench case) to exercise the shader path for F.rms_norm-produced graphs.
  • Suggested fix: Parametrize over torch.float16. Assert the fused op's args[1] is a param placeholder. Add a lowering test that asserts one executorch_call_delegate for nn.RMSNorm. Add negative cases (computed weight, runtime weight, chained weightless) that must not fuse. Add an end-to-end nn.RMSNorm model in the Vulkan delegate tests that CI runs on a real GPU.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 416ea65: fp16 coverage, a VulkanPartitioner lowering test, negative cases for non-constant weights, and test_vulkan_backend_rms_norm. Note vulkan.yml only runs the pt2e/torchao subset of test_vulkan_delegate.py, so the last one won't run in GitHub CI.

Comment thread backends/vulkan/patterns/rms_norm.py Outdated
rsqrt_node, exir_ops.edge.aten.rsqrt.default
)
if add_node is None or add_node.target != exir_ops.edge.aten.add.Tensor:
# add.Scalar is what aten.rms_norm (F.rms_norm, nn.RMSNorm) decomposes to.

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.

A4 (Low): weightless nn.RMSNorm(elementwise_affine=False) / F.rms_norm(weight=None) still splits the delegate

  • Where: backends/vulkan/patterns/rms_norm.py detector (anchor must be a weight-mul); op_registry.py (no add.Scalar).
  • Issue: The PR summary says add.Scalar split the delegate and is now accepted. That holds only when the pattern fuses. Without a weight, there is no anchor mul, add.Scalar remains unsupported, and lowering yields two delegates with aten.add.Scalar on CPU.
  • Evidence (executed): no affine top-level ops: ['executorch_call_delegate', getitem, 'aten.add.Scalar', 'executorch_call_delegate', getitem]; partitioner log: Due to [no operator implementation], skipping ... aten.add.Scalar.
  • Suggested fix: Out of scope to fully fix here. Either narrow the PR description, or register add.Scalar (e.g. by lowering it to add.Tensor with a scalar constant) in a follow-up.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, leaving it out of scope here.

if add_node is None or add_node.target not in (
exir_ops.edge.aten.add.Tensor,
exir_ops.edge.aten.add.Scalar,
):

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.

A5 (Low): alpha of add.Scalar / add.Tensor is ignored when extracting eps

  • Where: backends/vulkan/patterns/rms_norm.py:86-104, _extract_eps_value.
  • Issue: add.Scalar(self, other, alpha) computes self + alpha*other. A hand-written torch.add(ms, eps, alpha=a) with a != 1 fuses with eps = eps instead of a*eps. The decomposition always uses alpha=1, so this is a robustness gap. The PR widened it to add.Scalar; it already existed for add.Tensor.
  • Suggested fix: if add_node.kwargs.get("alpha", add_node.args[2] if len(add_node.args) > 2 else 1) != 1: return.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 416ea65, a non-unit alpha is no longer matched.

Comment thread backends/vulkan/patterns/rms_norm.py Outdated
return
mean_dims = mean_node.args[1]
if mean_dims != [-1]:
ndim = len(mean_node.meta["val"].shape)

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.

A6 (Nit): dim check and stale comments

  • Where: backends/vulkan/patterns/rms_norm.py:47, 82, 111-120.
  • Issue: ndim comes from the mean output before keepdim is verified. That is correct only because the keepdim check follows. mean_node.meta["val"] raises KeyError if a prior pass dropped meta, while the rest of the matcher bails out gracefully. The docstring (:47) and the step comment (:82) still say dim=-1 and add(eps) only.
  • Suggested fix:
    ndim = mean_node.args[0].meta["val"].dim()
    if [d % ndim for d in mean_node.args[1]] != [ndim - 1]:
        return
    Update the two comments.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 416ea65.

et_vk.rms_norm prepacks its weight, so a computed weight (1 + w), a graph
input weight or the rsqrt of a chained weightless norm aborted at delegate
init. The detector now requires the weight to be a placeholder of shape
[hidden] in the output dtype, and the partitioner and the replacement require
it to be a constant.

In fp16 the aten.rms_norm decomposition casts with _to_dim_order_copy, which
was not looked through, so the weight reached the op as a cast tensor. The
pattern now looks through it and fuses the trailing cast, so the op runs fp16
in, fp16 out with the fp16 weight. Also reject a non-unit add alpha and
normalize the mean dims against the input rank.

@SS-JIA SS-JIA 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.

@msluszniak LGTM!

@SS-JIA

SS-JIA commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@msluszniak could you try rebasing the branch? I think that will be needed in order to trigger required signals to run

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

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. community: contribution PRs coming from community (excluding hardware partners) module: vulkan Issues related to the Vulkan delegate and code under backends/vulkan/ release notes: vulkan Changes to the Vulkan backend delegate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants