Skip to content

Qualcomm AI Engine Direct - Fix float16 RMSNorm, float64 data, integer buffers, and constant outputs - #24428

Open
shoumikhin wants to merge 19 commits into
pytorch:mainfrom
shoumikhin:qnn-rmsnorm-dtype
Open

shoumikhin wants to merge 19 commits into
pytorch:mainfrom
shoumikhin:qnn-rmsnorm-dtype

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

What is wrong today

  • RecomposeRmsNorm skipped only aten.to.dtype casts, so Qwen and Llama norms lost their cast.
  • In HTP (Hexagon NPU) float16, a decomposed norm overflows for inputs above about 256.
  • float64 was mapped to QNN float32 without converting data.
  • A delegate whose only output is a full_like failed: QNN never outputs static tensors.
  • Uninitialized quantize params made QNN sometimes reject integer ops.
  • HTP float16 Concat can silently read an all-True static bool input as False.
  • A delegated mutable buffer ignores the starting value that InitializedMutableBufferPass saves.

What this changes

RMSNorm. RecomposeRmsNorm also skips _to_copy and _to_dim_order_copy. When it cannot rebuild a whole norm, in HTP float16 it rebuilds only the float32 normalization, also in export_llama. RemoveRedundancy keeps a _to_copy that changes the dtype.

Where the norm runs. rms_norm has no CPU kernel, so the pass rebuilds a norm only where the partitioner will delegate it. It estimates this with the partitioner's per-node rules and its estimate of the HTP partitions that read no runtime value.

