|
| 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()]) |
0 commit comments