Skip to content

Commit 98b49e8

Browse files
Add rank-4 RMSNormalization reshape rule for QNN HTP (#372)
## What A rewrite rule that reshapes rank-4 `RMSNormalization` (query/key norm) to rank-3 for the QNN HTP, which miscomputes RMSNormalization over the last axis of a rank-4 tensor. ## Why Gemma-4 (and Qwen3) apply RMSNormalization over the head dimension after reshaping q/k to `(batch, seq, heads, head_dim)`, so the norm runs on a rank-4 tensor. On the Hexagon HTP this computes incorrectly -- the graph finalizes but the q/k-norm output is numerically wrong (uncorrelated with CPU); rank-3 RMSNormalization runs correctly. Pairs with the QNN EP profile (#370): that targets the HTP, this makes the q/k-norm graph compute correctly there. ## How `ReshapeRank4RMSNorm` reshapes `(B, S, H, Dh)` -> `(B, S*H, Dh)`, applies the identical RMSNormalization over the last axis, and reshapes back. Both reshapes use constant shapes (`[0, -1, head_dim]`, `[0, -1, heads, head_dim]`) so no `Shape` op is introduced and the graph stays static for the HTP. Numerically exact -- the normalized axis is unchanged. Gated on a new `supports_rank4_rmsnorm` capability (default `True`; `False` only for `qnn`), applied in the lowering stage alongside SeparateRoPE. ## Test `_reshape_rmsnorm_test.py`: the rule reshapes a rank-4 RMSNorm to rank-3 (2 Reshapes added) and the rewritten graph matches the original on CPU (where rank-4 RMSNorm is correct); a rank-3 RMSNorm is left untouched.
1 parent aeb8fa1 commit 98b49e8

5 files changed

Lines changed: 190 additions & 0 deletions

File tree

‎src/mobius/_execution_providers.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,10 @@ class EpCapabilities:
6767
``PackedMultiHeadAttention`` via InlinePass to a
6868
block-diagonal attention bias + standard ``Attention``.
6969
Leave ``True`` for CUDA / DML EPs that ship the native kernel.
70+
supports_rank4_rmsnorm: ``False`` reshapes rank-4 ``RMSNormalization``
71+
(query/key norm over the head dimension) to rank-3 and back via
72+
HtpRank4RMSNorm. ``True`` leaves it unchanged. Set ``False``
73+
only for the QNN HTP, which miscomputes rank-4 RMSNormalization.
7074
default_int4_accuracy_level: Default accuracy level for INT4
7175
quantization (0 = highest accuracy, 4 = fastest).
7276
provider_options: Default ORT GenAI provider options dict for this EP.
@@ -102,6 +106,7 @@ class EpCapabilities:
102106
supports_skip_layer_norm: bool = True
103107
supports_fused_moe: bool = True
104108
supports_packed_multi_head_attention: bool = False
109+
supports_rank4_rmsnorm: bool = True
105110
default_int4_accuracy_level: int = 0
106111
provider_options: dict[str, str] = dataclasses.field(default_factory=dict)
107112
enable_graph_capture: bool = False
@@ -288,6 +293,7 @@ def _register_builtins() -> None:
288293
"enable_htp_shared_memory_allocator": "1",
289294
},
290295
supports_past_present_share_buffer=False, # standard-Attention KV concat
296+
supports_rank4_rmsnorm=False, # HTP miscomputes rank-4 RMSNorm (q/k norm)
291297
),
292298
# onnx-standard: ONNX-only runtime — emits zero custom-domain ops.
293299
# All com.microsoft ops (SkipLayerNorm, PackedMHA) are expanded via