CPU fallbacks. float64 tensors, HTP constants of more than 5 dims, and in HTP float16 a bool cat of a static tensor (#24750) stay on CPU. Mutable buffers that are not floating point stay on CPU too. This is a stopgap: float buffers still start at zero until the QNN runtime loads the starting value of the buffers it owns (#24749).

Other. Constant delegate outputs get a Reshape that writes them. A static-shape, contiguous full_like becomes a full, unless it is skipped or int64. Quantize params are zeroed. capture_program and the backend tester pass the skip sets to the passes. The exir ops_to_not_decompose docstring is clarified.

int64 is unchanged. An earlier version of this PR also made I64toI32 cast every int64 result to int32. That turned some int64 values that main computes exactly into wrong values with no error, such as a product larger than int32 read by topk. That rework is dropped, so I64toI32 behaves as on main.

Tests

New tests fail without their fix, except guards that pass either way: the quantized rms_norm_upcast test and the int64 counter delegate test, which starts from zero. The quantize params fix has no unit test. On the QNN SDK 2.51 x86 simulator (SM8650), the worst relative norm error drops from 4.5 to 0.005 and the related delegate tests pass. Not run on device.

cc @cbilgin @psiddh

@shoumikhin shoumikhin added the release notes: qualcomm Changes to the Qualcomm backend delegate label Nov 2, 2026
Copilot AI balanced review requested due to automatic review settings November 2, 2026 13:54
@shoumikhin
shoumikhin requested a review from psiddh as a code owner November 2, 2026 13:54
@pytorch-bot

pytorch-bot Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ No Failures, 1 Pending

As of commit 5301606 with merge base a4df8b7 (image):
💚 Looks good so far! There are no failures yet. 💚

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 Nov 2, 2026

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 25m 39s —— View job


PR Review: #24428

No blockers, but in rare mixed-dtype graphs the pass can still build an rms_norm that QNN rejects, or rebuild a later mul with the wrong weight; the float32-weight handling and the test tolerances also need another look.

Detailed review

Summary

The PR makes RecomposeRmsNorm walk past _to_copy/_to_dim_order_copy casts to the nearest input in the norm's output dtype. It leaves the norm decomposed when that dtype has no QNN type.

Nothing blocks the PR. The problems are:

  • two gaps in mixed-dtype graphs, one of which gives silently wrong output;
  • a design question about float32 weights;
  • missing test coverage.

All findings come from reading the code. Python can't run in this environment, so none of them were executed.

Code Quality

  1. A skipped norm lets a later mul be rebuilt with the wrong weight (backends/qualcomm/_passes/recompose_rms_norm.py:151-154).

    • When the new gate skips a norm, its weight mul y stays in the graph.
    • The "*" in the patterns spans up to three nodes (max_wildcard_life=3, _passes/utils.py:278), so it can cover y and the cast back.
    • A following z = y * s then matches with s as gamma, when s is a [D]-shaped placeholder, get_attr or dq.
    • Example: a bfloat16 Qwen-style norm followed by * s, with s in float32. z is float32, the walk stops at the float32 upcast and the gate passes. z becomes rms_norm(x.to(float32), [D], s), and the real weight is silently dropped.
    • Before this PR, y was always rebuilt first, so this graph failed loudly at lowering. The older skips (no gamma found, the shape checks) already had this hole; the new gate opens it for bfloat16 norms.
    • Suggested fix: recompose only when the nodes between last_mul_node and rms_norm_pattern[2] are dtype-only casts.
    • Fix this →
  2. The new dtype gate does not check the weight (recompose_rms_norm.py:151-153).

    • The partitioner's has_unsupported_dtype (partition/utils.py:149-159, called at qnn_partitioner.py:177) rejects a node if any unquantized input has no QNN type. The pass checks only the output dtype.
    • Example: UpcastNorm(torch.bfloat16) with a float32 x has a float32 output, so the norm is rebuilt with a bfloat16 gamma. The partitioner keeps it on CPU, and lowering fails with the same Missing out variants: {'aten::rms_norm'} error this PR fixes.
    • A float16 x with a bfloat16 weight fails the same way, since it promotes to float32.
    • Suggested fix: also require gamma_node.meta["val"].dtype to have a QNN type.
    • Fix this →
  3. With a float32 weight, the target dtype is taken after type promotion (recompose_rms_norm.py:146-150).

    • The comment says rms_norm computes in its input's dtype, which "has to be the pattern's output dtype". That doesn't match eager: aten.rms_norm upcasts float16/bfloat16 internally and applies the weight after casting back to the input dtype. Its output dtype is promote_types(input, weight).
    • Because the target is last_mul_node's dtype, a Qwen-style float16 x with a float32 weight is rebuilt on x.to(float32). That drops the model's h.to(float16) rounding before the weight multiply, which is the kind of rounding the comment at lines 103-105 is meant to preserve. The float32-weight test case only passes because of atol=rtol=1e-2 at test_passes.py:561.
    • A cast-free float16 norm with a float32 weight is now left decomposed: x is float16 and the target is float32. The old pass rebuilt it, and the PR description doesn't mention this change.
    • If QNN's RmsNorm needs a single dtype for input, weight and output, the comment should say so, and the weight then has to match too (see item 2).
    • Otherwise, target the dtype of the weight mul's other operand (the cast back). That rebuilds both cases on the float16 x and matches what eager computes for the original module.
  4. The walk still skips narrowing casts (recompose_rms_norm.py:106-109).

    • The loop walks past every cast whose output is not the target dtype, including narrowing ones. So the guarantee in the comment above it only covers round trips that end in the target dtype.
    • Example: x32 → .to(float16) → norm → .to(float32) → w32 * is rebuilt as a float32 norm on x32, which drops the float16 rounding and compute.
    • Suggested fix: walk only past casts that don't narrow, or narrow the comment's claim.
    • Fix this →
  5. _is_cast compares dim_order with the contiguous order instead of the input's (recompose_rms_norm.py:99).

    • MemoryFormatOpsPass gives a preserve-format cast the input's dim order (exir/passes/memory_format_ops_pass.py:114-117).
    • So a dtype-only cast of a channels-last tensor isn't treated as a cast, and its norm is not recomposed.
    • A cast that also turns a channels-last input contiguous is skipped, which contradicts "Only casts that change nothing but the dtype are skipped".
    • Suggested fix: compare with list(node.args[0].meta["val"].dim_order()).
    • Fix this →

Testing

  • The test is too lenient to catch numeric bugs (backends/qualcomm/tests/test_passes.py:509, :561).
    • UpcastNorm's weight is torch.ones, and the comparison uses atol=rtol=1e-2. A wrong or dropped gamma (item 1) or a dropped rounding (item 3) still passes.
    • ScaledNorm above uses torch.randn and default tolerances.
    • Only the float32-weight case should need a looser bound. I haven't run the other cases to confirm they pass at default tolerances.
  • Cases with no test:
    • the Llama-style pattern (x * x, x.float(), .type_as(x); examples/models/llama/norm.py:34-41), which the description says was checked on device;
    • the round trip described in the _get_input_node comment (float32 → float16 → float32 before the norm);
    • _is_cast rejecting a cast with extra kwargs or a non-contiguous dim_order. Dropping those two conditions (lines 98-99 of the pass) still passes every case.
  • The new cases are in the wrong test. They are appended to test_recompose_rms_norm_only_takes_last_dim_with_weight, which is about shape gating. A separate test would make a failure point at the dtype logic.
  • Fix this →

Recommendation

Needs Discussion

Nothing blocks. Item 3 needs an answer on whether QNN's RmsNorm requires one dtype throughout, because that decides how items 2 and 3 should be fixed. Items 1 and 2 are small enough to close in this PR.


  • Gather context (diff, changed files, CLAUDE.md)
  • Run three independent reviewers
  • Consolidate findings
  • Fact-check findings
  • Post review

Copilot AI balanced review requested due to automatic review settings November 2, 2026 17:17

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

Thanks for the review. The latest push changes this:

  1. Wrong weight after a skipped norm: fixed. Only casts that change nothing but the dtype may now sit between the normalization and the weight multiply, so a later * s is no longer rebuilt as the norm. The new test has a bfloat16 norm followed by a float32 scale.
  2. Weight dtype: not changed, because this case is never rebuilt. When the weight's dtype differs from the multiply's output, the weight reaches the multiply through a cast in the edge graph. The pass then finds no parameter or constant as gamma, so the norm stays decomposed. I checked float32 input with a bfloat16 weight, float16 input with a bfloat16 weight, and float32 input with a float16 weight: no rms_norm is built in any of them.
  3. One dtype or mixed: I found nothing that says QNN's RmsNorm takes different dtypes for input, weight and output, so I went with one dtype throughout. The norm is rebuilt only when its input and its output share a dtype, and no cast in between rounds below that dtype. So a float16 Qwen-style norm with a float32 weight now stays decomposed. Before, it was rebuilt in float32 and lost the float16 rounding. The description now says this.
  4. Narrowing casts: fixed. The walk stops at a cast to a dtype narrower than the output.
  5. dim_order: fixed. A cast is compared with its input's dim order. The test has a channels-last input, once with a cast that keeps its dim order and once with a cast to contiguous, which stops the rebuild.

Tests: the dtype cases are now in their own test, test_recompose_rms_norm_keeps_the_norm_dtype, with random weights and default tolerances. It adds a Llama-style norm (type_as), float16 rounding before a float32 norm (rebuilt on the rounded tensor) and inside one (left decomposed), and the channels-last cases.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 36m 11s —— View job


PR Review: #24428

During quantization capture, the new check between the normalization and the weight stops a norm that casts back with type_as from being recomposed, which is a regression that needs a fix before merge; the other two items are older bugs next to the change.

Detailed review

Summary

The PR makes RecomposeRmsNorm rebuild a norm only on an input in the norm's output dtype. It finds that input by walking past casts that change only the dtype, and requires that only such casts sit between the normalization and the weight.

  • Item 1 is a regression in the quantization flow, caused by the new check on the weight side.
  • Items 2 and 3 are older bugs next to the change.

I covered both changed files. Python can't run in this environment, so nothing was executed; every finding comes from reading the code.

Code Quality

  1. During quantization capture, a norm that casts back with type_as is no longer recomposed (backends/qualcomm/_passes/recompose_rms_norm.py:91, :133-140).

    • Why it misses:
      • In capture mode, skip_targets is only torch.ops.aten.to.dtype.
      • A captured graph keeps h.type_as(x) as aten.type_as.default, even when the dtype doesn't change.
        • Arm's annotation pipeline runs a pass that removes such no-op calls on parameters (backends/arm/_passes/remove_redundant_type_as_pass.py:24, arm_pass_manager.py:808).
        • _cast_source in backends/transforms/fuse_rms_norm.py:210 matches the same op.
      • QNN's capture-mode RemoveRedundancy removes only _assert_tensor_metadata, so the type_as node stays.
      • The new walk back from the weight multiply stops at that node, normalized is pattern[2] fails, and _get_norm_input returns None.
      • The old pass let the "*" take the type_as and built one rms_norm on x.
    • Trigger: the Meta reference Llama RMSNorm (self._norm(x.float()).type_as(x) * self.weight) or the PR's TypeAsNorm, in float32 or bfloat16, run through RecomposeRmsNorm(quantization_capture=True).
      • The norm stays decomposed through annotation, so its ops are quantized one by one instead of as one rms_norm.
      • For bfloat16, this contradicts the description, which says a bfloat16 norm stays decomposed unless it is about to be quantized.
    • Test gap: TypeAsNorm runs only on the edge path (backends/qualcomm/tests/test_passes.py:561). The capture rows (:567-568) use only UpcastNorm, which casts back with to.dtype.
    • Fix: add torch.ops.aten.type_as.default to the capture skip_targets. Add capture rows such as (TypeAsNorm(f32), f32, c, True, True, [(f32, True)]) and the bfloat16 version.
    • Related:
      • _is_cast reads layout, device and dim order only from node.kwargs (:102-111).
      • aten.to.dtype takes memory_format positionally. So in capture, a to.dtype that makes a channels-last input contiguous still counts as changing only the dtype. The values are unaffected.
      • Comparing node.args[0].meta["val"] with node.meta["val"] instead would apply one rule to all four cast ops. _cast_source already compares device and layout this way (fuse_rms_norm.py:194).
    • Basis: I confirmed the mechanism by reading the code. That captured graphs keep aten.type_as.default is inferred from those two passes, not from a run.
    • Fix this →
  2. Nothing checks that the tensor being scaled is the norm's input (recompose_rms_norm.py:123, :140). This bug predates the PR.

    • Problem: the input is taken from pattern[6].args[0], the base of the square, and the new check verifies only the weight side. Nothing checks that:
      • the other operand of pattern[2] (the h in h * rsqrt(...)) is that same tensor;
      • both operands of the Llama-form h * h are the same tensor;
      • the pow exponent is 2.
    • Trigger: y * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-6) * w is rebuilt as rms_norm(x, [D], w), and y is silently dropped.
    • Why fix it here: _match_rms_norm_core in backends/transforms/fuse_rms_norm.py:104-108 already checks the scaled tensor and the exponent. This PR rewrote how the input is chosen, and its test asserts which tensor the norm reads.
    • Fix this →
  3. With _skip_dim_order=True, the dim-order rule never sees the cast it targets (recompose_rms_norm.py:102-111, test_passes.py:559). The cause predates the PR and is outside the diff.

    • Cause: RemoveRedundancy runs before this pass in the to_edge pipeline (qnn_pass_manager.py:344). Its _to_copy_op_condition (remove_redundancy.py:51-52) deletes every _to_copy that has a memory_format kwarg, including one that changes the dtype. It doesn't re-trace, so the metadata downstream stays stale.
    • Trigger: ContiguousUpcastNorm(f16) lowered with _skip_dim_order=True.
      • _to_copy(x, dtype=torch.float32, memory_format=torch.contiguous_format) is deleted.
      • The pow then reads the float16 x, while its metadata still says float32.
      • The norm is rebuilt on x, although under the PR's rule this cast keeps the norm decomposed.
    • Wider effect: any x.to(dtype, memory_format=...) in that flow loses its dtype change the same way.
    • Why the test misses it: it calls the pass on its own and checks the rule only with dim order on.
    • Fix: make _to_copy_op_condition also require an unchanged dtype, as _dim_order_op_condition does.
    • Fix this →

