Repository navigation
Vulkan: fuse aten.rms_norm's decomposition into et_vk.rms_norm - #24119
msluszniak wants to merge 6 commits into
Conversation
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.
🔗 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. |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SS-JIA
left a comment
There was a problem hiding this comment.
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
RmsNormMatchto acceptadd.Scalar(in addition toadd.Tensor), andmeandims[ndim - 1](in addition to[-1]). Purpose: theaten.rms_normdecomposition (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.cppcallsprepack_standard(..., passthrough=false), whichVK_CHECK_COND(graph.val_is_tref(...))-fails. Before this PR the same model stayed decomposed and ran. - The widened match also fuses
F.rms_normwith a computed or runtime weight (e.g.1 + w, adaptive scale), and chains of weightlessF.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.pyor the test file changed since the PR's merge base.add.Scalarstill has no standalone Vulkan implementation on main. WebGPU reusesVulkanPartitioner/vulkan_preprocessand will now receiveet_vk.rms_normfornn.RMSNorm. ItsRmsNorm.cppis 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, |
There was a problem hiding this comment.
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(newadd.Scalaracceptance enables the match); runtimebackends/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 aredim_order_ops._to_dim_order_copy, which_skip_castsdoes not unwrap. The match is found withweight_node = _to_dim_order_copy(w). Afterinsert_prepack_nodes, the serializedet_vk.rms_normweight arg is_to_dim_order_copy(et_vk.prepack(w)), aTensor, not aTensorRef.add_rms_norm_nodecallsprepack_standard(graph, weight_data, ...)withpassthrough=false, which hitsVK_CHECK_COND(graph.val_is_tref(tensor_data))and throws during graph build. Before this PR,add.Scalarblocked 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
VkGraphBuilderduringto_edge_transform_and_lower(..., [VulkanPartitioner()]).to_executorch():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== 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= TrueRmsNorm.cpp:56andStaging.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. Adddim_order_ops._to_dim_order_copy.defaultto_CAST_OPS. Anchor on the trailingcopy(→orig dtype)when present. Pass the un-castxandwso 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.
There was a problem hiding this comment.
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?
| 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]: |
There was a problem hiding this comment.
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_normspelling. That includesF.rms_norm(x, (D,), 1.0 + w)(Gemma-style),F.rms_norm(x, (D,), scale_input)(adaptive norm), andF.rms_norm(F.rms_norm(x, (D,)), (D,)). In the last case, the outermul(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-TensorRefweight toprepack_standardand 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-writtenadd.Tensorpatterns. This PR extends it to the standard PyTorch API. - Evidence (executed): ad-hoc
FusePatternsPassruns: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). Loweringcomputed weightviaVulkanPartitionerputsaten.add.Tensor(for1 + w) andet_vk.rms_normin 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].
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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
FusePatternsPassdirectly on an edge program. It never covers fp16 (the stated motivation, and the broken case, A1). It never runsVulkanPartitioner, although the PR's second claim is thatadd.Scalarno longer splits the delegate. It never asserts the fused weight is a constant (A1/A2). There is no runtime correctness case (e.g. atest_vulkan_delegatemodel test or anetvk_ops_benchcase) to exercise the shader path forF.rms_norm-produced graphs. - Suggested fix: Parametrize over
torch.float16. Assert the fused op'sargs[1]is a param placeholder. Add a lowering test that asserts oneexecutorch_call_delegatefornn.RMSNorm. Add negative cases (computed weight, runtime weight, chained weightless) that must not fuse. Add an end-to-endnn.RMSNormmodel in the Vulkan delegate tests that CI runs on a real GPU.
There was a problem hiding this comment.
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.
| 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. |
There was a problem hiding this comment.
A4 (Low): weightless nn.RMSNorm(elementwise_affine=False) / F.rms_norm(weight=None) still splits the delegate
- Where:
backends/vulkan/patterns/rms_norm.pydetector (anchor must be a weight-mul);op_registry.py(noadd.Scalar). - Issue: The PR summary says
add.Scalarsplit the delegate and is now accepted. That holds only when the pattern fuses. Without a weight, there is no anchor mul,add.Scalarremains unsupported, and lowering yields two delegates withaten.add.Scalaron 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 toadd.Tensorwith a scalar constant) in a follow-up.
There was a problem hiding this comment.
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, | ||
| ): |
There was a problem hiding this comment.
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)computesself + alpha*other. A hand-writtentorch.add(ms, eps, alpha=a)witha != 1fuses with eps =epsinstead ofa*eps. The decomposition always usesalpha=1, so this is a robustness gap. The PR widened it toadd.Scalar; it already existed foradd.Tensor. - Suggested fix:
if add_node.kwargs.get("alpha", add_node.args[2] if len(add_node.args) > 2 else 1) != 1: return.
There was a problem hiding this comment.
Done in 416ea65, a non-unit alpha is no longer matched.
| return | ||
| mean_dims = mean_node.args[1] | ||
| if mean_dims != [-1]: | ||
| ndim = len(mean_node.meta["val"].shape) |
There was a problem hiding this comment.
A6 (Nit): dim check and stale comments
- Where:
backends/vulkan/patterns/rms_norm.py:47, 82, 111-120. - Issue:
ndimcomes from the mean output before keepdim is verified. That is correct only because the keepdim check follows.mean_node.meta["val"]raisesKeyErrorif a prior pass dropped meta, while the rest of the matcher bails out gracefully. The docstring (:47) and the step comment (:82) still saydim=-1andadd(eps)only. - Suggested fix:
Update the two comments.
ndim = mean_node.args[0].meta["val"].dim() if [d % ndim for d in mean_node.args[1]] != [ndim - 1]: return
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.
|
@msluszniak could you try rebasing the branch? I think that will be needed in order to trigger required signals to run |
# Conflicts: # backends/vulkan/patterns/rms_norm.py
Summary
F.rms_norm/nn.RMSNormdecompose tomean(dim=[ndim - 1])andadd.Scalar, but the RMSNorm pattern only matcheddim=[-1]andadd.Tensor. The norm stayed decomposed (fp16 sum of squares overflows on large activations) andadd.Scalarsplit 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 onadd.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