‎src/mobius/_optimizations.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
from mobius.rewrite_rules import (
6464
gelu_fusion_rules,
6565
group_query_attention_rules,
66+
htp_rank4_rmsnorm_rules,
6667
pack_qkv_for_gqa_rules,
6768
separate_rope_rules,
6869
skip_layer_norm_rules,
@@ -312,6 +313,10 @@ def _get_optimization_passes(
312313
lower.append(("SeparateRoPE", list(separate_rope_rules())))
313314
lower.append(("UnpackQKV", list(unpack_qkv_rules())))
314315

316+
# Reshape rank-4 RMSNorm (q/k norm) to rank-3 for the QNN HTP, which miscomputes it.
317+
if not caps.supports_rank4_rmsnorm:
318+
lower.append(("HtpRank4RMSNorm", list(htp_rank4_rmsnorm_rules())))
319+
315320
return fuse, lower
316321

317322

‎src/mobius/rewrite_rules/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
"bias_gelu_rules",
3333
"gelu_fusion_rules",
3434
"group_query_attention_rules",
35+
"htp_rank4_rmsnorm_rules",
3536
"layer_norm_fusion_rules",
3637
"pack_qkv_for_gqa_rules",
3738
"packed_attention_rules",
@@ -47,6 +48,7 @@
4748
group_query_attention_rules,
4849
pack_qkv_for_gqa_rules,
4950
)
51+
from mobius.rewrite_rules._htp_rank4_rmsnorm import htp_rank4_rmsnorm_rules
5052
from mobius.rewrite_rules._layer_norm_fusion import (
5153
layer_norm_fusion_rules,
5254
)
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""Qualcomm Hexagon HTP rewrite rule for lowering rank-4 RMSNormalization to rank-3.
5+
6+
This is an HTP-hardware workaround, not a generic transform: it is only applied
7+
for the QNN HTP (``supports_rank4_rmsnorm=False``), which miscomputes rank-4
8+
RMSNormalization. Other EPs compute it correctly and leave the op unchanged.
9+
10+
Models with query/key normalization (e.g. Gemma-4, Qwen3) apply
11+
``RMSNormalization`` over the head dimension of a rank-4 tensor shaped
12+
``(batch, seq, heads, head_dim)`` — the norm reduces only the last axis.
13+
The Qualcomm Hexagon HTP miscomputes RMSNormalization when the input is
14+
rank-4, so the result is numerically wrong even though the graph finalizes;
15+
3-D RMSNormalization (over the last axis of a rank-3 tensor) runs correctly.
16+
17+
This rule reshapes the rank-4 input down to rank-3
18+
``(batch, seq*heads, head_dim)``, applies the identical RMSNormalization over
19+
the last axis, and reshapes back. Both reshapes use constant shapes
20+
(``[0, -1, head_dim]`` and ``[0, -1, heads, head_dim]``) so no ``Shape`` op is
21+
introduced. The transform is numerically exact: the normalized axis
22+
(``head_dim``) is unchanged.
23+
24+
These rules are applied automatically by
25+
:func:`~mobius._optimizations.optimize_model` for EPs that miscompute rank-4
26+
RMSNormalization (``supports_rank4_rmsnorm=False``; QNN). They can also be
27+
applied manually::
28+
29+
from mobius.rewrite_rules import htp_rank4_rmsnorm_rules
30+
from onnxscript.rewriter import rewrite
31+
32+
model = build("google/gemma-4-12B-it", execution_provider="qnn")
33+
rewrite(model, pattern_rewrite_rules=htp_rank4_rmsnorm_rules())
34+
"""
35+
36+
from __future__ import annotations
37+
38+
from onnxscript.rewriter._basics import MatchResult
39+
from onnxscript.rewriter._rewrite_rule import RewriteRuleClassBase, RewriteRuleSet
40+
41+
42+
class HtpRank4RMSNormToRank3(RewriteRuleClassBase):
43+
"""Reshape a rank-4 RMSNormalization (norm over the last axis) to rank-3.
44+
45+
**Matched pattern:**
46+
47+
.. code-block:: text
48+
49+
norm_out = RMSNormalization(x, weight) # x rank-4, axis = -1
50+
51+
**Replacement:**
52+
53+
.. code-block:: text
54+
55+
x3 = Reshape(x, [0, -1, head_dim]) # (B, S*H, Dh)
56+
normed = RMSNormalization(x3, weight, axis=-1)
57+
norm_out = Reshape(normed, [0, -1, heads, head_dim]) # (B, S, H, Dh)
58+
59+
Only fires when the input rank is 4, the norm reduces a single (last)
60+
axis, and the head/head_dim sizes are static. The two reshapes use
61+
constant shapes (no ``Shape`` op), so the rewritten graph stays static.
62+
The rank-3 replacement does not re-match (the check requires rank 4).
63+
"""
64+
65+
def pattern(self, op, x, weight):
66+
return op.RMSNormalization(
67+
x, weight, _allow_other_attributes=True, _outputs=["norm_out"]
68+
)
69+
70+
def check(self, context, x, norm_out, **_):
71+
result = MatchResult()
72+
shape = x.shape
73+
if shape is None or len(shape) != 4:
74+
return result.fail("RMSNormalization input is not rank-4")
75+
heads, head_dim = shape[2], shape[3]
76+
if not isinstance(heads, int) or not isinstance(head_dim, int):
77+
return result.fail("rank-4 RMSNormalization head/head_dim are not static")
78+
# Reshaping heads into the sequence axis is only valid when the reduced
79+
# axis is head_dim alone, i.e. the last axis.
80+
axis = norm_out.producer().attributes.get_int("axis", -1)
81+
if axis not in (-1, 3):
82+
return result.fail("RMSNormalization reduces more than the last axis")
83+
if norm_out.producer().attributes.get_float("epsilon", None) is None:
84+
return result.fail("Missing epsilon attribute on RMSNormalization")
85+
return result
86+
87+
def rewrite(self, op, x, weight, norm_out, **_):
88+
rmsnorm = norm_out.producer()
89+
heads, head_dim = x.shape[2], x.shape[3]
90+
attrs = {key: rmsnorm.attributes[key].value for key in rmsnorm.attributes}
91+
attrs["axis"] = -1
92+
x3 = op.Reshape(x, op.Constant(value_ints=[0, -1, head_dim]))
93+
normed = op.RMSNormalization(x3, weight, **attrs)
94+
return op.Reshape(normed, op.Constant(value_ints=[0, -1, heads, head_dim]))
95+
96+
97+
def htp_rank4_rmsnorm_rules() -> RewriteRuleSet:
98+
"""Return rules that reshape rank-4 RMSNormalization to rank-3.
99+
100+
Used for the QNN HTP, which miscomputes RMSNormalization over the last
101+
axis of a rank-4 tensor (query/key norm). The transform is numerically
102+
exact.
103+
104+
Returns:
105+
:class:`RewriteRuleSet` containing the :class:`HtpRank4RMSNormToRank3` rule.
106+
"""
107+
return RewriteRuleSet([HtpRank4RMSNormToRank3().rule()])
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
from __future__ import annotations
5+
6+
import numpy as np
7+
import onnx_ir as ir
8+
import onnxruntime as ort
9+
from onnxscript import GraphBuilder
10+
from onnxscript.rewriter import rewrite
11+
from onnxscript.rewriter._rewrite_rule import RewriteRuleSet
12+
13+
from mobius._constants import OPSET_VERSION
14+
from mobius.rewrite_rules import htp_rank4_rmsnorm_rules
15+
from mobius.rewrite_rules._testing_utils import count_ops
16+
17+
18+
def _rmsnorm_model(shape: list[int]) -> ir.Model:
19+
"""A single ai.onnx::RMSNormalization (norm over the last axis) of *shape*."""
20+
rng = np.random.default_rng(0)
21+
x = ir.Value(name="x", shape=ir.Shape(shape), type=ir.TensorType(ir.DataType.FLOAT))
22+
graph = ir.Graph(
23+
inputs=[x],
24+
outputs=[],
25+
nodes=[],
26+
name="rmsnorm",
27+
opset_imports={"": OPSET_VERSION},
28+
)
29+
op = GraphBuilder(graph).op
30+
weight = op.Constant(value=ir.tensor(rng.standard_normal(shape[-1]).astype(np.float32)))
31+
y = op.RMSNormalization(x, weight, epsilon=1e-6)
32+
y.name = "y"
33+
graph.outputs.append(y)
34+
return ir.Model(graph, ir_version=11)
35+
36+
37+
def _run(model: ir.Model, x: np.ndarray) -> np.ndarray:
38+
sess = ort.InferenceSession(
39+
ir.serde.serialize_model(model).SerializeToString(),
40+
providers=["CPUExecutionProvider"],
41+
)
42+
return sess.run(["y"], {"x": x})[0]
43+
44+
45+
class TestHtpRank4RMSNorm:
46+
def test_rules_returns_rule_set(self):
47+
assert isinstance(htp_rank4_rmsnorm_rules(), RewriteRuleSet)
48+
49+
def test_reshapes_rank4_and_is_numerically_exact(self):
50+
# (batch, seq, heads, head_dim) — the query/key-norm shape.
51+
model = _rmsnorm_model([1, 3, 4, 8])
52+
x = np.random.default_rng(1).standard_normal((1, 3, 4, 8)).astype(np.float32)
53+
before = _run(model, x)
54+
55+
rewrite(model, pattern_rewrite_rules=htp_rank4_rmsnorm_rules())
56+
57+
counts = count_ops(model)
58+
assert counts["RMSNormalization"] == 1 # still one norm, now over a rank-3 tensor
59+
assert counts.get("Reshape", 0) == 2 # reshaped down then back
60+
61+
after = _run(model, x)
62+
np.testing.assert_allclose(before, after, rtol=1e-5, atol=1e-6)
63+
64+
def test_rank3_rmsnorm_untouched(self):
65+
# A hidden-state RMSNorm is rank-3 and must not be rewritten.
66+
model = _rmsnorm_model([1, 3, 8])
67+
rewrite(model, pattern_rewrite_rules=htp_rank4_rmsnorm_rules())
68+
counts = count_ops(model)
69+
assert counts.get("Reshape", 0) == 0
70+
assert counts["RMSNormalization"] == 1

0 commit comments

Comments
 (0)