Recommendation

Request Changes

Item 1 makes the quantization flow worse for norms written with type_as. The fix is one skip_targets entry and two test rows. Items 2 and 3 predate the PR and can be follow-ups.


  • Gather context (diff, changed files, CLAUDE.md)
  • Run three independent reviewers
  • Consolidate findings
  • Fact-check findings
  • Post review

Copilot AI balanced review requested due to automatic review settings November 2, 2026 19:47
@shoumikhin

Copy link
Copy Markdown
Contributor Author

Thanks. The latest push changes this:

  1. type_as in quantization capture: fixed. aten.type_as now counts as a cast in captured graphs. _is_cast also compares the cast's output with its input (layout, device, dim order) instead of reading kwargs, so one rule covers every cast op, however it passes its arguments. The test runs TypeAsNorm in capture for float32 and bfloat16.
  2. The scaled tensor and the exponent: fixed here. The norm is rebuilt only when the tensor it scales is the tensor it squares, and the square is pow(2) or h * h. The comparison looks past dtype-only casts, because T5's norm squares a float32 copy of the tensor it scales; the test covers T5's norm too. A new test checks that a different scaled tensor, a cube and a product of two tensors stay decomposed.
  3. RemoveRedundancy dropping a dtype change: fixed in a second commit. A _to_copy with memory_format is now removed only when it keeps the dtype, as _to_dim_order_copy already was. A new test exports such casts without dim order: the layout-only one is removed, and the float16 one stays.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 42m 16s —— View job


PR Review: #24428

Nothing blocks this PR. Quantization capture can still rebuild a norm whose weight has another dtype, no test runs the lifted pow exponent that real edge-flow norms go through, and recompose_rms_norm.py needs two small cleanups.

Detailed review

Summary

The PR changes two passes:

  • RecomposeRmsNorm now rebuilds a norm only when its input and output share a dtype and no cast between them rounds to a narrower one.
  • RemoveRedundancy now keeps a _to_copy that changes the dtype.

I found no blockers: three minor code problems and one test gap. All three changed files were covered. Python can't run in this environment, so every finding comes from reading the code.

Code Quality

  1. Quantization capture still rebuilds a norm whose weight has another dtype (backends/qualcomm/_passes/recompose_rms_norm.py:158-161; gamma is picked at :198-200).

    • Cause: The earlier reply said the weight reaches the multiply through a cast. That is only true for edge graphs.
      • The cast comes from RemoveMixedTypeOperators (exir/passes/remove_mixed_type_operators.py:25, :87), which only runs inside to_edge (exir/program/_program.py:649).
      • The annotation pipeline (qnn_pass_manager.py:173-211) has no such pass, so in a captured graph the weight get_attr feeds the multiply directly.
    • Trigger: UpcastNorm(torch.bfloat16), or a float16 weight, with a float32 x, run through RecomposeRmsNorm(quantization_capture=True).
      • The weight multiply outputs float32, the walk returns x, and _get_norm_input never looks at the weight.
      • The pass then builds aten.rms_norm(x_f32, [32], weight_bf16). That breaks the description's assumption that QNN's RmsNorm takes one dtype throughout.
      • No capture row in test_recompose_rms_norm_keeps_the_norm_dtype uses a weight in another dtype.
    • Scope: Only a captured model that mixes dtypes inside the norm is affected. I didn't trace what QNN does with such a node when it stays in floating point.
    • Fix: In _get_norm_input, also return None when gamma_node.meta["val"].dtype != dtype, so both flows apply the same rule.
    • Fix this →
  2. The _get_norm_input docstring misstates what rms_norm computes (recompose_rms_norm.py:143).

    • Problem: The docstring says "rms_norm computes in its input's dtype". ATen's rms_norm actually upcasts float16 and bfloat16 inputs to float32 for the normalization, then casts back before applying the weight.
    • Why it matters:
      • That upcast is why the float16 Qwen, Llama and T5 rows match eager at default tolerances.
      • Read literally, the docstring says rebuilding those norms on x_f16 drops the float32 math the model asks for. That is the opposite of the reason the pass can rebuild them.
    • Fix: State the constraint the code actually enforces: rms_norm returns its input's dtype, so the input has to be in the pattern's output dtype. Separately, state the assumption that QNN's RmsNorm takes one dtype throughout.
    • Basis: ATen's rms_norm implementation, which isn't in this checkout.
    • Fix this →
  3. getattr(exponent.meta["val"], "constant", None) is the dynamic getattr pattern CLAUDE.md rules out (recompose_rms_norm.py:127).

    • The default is never used: FakeTensor always defines .constant. lift_constant_tensor_pass sets it on every lifted constant (exir/program/_program.py:289), and transform_for_export_pipeline calls that pass (qnn_pass_manager.py:476).
    • Same file: Line 225 already reads eps.meta["val"].constant.item() directly.
    • Fix: Use exponent.meta["val"].constant, and keep the None check for an exponent that isn't a constant.
    • Fix this →

Testing

  • No test runs the exponent branch that real edge-flow norms go through (recompose_rms_norm.py:125-128; test_passes.py:599-602, :620).
    • Why it's the main path:
      • to_edge_transform_and_lower_to_qnn runs transform_for_export_pipeline before to_edge (backends/qualcomm/utils/utils.py:524).
      • That pipeline includes LiftConstantScalarOperands (qnn_pass_manager.py:245). It rewrites pow.Tensor_Scalar(h, 2) as pow.Tensor_Tensor(h, <lifted constant>) (lift_constant_scalar_operands.py:57).
      • So in the real flow, every pow-form norm (Qwen, T5) reaches this pass through lines 125-128.
    • What the tests run instead: _check_recomposed_rms_norm and test_recompose_rms_norm_needs_the_norm_of_one_tensor call to_edge on the raw export. Only the scalar-exponent branch runs there.
    • What's left unchecked: Neither the pow(2) acceptance nor the pow(3) rejection is tested in the form the pipeline produces. A regression there would only show up on device.
    • Fix: Run transform_for_export_pipeline(ep) before to_edge, at least for the float16 UpcastNorm row and the pow3 case. The tests at test_passes.py:1006-1011 already do this.
    • Fix this →

Recommendation

Approve

Nothing blocks. Item 1 and the test gap are small and worth folding into this PR. Items 2 and 3 are one-line cleanups.


  • Gather context (diff, changed files, CLAUDE.md)
  • Run three independent reviewers
  • Consolidate findings
  • Fact-check findings
  • Post review

JakeStevens pushed a commit to JakeStevens/executorch that referenced this pull request Nov 2, 2026
… Samsung passes (pytorch#24316)

## What is wrong today

torch.export does not record some of the node names it assigns: the
names of inputs, and the names of ops it renamed to make room for an
input. With an input called `mul`, the model's own `input * 2` becomes
`mul_1`, and nothing marks `mul_1` as taken. A later pass that adds a
node can pick one of those names again, and the graph breaks:

```
RuntimeError: Node redefined name t_1!
```

QNN models with autocast regions or attention hit this in the QNN export
passes. The Samsung passes hit it too: with an input named `cat`,
`torch.cat` followed by `torch.roll` fails in `DecomposeRoll`.

## What this change does

`reserve_node_names` in `backends/transforms/utils.py` records the name
of every node in the top-level graph, so nodes added later get names
that are not taken. The QNN and Samsung pass managers call it at the
start of `_transform`.

torch.fx has no public way to reserve a name, so the helper adds the
names to the graph's name set directly. Copying the graph would register
the names through public API, but it also renames inputs named after
Python builtins (`input` becomes `input_1`) while the graph signature
keeps the old names. The real fix belongs in torch.export
(pytorch/pytorch#202927), and a TODO says to
drop the helper once that lands.

## Tests

`test_export_pipeline_keeps_node_names_unique` runs the QNN export
passes on an autocast model and on an attention model whose inputs are
named `input` and `mul`. It checks that the graph lints, keeps the input
names the graph signature uses, and matches eager, and that the
collision really happens without the helper. If a torch update removes
the collision, the test skips with a pointer to the torch issue instead
of failing.

On Linux x86_64 with torch 2.14 and a 2.16 nightly: the test fails with
`Node redefined name t_1!` and `Node redefined name mul_1!` when the
call is removed, and it fails on the `input` case when the helper copies
the graph instead. The Samsung case above fails without the helper and
passes with it (torch only). `test_passes.py` passes, except two tests
that need torchtune or the quantized CPU kernels.

Earlier versions of this PR also carried an HTP change that decomposes
constant-only ops left on the CPU, and an RMSNorm dtype fix. Both now
have their own PRs:

RMSNorm dtype fix: pytorch#24428
HTP constant-only decomposition: pytorch#24429

cc @cbilgin @psiddh
@JacobSzwejbka JacobSzwejbka reopened this Nov 3, 2026
Copilot AI balanced review requested due to automatic review settings November 3, 2026 05:38

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

About a weight in another dtype during quantization capture: I kept the rebuild on purpose. The quantizer quantizes the weight with the same spec as the input, so QNN gets the input, the weight and the output of RmsNorm as one quantized type (8-bit with 8a8w, 16-bit with 16a16w).

I ran a float32 input through PTQ and lowered it for SM8650, with a bfloat16 weight (8a8w and 16a16w) and a float16 weight (8a8w). With the rebuild, the whole norm becomes one delegated rms_norm, and nothing stays on the CPU. With the suggested check, the norm stays decomposed, and QNN rejects the weight multiply because its two inputs get different types, so it runs on the CPU. The model after convert_pt2e is also usually a little less accurate (for example, 3.1e-2 instead of 2.8e-2 relative error with 8a8w and a bfloat16 weight). ATen's rms_norm with a mixed weight gives the same output as the original module.

I added a capture case with a bfloat16 weight and a float32 input that expects the rebuild, so this choice is now tested.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 7m 27s —— View job


PR Review: #24428

I found no blockers, but there is one major design issue: I64toI32 and RecomposeRmsNorm guess where ops will land using a third, separate copy of the partitioner's support logic, and that copy already disagrees with the partitioner. For RecomposeRmsNorm, a wrong guess can leave an rms_norm on CPU that has no kernel there. There are also a few smaller issues.

Detailed review

Summary

The PR fixes several QNN lowering problems:

  • float16 RMSNorm overflow on HTP
  • dtype loss when RMSNorm is recomposed
  • float64 data
  • int64 handling in I64toI32
  • delegates whose outputs are constants
  • quantize params that were never initialized

Not reviewed in depth: the 1302 new lines of tests in test_passes.py, and most of test_qnn_delegate.py.

Code Quality

  • The passes now use a third "would QNN take this" check, and it already disagrees with the partitioner (major; raised by all 3 reviewers).

    • may_be_delegated (backends/qualcomm/partition/utils.py:223) is what I64toI32._mark_ops_kept_on_cpu (i64_to_i32.py:99) and RecomposeRmsNorm._find_nodes_left_on_cpu (recompose_rms_norm.py:241) use.
    • Two other checks already exist, and each has different rules:
      • QnnPartitioner._may_run_on_qnn (qnn_partitioner.py:449) has no node-visitor check and leaves skips out on purpose.
      • QnnOperatorSupport.is_node_supported (qnn_partitioner.py:197).
    • may_be_delegated does not apply the per-node rules this PR adds to is_node_supported:
      • the HTP fp16 bool cat of a static tensor (:247)
      • the HTP limit of 5 dims for constants (:278)
    • The runtime-input tests differ too: the partitioner uses name not in constant_inputs, while the passes use get_runtime_inputs.
    • The PR description says the passes use "the partitioner's own estimate". Only find_nodes_left_on_cpu is actually shared; the set of nodes fed into it is not.
    • Trigger: a norm whose partition HTP later drops. This happens when a neighbouring op is rejected by one of the checks above, or by QNN op validation, so the partition no longer reads a runtime value.
      • The estimate thinks the norm is delegated, so the pass rebuilds aten.rms_norm.
      • The partitioner then leaves it on CPU, where (as the pass's own _get_input docstring says) it has no kernel.
      • Before this PR, that norm stayed decomposed and ran.
    • For I64toI32 the same mismatch only costs extra int32/int64 cast pairs, but placement is now decided in two places.
    • This is the drift shewu-quic raised. At minimum, the per-node rules should live in one helper that both is_node_supported and may_be_delegated call, so they can't diverge.
    • Fix this →
  • skip_node_id_set names are matched before nodes are renamed (2 reviewers).

    • qnn_partitioner.py:482-484 itself says a rewrite before partitioning "would rename later nodes, so a skip_node_id_set entry could name a different node", and leaves skips out of _left_on_cpu for that reason.
    • I64toI32._mark_ops_kept_on_cpu and RecomposeRmsNorm._is_skipped (recompose_rms_norm.py:199-203) still match the names users take from the final graph. I64toI32's own retrace inserts _to_copy nodes, which renumber later aten__to_copy_default_N names.
    • Trigger: a user skips one of several same-target nodes by name. Then either the wrong op keeps int64, or a norm is rebuilt or left decomposed wrongly.
    • Related: _is_skipped never checks the name the new rms_norm node will get.
  • CPU-kept ops still read int64 constants with a non-int64 val (i64_to_i32.py:245, suspected).

    • For parameters, buffers and lifted constants, _cast_constant_to_int32 → _update_meta rewrites meta["val"] to float (:232-235).
    • It inserts no cast, so the constant never enters input_casts, and _read_int64_inputs_on_cpu cannot restore it.
    • Trigger: an op tagged QCOM_KEEP_INT64 (for example a skipped index_select or gather) that reads an int64 buffer is retraced on a float input.
    • The _update_meta behaviour predates this PR, but the new claim that "a CPU op reads every value that was int64 in the original graph as int64" does not hold for constants.
  • Cross-pass state lives in node meta and is copied wholesale (3 reviewers).

    • _cast (i64_to_i32.py:127) builds the cast's meta as {**value.node.meta, QCOM_INSERTED_CAST: True}. So the cast inherits everything the producer has, including QCOM_ORIG_DTYPE, which _preserve_output_dtype silently depends on.
    • QCOM_INSERTED_CAST survives until the partitioner. There, _drop_partitions_of_inserted_casts (qnn_partitioner.py:393) keeps a whole partition on CPU if every node in it carries the flag.
    • Risk: any later pass that builds a node with copy_meta from one of these casts spreads the flag to a real op, and can silently push a real partition to CPU.
    • Recognising the casts by structure (a _to_copy between int32 and int64) would avoid the side channel.
  • ConvertFullLikeToFull keeps the full_like's meta, but the new full is laid out differently (convert_full_like_to_full.py:47-56; 2 reviewers, suspected).

    • The new full keeps only dtype. memory_format (default preserve_format) is dropped, yet full.meta = copy_meta(node.meta) keeps the input's dim order.
    • Trigger: torch.full_like(x_channels_last, v). The val says channels-last, but full produces a contiguous tensor. This matters when the full stays on CPU, for example with more than 5 dims on HTP.
  • The 5-dim constant rule rejects every HTP constant, not only partition outputs (qnn_partitioner.py:275-285; 2 reviewers).

    • define_constant (node_visitor.py:617) still emits a plain STATIC tensor when the constant is not a graph output. The Reshape path is the only one with the 5-dim limit.
    • Trigger: torch.full((1,1,1,2,2,2), 1.0).reshape(8) + x. Before this PR it was delegated; now the full falls to CPU and the graph is split.
    • Whether a node will be a partition output can't be known per node, so this may be deliberately conservative. If so, the comment should say that.
  • The static-tensor check behind the bool-cat rule misses some cases (qnn_partitioner.py:191, 1 reviewer, low confidence).

    • constant_operator (partition/common_defs.py:35) lists torch.ops.aten.scalar_tensor.default, not the edge op, so an edge scalar_tensor is never seen as static.
    • The look-through tuple omits slice_copy, select_copy and repeat.
    • Trigger: a bool cat with torch.full(..., True)[..., :k]. It would still be delegated and possibly misread by HTP fp16.

Performance

  • Integer mutable buffers are now always copied in and out of the delegate (qnn_partitioner.py:553-557, low confidence on impact).
    • With skip_mutable_buffer=False, every non-floating-point mutable buffer loses its delegation tag, so a model with int or bool state now crosses the delegate boundary on each call.
    • The stated cause (QNN does not load a delegate-owned buffer's starting value) applies to float buffers too, and those stay delegated (TODO Qualcomm AI Engine Direct: a delegated mutable buffer starts from leftover memory #24749).
    • Gating on dtype rather than on whether the starting value matters is inconsistent. The cost should at least be measured on a model with integer state.

Recommendation

Needs Discussion

The duplicated placement estimate is the main concern. It is the drift shewu-quic already pointed out, and it can turn a working decomposed norm into an rms_norm with no CPU kernel. Sharing one set of per-node rules with is_node_supported, plus a test where the estimate and the partitioner disagree, would resolve it. The other points are minor.

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Reviewing PR #24428

  • Gather context
  • Run three reviewers
  • Consolidate findings
  • Fact-check findings. Almost done: 12 claims dropped as invalid or pre-existing with no effect. One confirmed so far: transform_for_to_edge_pipeline drops the graph that I64toI32 retraces, so the new int64 handling never reaches export_llama_lib.
  • Review the files no reviewer reached
  • Post review

View job run

RecomposeRmsNorm finds the norm's input by skipping casts, but it only
skipped aten.to.dtype. Edge graphs carry the cast as _to_copy or
_to_dim_order_copy, so for a Qwen-style norm (upcast to float32,
normalize, cast back) the rebuilt rms_norm read the float32 cast and the
cast back was lost. Its metadata was copied from the original output, so
the graph still claimed the old dtype until a later pass recomputed it.
A float16 Qwen norm then failed to lower with "rms_norm was not
decomposed or delegated". A bfloat16 Qwen norm followed by
masked_scatter failed with "expected self and source to have same
dtypes", and when the rebuilt norm stayed on the CPU, to_executorch
failed with "Missing out variants: aten::rms_norm".

The pass assumes QNN's RmsNorm takes one dtype throughout, so it now
rebuilds the norm only when its input and its output share a dtype, and
no cast in between rounds below that dtype or widens it past float32,
the widest dtype rms_norm computes in. It skips casts that change only
the dtype: to.dtype, to.device or type_as in captured graphs, and
_to_copy or _to_dim_order_copy in edge graphs, whose output keeps the
input's layout, device and dim order. It walks back to the nearest
tensor in the output dtype, but not past a cast to a narrower dtype or
one that changes the dim order. Only such casts may sit between the
normalization and the weight: the "*" in the patterns can match any op,
so before, a skipped norm let a later multiply be rebuilt as the norm
with the wrong weight. Outside quantization capture, the dtype also
needs a QNN type. The tensor it scales has to be the tensor it squares,
past such casts (T5's norm squares a float32 copy), and the square has
to be pow(2) or h * h, past such casts. Before, any multiply by a root
mean square was rebuilt as a norm of the squared tensor, and the scaled
tensor was dropped.

So a float16 Qwen norm is rebuilt on its float16 input. A norm that
rounds to float16 before a float32 weight, and a bfloat16 norm, stay
decomposed, unless the bfloat16 norm is about to be quantized.

A new test covers these cases, with and without dim order, with a
channels-last input and a cast that changes its dim order, a Llama-style
norm, a T5 norm, float16 rounding before and inside a float32 norm, a
float32 norm computed in float64, a multiply after the norm, a square of
two casts, and quantization capture, including type_as, to with a
device, and a weight narrower than the input there, and a wider one,
which stays decomposed since rms_norm returns its input's dtype. Edge
graphs first go through the QNN export pipeline, as in
to_edge_transform_and_lower_to_qnn, so the exponent of pow is a lifted
constant. The test checks which tensor the norm reads and compares the
output with eager, with random weights. Another test checks that a
different scaled tensor, a cube and a product of two tensors stay
decomposed, with and without the lifted exponent. Delegate tests lower a
float16 Qwen-style norm, and a quantized float32 one with a bfloat16
weight, and check their output.
Without dim order, a layout change in an edge graph is a _to_copy with a
memory_format argument, and RemoveRedundancy drops every such _to_copy,
because QNN does not need layout changes. A cast like
x.to(torch.float16, memory_format=torch.contiguous_format) is also a
_to_copy with memory_format, so its dtype change was dropped too, and
later ops read the old dtype while their metadata said the new one.

RemoveRedundancy now drops a _to_copy with memory_format only when it
keeps the dtype, as it already does for _to_dim_order_copy.

The new test exports such casts without dim order. A layout-only cast
is still removed, and a cast to float16 stays, with a float16 output.
RecomposeRmsNorm rebuilds a norm into one rms_norm only when its input,
its weight and its output share a dtype. A Llama-style norm with a
bfloat16 input or weight upcasts to float32, normalizes, casts back and
multiplies by the weight, so it stayed decomposed. With HTP's float16
precision, QNN then ran its float32 pow, mean and rsqrt in float16.
Squaring x passes the largest float16 value (65504) once |x| > 255.9, so
rows with large values, like the massive activations of a language
model, came out wrong (relative error up to 4.5 on SM8650 for values of
1000 to 2000).

When the whole norm cannot be rebuilt and the graph is lowered for HTP's
float16 precision, the pass now rebuilds only its float32 normalization,
as an rms_norm without a weight, and leaves the casts and the weight
multiply after it as they are. rms_norm computes in float32, so this
matches what the model computes. A float32 norm whose weight is not one
value per channel, such as a 0-d scale, gets the same. A normalization
in float16 stays decomposed, since rms_norm would compute it in float32
instead. Other backends and precisions, and quantization capture, keep
the normalization decomposed as before, since every op in it has a CPU
kernel. The pass takes the compiler specs to know the backend and
precision, so this needs a caller that passes them, as
to_edge_transform_and_lower_to_qnn does. The FP16 lowering recipe now
passes its compiler specs and skip sets to the edge passes too, so it
gets the fix, and so does the QNN stage of the backend test suite. Its
Buck target, :tester, now lists the test harness that tester.py imports.
QnnPassManager.transform_for_to_edge_pipeline now takes the compiler
specs and skip sets as well, and the Llama export script passes those of
its QNN partitioner, so a Llama model exported for HTP's float16
precision gets the fix too. The deprecated capture_program takes no
compiler specs, so it keeps the normalization decomposed.

rms_norm has no CPU kernel, so a rebuilt norm that QNN refuses fails the
lowering. The pass now rebuilds only what QNN's RmsNorm takes: the last
of 1 to 4 dims, with static sizes and a constant eps, both for a whole
norm and for its normalization, and also during quantization capture.
Anything else stays decomposed. This also lets a rank-5 or a
dynamic-shape float32 norm lower, which failed before. For the same
reason, on the edge graph, nothing is rebuilt when the partitioner would
skip rms_norm, and a part of a norm is not rebuilt when the partitioner
would skip, by op or by name, a node that rebuilding it removes, that is
one that only feeds that part. A skipped rms_norm stays on the CPU, so
this failed for weighted norms before too, and a node skipped by op now
stays on the CPU as asked. Names can change when a later pass retraces
the graph, so a skip by name may stop matching. Quantization capture
does not see the skip sets, so a norm it rebuilds still fails to lower
when rms_norm is skipped, as before.

Outside quantization capture, and unless the compiler specs select
another backend, the norm also has to meet a runtime value: its input
reads one, or its result feeds an op that reads one. The pass cannot see
the partitions, and HTP drops a partition that reads only constants, so
a norm of constants cut off from runtime ops failed to lower. Such a
norm now stays decomposed. A norm of constants whose result feeds an op
that reads a runtime value, like x + norm(table), shares a partition
with that op and is still rebuilt, if the partitioner may take every op
on the way: one with a QNN builder, not skipped, and with no
data-dependent size or unsupported dtype. Through an op left on CPU,
like a skipped sub, a boolean mask index or a prod, it stays decomposed.
A runtime value comes from a user input or from a buffer the model
updates. The program fresh from torch.export still writes such a buffer
in place and does not list it as mutated yet, so the pass also looks for
those writes. The pass takes the program to find them, and now requires
it outside quantization capture. For the same reason a graph input is no
longer taken as the weight: QNN's RmsNorm needs a constant one, and
lowering failed when it tried to read the input as a parameter.

On the QNN SDK's x86 simulator for SM8650 (float16), a bfloat16 norm and
a float32 norm with a bfloat16 weight now lower to RmsNorm, with a worst
relative error of 0.005 and 0.0007 on rows with values up to 2000, like
a float32 norm (0.0008).

The test now also checks whether each rebuilt norm keeps its weight. It
expects the float32 normalization alone to be rebuilt for a bfloat16
norm, a float32 input with a bfloat16 weight, a float16 cast before a
float32 weight, a cast that changes the dim order, and an op between the
normalization and the weight, and no normalization-only rebuild in
float16 or during quantization capture. A new test checks that a rank-5
input, a dynamic dim and an eps buffer, with and without a weight, and a
mean that is not over the last dim with keepdim stay decomposed, that a
norm with a 0-d scale is rebuilt without it, and that a norm of a buffer
added to the input is rebuilt, with or without a weight. It replaces the
old last-dim test, which only compared outputs. Two more tests check
that only HTP's float16 precision, passed in by the pass manager, its
to-edge pipeline (as export_llama runs it, on a bfloat16 Llama-style
norm) or the FP16 recipe, rebuilds a normalization alone, and that a
graph input is not taken as the weight. Another checks the skip sets: a
skipped rms_norm or rsqrt keeps the norm decomposed, a skipped cast is
kept, a skipped weight multiply stops only the rebuild of the whole
norm, and a skipped rsqrt that is used elsewhere too does not stop it.
One more checks that only HTP, or an unknown backend, leaves a norm of
constants decomposed, and only when its result meets no runtime value
and the model does not update the buffer, also given the program fresh
from torch.export. Another checks that a norm of constants is rebuilt
when its result reaches x through an add, and not through a skipped sub,
a boolean mask index or a prod. Another checks that the backend test
suite's stage delegates the rebuilt normalization. Delegate tests lower
a norm with a 0-d scale, and a float32 Qwen-style norm with a bfloat16
weight, with values up to 1000 for HTP's float16 precision and check
their output.
The backend mapped torch.float64 to QNN_DATATYPE_FLOAT_32 and
delegated float64 ops. The data was never
converted: float64 constants and graph inputs reached QNN as raw 8-byte
values read as 4-byte floats. So float64 math gave wrong results with no
error. For example, (x.double() * 2 + 1).float() returned zeros on the
QNN SDK's x86 simulator for SM8650 in float16 mode, and a sinusoidal
timestep embedding computed in float64, as openpi and LeRobot's pi0,
pi05 and SmolVLA do, was off by up to 2.0.

float64 is now left out of the QNN type map, as bfloat16 already is. A
node that reads or writes a float64 tensor stays on CPU, where float64
is computed exactly. Ops on other dtypes are delegated as before. The
quantizer's dtype check reads the same map, so it now treats a float64
input as having no QNN type instead of failing on the missing key.

The To builder's uint8 cast through int32 on HTP no longer needs a
float64 case, since a float64 cast now stays on CPU.

On the simulator, both examples above now match PyTorch exactly, and
the error of SmolVLA's denoising step drops from 0.32 to 0.0027
(largest absolute error, outputs up to 3.2).

New tests lower float64 math between float32 ops, unquantized and
quantized, and check the output.
When the QNN partitioner delegates a mutable buffer, the delegate owns
the buffer's memory. The QNN runtime fills that memory with zeros. It
does not load the starting value that InitializedMutableBufferPass
saves in the program, while the CPU runtime does. So a buffer that
starts from another value is wrong with no error:

    self.register_buffer("count", torch.tensor([5, 7], dtype=torch.int32))
    ...
    self.count.add_(1)
    # with InitializedMutableBufferPass(["count"]), the delegate starts
    # count at zero, so it comes back as [1, 1] instead of [6, 8]

This change is a stopgap, not the real fix. The partitioner now leaves
integer mutable buffers on CPU, and any other buffer that is not
floating point, even with the default skip_mutable_buffer=False. The
ops that update the buffer can still run in the delegate: the buffer
goes in as a delegate input, and the new value comes back as a delegate
output that CPU writes to the buffer, as skip_mutable_buffer=True
already does for every buffer. Floating-point buffers are delegated as
before, so a float buffer still starts at zero. The real fix is for the
QNN runtime to load the starting value of the buffers it owns, which
issue pytorch#24749 tracks. Then this special case can go.

A test lowers int64 and int32 counters updated by a constant and an
argmax, and checks that only the float buffer is delegated. With this
change, the counter above returns [6, 8] for int32 and int64 on the
QNN x86 simulator, and a float32 counter still does not. The delegate
test of an int64 counter starts from zero, so it passes with or without
this change.
full, full_like, arange and scalar_tensor have values that are known
ahead of time, so their QNN builders make static tensors that the
consumers read directly. When such a value is also an output of the
delegated graph, for example because the op that uses it stays on CPU,
QNN never publishes it. QNN only exposes a graph output that an op
writes, and a static tensor has no writer. The program then fails when
it runs:

    y = x * 2
    return y, torch.full_like(y, -1)

    Method forward: the QNN context binary binds 2 tensors (1 bindable
    inputs, 1 bindable outputs) but ExecuTorch passed 3 arguments

When the constant is also used inside the delegate, QNN fails to build
the graph instead ("Failed to generate Qnn context binary").

The 4 builders now share a NodeVisitor.define_constant helper. When the
value stays inside the graph, it defines the static tensor as before.
When the value is a graph output, it also adds a Reshape that copies the
static tensor into the output tensor, made with
define_custom_tensor_wrapper, which can now also build a tensor that
holds given data.
Graphs where these values stay inside the delegate are built as before.
… full

A full_like reads only the shape of its input, and the QNN backend
builds it as a static tensor. When the full_like is the only output of a
delegate, QNN drops the ops that only fed it, and the QNN graph is left
with no input, while ExecuTorch still passes one, so the program fails
when it runs:

    return torch.full_like(torch.frac(x), 0.5)

    Execute with 1 in, 1 out; graph expects 0 in and 1 out

With another output that reads an input, like y * 2, the program runs,
but the delegate still takes x and the ops that only fed the full_like.

A new to_edge pass, ConvertFullLikeToFull, replaces a full_like whose
shape is static with a full of the same shape, value and dtype, and
removes the ops that only fed it. On HTP, a full alone reads nothing at
runtime, so it stays on CPU, as other constant-only partitions already
do. This also covers a full_like of a value computed on CPU. A
full_like with a dynamic shape is left as it is.

I64toI32 casts the int64 result of every full to int32, but not of a
full_like. So an int64 full_like is left as it is too, or the new cast
would wrap its value, or a value computed from it, with no error. Alone
in a delegate it still fails as before.

Tests: a unit test checks that the full_like becomes a full and nothing
reads x any more, and that a dynamic shape and an int64 full_like keep
the full_like. It also runs the result against eager, with a float and
an int fill value. A delegate test lowers the 2 cases above and checks
their outputs on the x86 simulator, together with an int64 full_like of
2**40, and a quantized one lowers the full_like alone. The
cases with only the full_like fail without the pass. Other backends do
not drop a partition that reads nothing at runtime, so there the lone
full keeps its delegate.
The QNN SDK's HTP op validator sometimes rejected a delegated integer
op, like an int32 mul, with an error whose bound changed from run to
run:

    [4294967295] has incorrect Value 1, expected < 225764768

Every tensor without quantization, such as an int32 or float16 one,
gets its quantize params from UndefinedQuantizeParamsWrapper. Its
CreateQuantizeParams() declared Qnn_QuantizeParams_t without an
initializer and set only the encoding definition and type, so the
encoding union kept leftover stack bytes. The validator reads them even
when the encoding is undefined, and the bound in the error is that
garbage.

All 6 CreateQuantizeParams() now value-initialize the struct, which
zeroes all of it, union included. QNN_QUANTIZE_PARAMS_INIT is not used,
because brace initialization sets only the first union member, and
newer compilers, like GCC 15, no longer zero the rest. The other 5 set
their union member right after, so they are unchanged in practice.

Test: with the QNN 2.51 x86 simulator for SM8650 in float16, one fresh
process per run, lowering a k * k of int32 k was rejected in 18 of 112
runs, and torch.where(k > 0, k, k * 2) in 8 of 48. With the union zeroed
where the params reach QNN, both passed every run (96
and 48). In each of the 11 failing processes checked, the same op
passed validation once only its quantize params union was zeroed. No unit test is added,
since none of the existing test targets builds this C++ header against
the QNN SDK.
During decomposition, exir calls a partitioner's ops_to_not_decompose
filter on the nodes of the ATen program one at a time, in graph order.
Each node whose op is in the list and that the filter accepts gets its
target replaced right away by a copy in the EDGE_DO_NOT_DECOMP
namespace (except ops that exir does not preserve, such as mutable and
aliasing ops), and the original target comes back only after that
partitioner's decomposition. So a filter that looks at other nodes, for
example to ask whether an input comes from a dequantize op, sees that
copy for every earlier node that was replaced, not the original op.

The docstring said which program each filter is applied to, but not
this. Partitioner authors now find it there instead of in exir's code.
A constant op such as full can end up as an output of a QNN partition,
either because it is a graph output or because the op that reads it
stays on CPU. QNN then writes it with a Reshape from a static tensor
(see define_constant). Constant ops skip the QNN op check, and HTP
cannot build such a constant with more than 5 dims, so the whole graph
fails to build:

    return x * 2, torch.zeros(1, 2, 1, 1, 3, 4)

    OpDef_Const failed to generate tensor
    Failed to add node to Qnn Graph with error: 6007
    AssertionError: Failed to generate Qnn context binary.

Before constant outputs were written with a Reshape, the same program
built, but it failed when it ran, because QNN never published the
constant.

On HTP, the partitioner now leaves constant ops of more than 5 dims on
CPU. A new test lowers a 6-dim constant that is a graph output, and one
that a CPU op reads, and checks that the multiply is delegated and the
constant is not. Both cases fail without this change.
In HTP float16, Concat can read a static bool input of all True as
False, with no error. For example, with a positive x of shape (2, 3), a
mask built from a computed mask and a constant one comes back wrong on
the x86 simulator of QNN SDK 2.51:

    torch.cat([x > 0, torch.full((2, 2), True)], dim=1)
    # QNN:   [[True, True, True, False, False], ...]
    # eager: [[True, True, True, True, True], ...]

The static tensor ExecuTorch gives QNN holds the right values: QNN
Saver records 0x01 for each element. The wrong result also depends on
the shapes and on where the static input is. At the same shapes,
constants with mixed values, float and int32 cats with a constant, and
quantized graphs come out right.

In HTP float16, the partitioner now keeps on CPU a bool cat that reads
a static tensor: a constant op such as full, or a parameter, a buffer
that the model does not update, or a lifted constant. Since the failing
shapes are not known in advance, this also moves some cats that came
out right, which can split a graph into 2 delegates. A constant op such
as full can then become a partition output, which QNN writes with a
Reshape. The partitioner keeps the fp16 HTP check in one flag,
is_htp_fp16, which the dilated conv VTCM warning now reads too.

A new test checks that, in HTP float16, a bool cat of a full or of a
buffer stays on CPU, that the same float32 cat is delegated, and that a
quantized bool cat stays delegated. Both cat delegate tests gain a bool
cat of a full. The floating-point one comes out wrong without this
change, and the quantized one checks the values of the cat that stays
delegated.
ConvertFullLikeToFull turned every full_like of a static shape into a
new full node. A full_like named in skip_node_id_set or skip_node_op_set
then lost its skip, since the new node has another name and op, so the
partitioner could delegate the full that the user asked to keep on CPU.

The pass now takes both skip sets, which the pass manager already hands
to every pass that accepts them, and leaves a skipped full_like alone.
It stays on CPU, so the problem the pass solves, QNN dropping the ops
that only feed a delegate output, does not apply to it.

A new test runs the pass with each skip set and checks that the
full_like stays and that its value matches eager.
The ops_to_not_decompose docstring said that exir calls the filter on
the nodes in graph order. exir walks all top-level nodes first and only
then the nodes of each cond, map and scan submodule. So a filter on a
submodule node already sees every replaced top-level node, including
those after the cond. The docstring now says that, and that a filter
sees the EDGE_DO_NOT_DECOMP op for each node already replaced before it.
…mposeRmsNorm

RecomposeRmsNorm erased each rebuilt norm and its dead inputs with its
own helper, _erase_unused. The pass already removes dead code with
graph.eliminate_dead_code() before it starts, so right after a rebuild
the only dead nodes are the ones that rebuild left. Calling
eliminate_dead_code() there does the same thing, and dead nodes are
erased one way. It still runs right away, so a node that another norm
shares has the right users when _is_skipped counts them.

The RMSNorm tests in test_passes.py pass unchanged.
…or on CPU

In HTP float16, the partitioner keeps on CPU a bool cat that reads a
static tensor, because HTP Concat can read such an input of all True as
False. The check looked only at the cat's direct inputs. A static tensor
reached through a reshape was missed, so the cat stayed delegated, and
on the QNN x86 simulator it came back wrong in the same way:

    torch.cat([x > 0, mask.reshape(1, 4)], 1)  # mask is a bool buffer
    # QNN:   [1, 0, 1, 0, 0, 0, 0, 0]
    # eager: [1, 0, 1, 0, 1, 1, 1, 1]

The check now looks through view_copy, squeeze_copy, unsqueeze_copy,
permute_copy and expand_copy, which only change the shape or the order
of the dims, to the tensor they read. A permute or an expand of a static
tensor read right at the shapes tried on the simulator, but whether
Concat misreads depends on the shapes, so those cats stay on CPU too,
like a cat of the static tensor itself.

The partitioner test gains a view and an expand of a full, and a
reshape and a permute of a buffer. All 4 stay delegated without this
change.
On HTP, the partitioner leaves a partition on CPU when it reads no
runtime value. It merges partitions even when no data flows between
them, unless that makes a cycle, and it counts the output of a CPU op as
a runtime value. RecomposeRmsNorm guessed this in its own way, and the
guess was wrong in some graphs. It did not rebuild a norm of constants
that the partitioner merges with unrelated ops that read an input, or a
norm whose input is the output of a CPU op. The partitioner still
delegated the decomposed norm, and in float16 it overflowed with no
error.

The partitioner already estimates this for the ops it keeps whole. That
estimate moves to find_nodes_left_on_cpu in partition/utils.py, and
RecomposeRmsNorm uses it too, with may_be_delegated telling which ops
the partitioner may take. Ops that the op packages in the compiler specs
build count as ops QNN takes. QNN's op check is not known this early.

Also:
- capture_program takes skip_node_id_set and skip_node_op_set and
  passes them to the edge passes, like to_edge_transform_and_lower_to_qnn.
  Its docstring says that only the passes that read the sets keep those
  nodes for CPU.
- The RMSNorm runtime value tests run the export pipeline first, as the
  real lowering does, so pow has a lifted exponent and a QNN builder.
  The buffer update in one of them is a clamp_, because the pipeline
  turns a fill_ into a full that no longer reads the buffer. A norm of
  constants is tested in a graph with no other runtime value, and a
  norm next to a mask index is now expected to be rebuilt, since the
  partitioner delegates it with the comparison. A new test checks that
  the output of a skipped op counts as a runtime value.
… RecomposeRmsNorm

RecomposeRmsNorm estimates which ops the partitioner leaves on CPU. It
asked may_be_delegated about each op, and it did not know two rules
that QnnOperatorSupport applies on HTP: a constant of more than 5 dims
stays on CPU, and in float16 so does a bool cat of a static tensor. So
the pass could expect such an op on QNN while the partitioner kept it on
CPU. For example, a norm of constants that reaches the input only
through such a cat was rebuilt as an rms_norm. HTP then dropped its
partition, which read no runtime value, and lowering failed, since
rms_norm has no CPU kernel:

    Node aten_rms_norm_default ... was not decomposed or delegated

The two rules move to get_htp_skip_reason in partition/utils.py. Both
QnnOperatorSupport and may_be_delegated call it, so they apply the same
rules. get_backend_info reads the backend, the float16 precision and
the op package ops from the compiler specs for the pass.

QNN's op check and the limits of older HTP architectures still run only
in the partitioner.

The new test lowers such a model with ConstantFolding off, since it
would fold the norm of constants away, and fails without this change.
… in ConvertFullLikeToFull

ConvertFullLikeToFull gave the new full the dtype of the full_like but
not its device, so the full was made on the default device. With an
input on another device, such as CUDA, x + torch.full_like(x, 0.5) then
failed in the next pass that ran the graph:

    FakeTensorDeviceMismatchError: Expected all tensors to be on the same
    device, but found at least two devices, cuda:0 and cpu!

The full now gets the device too.

A full is also always contiguous, while a full_like takes the dim order
of its input, and the pass kept the meta of the full_like. For a
channels last x, x + torch.full_like(x, 0.5) with the add on CPU then
lowered, but failed at runtime:

    Check failed (tensors_have_same_dim_order(a, b, out))

A full_like that is not contiguous is now kept.
…s in the test lowering stage

ToEdgeTransformAndLower in the backend tester passed its own default
compiler specs to the edge passes, and not the skip sets of its
partitioners. With a QnnPartitioner that skips rms_norm,
RecomposeRmsNorm still built an rms_norm, the partitioner left it on
CPU, and lowering failed, since rms_norm has no CPU kernel. And with a
float16 QnnPartitioner on a stage made for quantized HTP, the passes did
not rebuild the float32 part of a norm, so it overflowed in float16.

The stage now passes the specs of its first QNN partitioner and the skip
sets of all of them, as to_edge_transform_and_lower_to_qnn does.
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Reviewing PR #24428

  • Gather context (diff, commits, changed files, CLAUDE.md)
  • Run independent reviewers
  • Consolidate findings
  • Fact-check findings: three minor findings survive, none blocking
  • Post review (in progress...)

View job run

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 54m 10s —— View job


Review of PR #24428

  • Gather context (diff, commits, changed files, CLAUDE.md)
  • Run three independent reviewers
  • Consolidate findings
  • Fact-check findings
  • Post review

I found three minor issues, none of them a regression: the HTP fp16 norm rebuild misses a weightless norm unless a mul follows it, the ATen-level CPU estimate does not model ConvertFullLikeToFull or the new HTP skip rules, and no quantized test reaches the graph-output branch of define_constant.

Detailed review

PR Review: #24428

Summary

This PR makes RecomposeRmsNorm keep each norm's dtype (on HTP fp16 it rebuilds only the normalization, so float32 squares no longer overflow), shares the partitioner's CPU estimate and new HTP skip rules with the passes, adds ConvertFullLikeToFull, and builds constant graph outputs through a Reshape. There are three minor issues and no regressions.

Code Quality

  • The HTP fp16 normalization-only rebuild misses a norm with no weight unless a mul follows it (backends/qualcomm/_passes/recompose_rms_norm.py:275-280, 315-321).

    • Both patterns start at a mul after the scale mul. So x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) is only matched when some later mul sits within the few nodes the "*" wildcard can skip.
    • If the norm is a graph output, or feeds a linear with no mul after it, it stays decomposed on HTP fp16. Squares of values above about 256 still overflow there, silently.
    • ScaledRmsNorm, the model in the large-value test, only gets the rebuild because it multiplies by a buffer.
    • This is not a regression.
    • A fix should match at the scale mul in a second loop, after the main one, for HTP fp16 only. graph.nodes reaches the scale mul before the weight mul, so matching it in the main loop would take norms away from the whole-norm rebuild.

    Fix this →

  • The ATen-level CPU estimate does not model two decisions this PR adds (backends/qualcomm/partition/qnn_partitioner.py:394-438).

    • _may_run_on_qnn and _left_on_cpu decide which kept-whole ops get decomposed.
    • They never apply get_htp_skip_reason, unlike RecomposeRmsNorm, which applies it through may_be_delegated.
    • They also count a full_like as reading its input, but ConvertFullLikeToFull removes that read later.

    Example on HTP: forward(x): return F.rms_norm(torch.full_like(x, 1.0), x.shape[-1:]).

    1. The estimate sees x read, so rms_norm stays whole.
    2. ConvertFullLikeToFull turns the full_like into a full that reads nothing.
    3. _drop_partitions_without_runtime_inputs drops the partition.
    4. exir raises "was not decomposed or delegated".

    On main no QNN op read x here either, so this case was already broken and this is not a regression. The missing skip rules mostly cause decompositions that aren't needed. Treating a full_like that is static-shape, non-int64 and contiguous as reading nothing, and applying the get_htp_skip_reason rules on ATen targets, would keep the estimate in line with the partitioner.

    Fix this →

Testing

  • No quantized test on HTP reaches the graph-output branch of define_constant (backends/qualcomm/builders/node_visitor.py:638-643).

    • test_qnn_backend_constant_graph_outputs exists only in TestQNNFloatingPointOperator (test_qnn_delegate.py:606-609).
    • The quantized test_qnn_backend_full_like_shape_only expects 0 partitions on HTP.
    • The quantized Arange, Full and FullLike tests use the constant inside the partition.
    • ConstantOp in quantizer/annotators/htp_rules.py:343-365 annotates arange, full, full_like and scalar_tensor. So a quantized model that returns one of them runs get_quant_tensor_value and the Reshape without any test.

    Add the same test to TestQNNQuantizedOperator with get_qdq_module and self.rtol = 1e-1. As the other new quantized tests note, the default rtol of 1 would pass an all-zero output.

    Fix this →

Recommendation

Approve

None of the findings blocks merging. The quantized constant-output test is cheap, so it is worth adding before merge. The other two fit into the follow-up already planned for the checker and fallback questions from shewu-quic's review.

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. release notes: qualcomm Changes to the Qualcomm backend delegate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants