Skip to content

Fix addmm and mm lowering for scales, bias shapes and identity permutes - #24658

Merged
shoumikhin merged 8 commits into
pytorch:mainfrom
shoumikhin:addmm-scales-and-bias
Nov 5, 2026
Merged

shoumikhin merged 8 commits into
pytorch:mainfrom
shoumikhin:addmm-scales-and-bias

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

torch.addmm(bias, x, w, beta=..., alpha=...) computes beta * bias + alpha * (x @ w), with any broadcastable bias. Some lowering steps miss this, so some programs give wrong values or fail.

What is wrong today

  • beta and alpha are dropped. AddmmToLinearTransform turns addmm(b, x, w.t(), beta=2.0) into linear(x, w, b) without the scale. XNNPACK delegates a scaled addmm to its fully connected op, which has no scales.
  • Some bias shapes break. The transform makes a linear with any bias, but ExecuTorch's linear kernel takes only a 1-D bias. The LLM export then fails at run time. XNNPACK misreads any bias that is not 1 value per output channel.
  • A [0, 1] permute counts as a transpose, so addmm and mm give wrong values with a square weight and fail with any other.
  • Dropping the view after a linear fails for an [M, N] bias and for x @ x.t(), because the transform points the linear at the dequantized tensor.

What this change does

  1. The transform keeps an addmm unless its weight is transposed, its scales are 1 and its bias is 1-D. addmm_can_be_linear holds the rule. Only t or a [1, 0] permute counts as a transpose, also for mm.
  2. Samsung's partitioner uses it, and skips one with a constant weight, because constant propagation folds the transpose first. These run on the CPU instead of giving wrong values or failing to lower.
  3. The view is kept for a bias of more than 1 dim, and only the linear's input is changed.
  4. XNNPACK keeps out a scaled addmm, and one whose bias is not 1 value per output channel.

Vulkan runs the same transform, and applies the scales itself for float weights. A 2-D bias was already correct there, but now its weight is transposed each run.

Testing

  • New tests cover scaled addmm, bias shapes, program-input biases, a decomposed F.linear, a standalone addmm, a [0, 1] permute, and the input as bias or weight, each failing without its fix.
  • The Vulkan test passes on SwiftShader and fails without the fix; CI does not run it.
  • After the LLM export's ConvertToLinearPass, an addmm with a non-1-D bias now runs. An F.linear with one still fails, and XNNPACK misreads it.
  • 5 static-shape models and 8 dynamic-shape programs match main byte for byte. Samsung was not run.

@shoumikhin shoumikhin added the release notes: xnnpack Changes to the XNNPack backend delegate label Nov 5, 2026
Copilot AI balanced review requested due to automatic review settings November 5, 2026 09:26
@pytorch-bot

pytorch-bot Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 4db2d9e with merge base d1f597e (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 5, 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 5, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 19m 21s —— View job


Request changes: AddmmToLinearTransform still turns an addmm whose bias is not 1-D into a linear that ExecuTorch's linear kernel rejects, and a scaled addmm now makes the whole Samsung lowering fail.

Full review

PR Review: #24658

Summary

The PR stops scaled addmms from becoming linears or entering the XNNPACK delegate. It also keeps an addmm whose bias is not per channel out of XNNPACK, and keeps the view after a linear whose bias has more than 1 dim.

There are 2 major problems:

  • The shared transform still makes linear nodes with a bias that linear.out rejects.
  • Samsung now fails to lower a scaled addmm.

There are also 4 minor problems. All 4 changed files were reviewed. Nothing was run, so every finding comes from reading the code.

Code Quality

  • Major: an addmm whose bias is not 1-D still becomes a linear, and ExecuTorch's linear kernel rejects that bias (backends/transforms/addmm_mm_to_linear.py:134-156).
    • The transform checks only the scales. addmm(b, x, w.t()) with a [M, N], [M, 1], [1, N] or 0-D bias still becomes linear(x, w, b).
    • The optimized linear.out takes only a 1-D bias of size N or 1 (kernels/optimized/cpu/op_linear.cpp:113-123). Portable has no linear.out (it is not in kernels/portable/functions.yaml).
    • The LLM export runs ConvertToLinearPass on the graph left outside delegates (extension/llm/export/builder.py:558), and that pass ends with this transform (backends/xnnpack/_passes/convert_to_linear.py:191). With XNNPACK, the new AddmmConfig check keeps an [M, N]-bias addmm out of the delegate, where it used to give wrong values. The transform then makes it such a linear, which fails at runtime with InvalidArgument. It never reaches a portable kernel, although the description says it does.
    • The guard at lines 91-96 makes the graph correct for ATen only. That is all test_bias_with_more_than_one_dim_keeps_the_input (test_addmm_mm_to_linear.py:225) checks, because it compares program.module() with eager. Vulkan and Samsung preprocess get the same linear; how they treat its bias was not checked.
    • Fix: in replace_addmm_mm_with_linear, skip an addmm whose bias is not 1-D, the same way the new scale check does, or reshape a [1, N] bias to [N]. The node then stays an addmm, which the new XNNPACK tests already run on portable kernels, and linears made by this transform no longer need lines 91-96. Fix this →
  • Minor: Vulkan's quantized linear fusion still drops beta and alpha.
    • backends/vulkan/op_registry.py:452-464 accepts any addmm, with no check on its scales.
    • QuantizedLinearMatch anchors on aten.addmm.default (backends/vulkan/patterns/quantized_linear.py:300-305) and reads its bias (:171-176), but never reads the scales.
    • FusePatternsPass runs right after AddmmToLinearTransform (backends/vulkan/vulkan_preprocess.py:192-196). So a scaled addmm with a dequantized constant weight is still fused without its scales, as before this PR. The description's "Vulkan keeps a scaled addmm and applies the scales itself" is true only for float weights.
    • Fix: make the match fail for a scaled addmm, or narrow the claim. Fix this →
  • Minor, low confidence: LinearConfig has no matching bias check.
    • to_edge_transform_and_lower keeps an aten.linear whenever LinearConfig.check_constraints passes (exir/backend/canonical_partitioners/config_partitioner.py:180-186).
    • LinearConfig (gemm_configs.py:300-340) never looks at the bias, and backends/xnnpack/operators/op_linear.py:66-89 passes it to the same XNNFullyConnected.
    • So a linear with 1 bias value for N > 1 channels seems to hit the misread that this PR fixes for addmm. The 0-D bias that F.linear allows is one example. The same model would then give different results depending on whether linear is decomposed. This was not traced end to end.
    • Fix, if this holds: apply the bias check to LinearConfig too. Do not put it in GEMMConfig, because a convolution's channels are not the last output dim.

Testing

  • Minor: test_addmm.py never uses a transposed weight.
    • Every addmm in backends/xnnpack/test/ops/test_addmm.py takes a [K, N] parameter directly. The transform skips those (addmm_mm_to_linear.py:142-147), and XNNPACK lowers them with AddmmVisitor.
    • The addmm(b, x, w.t()) form, which a decomposed linear produces, goes through the transform and LinearVisitor instead. That path is not tested with any of the biases the new check accepts ([N], [1, N], 0-D with N = 1) or rejects.
    • Fix: add self.weight.t() variants. Fix this →
  • Minor: nothing tests the Vulkan change.
    • Vulkan now lowers a scaled addmm as an addmm instead of as a linear without the scales.
    • The description says nothing was run on Vulkan, and no test under backends/vulkan/test/ uses an addmm with beta or alpha.
    • Fix: add a case to test_vulkan_delegate.py with a float weight and a quantized weight. It would check the description's claim and catch the quantized case above. Fix this →

Backward Compatibility

  • Major: a scaled addmm now makes the whole Samsung lowering fail, instead of falling back to the CPU.
    • EnnOperatorSupport.is_node_supported accepts every aten.addmm.default (backends/samsung/partition/enn_partitioner.py:41-43, :84-85). It relies on AddmmToLinearTransform (backends/samsung/_passes/enn_pass_manager.py:79) to turn the node into a linear.
    • Samsung has no addmm builder, so an addmm that the transform now leaves in place makes enn_preprocess.py:64-67 raise RuntimeError.
    • The description accepts this, but a few lines in is_node_supported that reject a scaled addmm would let the rest of the model lower.
    • The scale check is now written out at both gemm_configs.py:489 and addmm_mm_to_linear.py:136-139. One helper in addmm_mm_to_linear.py, used in all three places, would keep them in step if the transform skips more cases, as the first Code Quality item suggests. Fix this →

Recommendation

Request Changes

The first Code Quality item and the Samsung item block approval, and both fixes are small:

  • Because of the first item, the [M, N] bias fix does not hold in the LLM export.
  • The Samsung item turns 1 scaled addmm into a failed lowering of the whole model, when a CPU fallback takes only a few lines.

Review steps

  • Get the PR diff and context
  • Run 3 independent reviewers
  • Merge their findings (7 candidates; 2 were reported by all 3 reviewers)
  • Fact-check the findings (6 kept; 1 dropped: the order of the checks in AddmmConfig.check_constraints, which has no effect)
  • Post the review

Not checked:

  • No tests or scripts were run, because this environment does not allow running Python.
  • The XNNPACK C sources are not in the checkout.
  • Nothing was run on Vulkan or Samsung.

@shoumikhin
shoumikhin force-pushed the addmm-scales-and-bias branch from 6de0bb4 to 274e6e8 Compare November 5, 2026 11:34
@shoumikhin shoumikhin changed the title Fix addmm lowering with beta/alpha or a bias that is not per channel Fix addmm lowering with beta or alpha, or a bias that is not 1-D Nov 5, 2026
@shoumikhin

Copy link
Copy Markdown
Contributor Author

Both major items are fixed.

1. Bias that is not 1-D. I reproduced it: after ConvertToLinearPass, such an addmm became a linear that failed with "Bias has wrong dimensionality". The new helper addmm_can_be_linear also requires a 1-D bias, so these stay addmm and run. The new transform test fails without it. An F.linear with such a bias still becomes a linear in that pass's source-partition step. I left that for the LinearConfig follow-up below.

I kept the view rule for a bias with more than 1 dim, since a linear kept whole from export can still carry one. Its test uses such a linear, and fails without the rule.

2. Samsung. The partitioner now takes an addmm only when addmm_can_be_linear allows it. I added no test, since it needs the ENN SDK, which I do not have. With the native modules stubbed, is_node_supported returns True for a plain addmm and False for scaled or [4, 8]-bias ones. Nothing ran with the SDK. XNNPACK keeps its own check, because it can take a [1, N] bias that ExecuTorch's linear kernel cannot.

Minor items:

  • Vulkan quantized fusion: the description now limits the claim to float weights. Those scales were dropped before this change too.
  • LinearConfig: confirmed, it misreads such a bias today. With the same check, a rejected linear on an input of more than 2 dims is decomposed, and XNNPACK takes the pieces and still drops the bias. That needs its own PR.
  • Transposed weight: by default XNNPACK leaves addmm(b, x, w.t()) outside, but to_edge plus to_backend takes a decomposed F.linear whole. A new test covers that path; on main an [M, N] bias gives wrong values there.
  • Vulkan test: I have no Vulkan device to run one on.

Copilot AI balanced review requested due to automatic review settings November 5, 2026 11:34
@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 5, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 21m 20s —— View job


Needs discussion: Samsung still accepts addmms that its preprocess cannot turn into a linear, as it did on main, and Vulkan now runs a scaled addmm through a permute of the weight that its partitioner never checks and nothing tests.

Full review

PR Review: #24658

Summary

The PR keeps an addmm with beta or alpha other than 1, or with a bias that is not 1-D, from becoming a linear. It also keeps such an addmm out of the XNNPACK and Samsung delegates.

There is 1 major problem, which predates the PR, and there are 2 minor ones. None of them was confirmed to be a regression. All 5 changed files were reviewed. Nothing was run, so every finding comes from reading the code.

Code Quality

  • Major, predates the PR: Samsung still accepts addmms that its preprocess cannot turn into a linear (backends/samsung/partition/enn_partitioner.py:84-88). All 3 reviewers reported this.
    • The helper is not the whole rule. addmm_can_be_linear (backends/transforms/addmm_mm_to_linear.py:117-127) checks the scales and the bias rank. But replace_addmm_mm_with_linear also needs the weight to be a t_copy or permute_copy (:150-156), and otherwise leaves the addmm alone.
    • A transposed constant weight is left alone too.
      • transform_for_preprocess_pass runs Samsung's ConstantPropPass (enn_pass_manager.py:74) before AddmmToLinearTransform (:79).
      • That pass empties the skip targets (customized_constant_prop.py:25-27). permute_copy is not a default skip target either (exir/passes/constant_prop_pass.py:38-43).
      • So permute_copy(w) of a lifted weight is folded into a _prop_tensor_constant placeholder (constant_prop_pass.py:257-279), and the transform then skips the addmm as standalone.
    • The whole lowering fails. Samsung has no addmm builder (backends/samsung/builders has op_linear.py only), so enn_preprocess.py:64-67 raises.
    • Trigger: a model that calls torch.addmm(b, x, w) with a [K, N] parameter, as Hugging Face GPT-2's Conv1D does, or torch.addmm(b, x, w.t()) with a parameter w. In both cases beta = alpha = 1 and the bias is 1-D. Samsung keeps aten.linear from decomposition (enn_partitioner.py:201), so a direct torch.addmm is how an addmm usually reaches it.
    • Why it matters here: this failed the same way on main. But the new comment at :85-87 gives the wrong direction of the rule. The partitioner needs every addmm it accepts to become a linear. That the transform never converts an addmm this gate rejects does not give that.
    • Fix:
      • Move the weight check into addmm_can_be_linear, so the helper holds the whole rule and the transform needs no separate check.
      • In transform_for_preprocess_pass, run AddmmToLinearTransform before ConstantPropPass. Verifying this needs the ENN SDK, so it may need the Samsung maintainers.
    • Confirmed by reading; not run. Fix this →
  • Minor, suspected: Vulkan lets in the weight's permute without checking it, because it assumes the permute will fuse into a linear (backends/vulkan/partitioner/vulkan_partitioner.py:199-231, :325-327). All 3 reviewers reported this.
    • The assumption: is_linear_permute accepts a t_copy or permute_copy whose only user is an addmm. It returns before the permute's own op checks, because the permute "can be fused with the mm or addmm to produce a linear" (docstring at :201-203).
    • What changes:
      • AddmmToLinearTransform (vulkan_preprocess.py:192,194) now keeps a scaled addmm, and one whose bias is not 1-D.
      • So the permute of the constant weight now runs as an op of its own, which the partitioner never checked.
      • mat2 is then not a TensorRef, so addmm_tiled does not prepack the weight (backends/vulkan/runtime/graph/ops/impl/gemm/matmul/MatMul.cpp:247-281), and the weight is transposed on every run.
      • Before this PR, these became a linear, without the scales in the scaled case. Now they take a path that nothing tests.
    • Not checked: whether Vulkan's permute handles a constant input on this path.
    • No device is needed: the PR says there is no Vulkan device, but the Vulkan CI job runs on SwiftShader (.github/workflows/pull.yml:1842-1843). That job runs only the *pt2e* and *torchao* tests of test_vulkan_delegate.py (:1867-1868).
    • Fix: in is_linear_permute, return (False, False) when the user is an addmm that addmm_can_be_linear rejects. Add a SwiftShader test of addmm(b, x, w.t()), once with beta=2.0 and once with an [M, N] bias. Fix this →
  • Minor, low confidence: the new comment says MMConfig has no bias, but an mm taken through a linear source partition carries the linear's bias (backends/xnnpack/partition/config/gemm_configs.py:492-494). 2 reviewers reported this.
    • get_deps_from_src_partition adds every node of the source partition to the deps, including the bias add (:596-599).
    • In preprocess, create_linear looks for that bias with find_bias_for_mm (backends/xnnpack/_passes/convert_to_linear.py:77-94, :120-121):
      • When a view_copy sits between the mm and the add, it returns None. A linear without a bias then replaces the partition output (:136-149), so the bias is dropped with no error.
      • When the add follows the mm directly, its bias is used with no shape check.
    • Trigger: F.linear(x[2, 2, 3, 16], w[8, 16], b[3, 8]) through to_edge() + partition(), the flow of the new test_fp32_decomposed_linear_with_biases. ATen lowers a linear on an input of more than 3 dims with a bias that is not 1-D as matmul + add, which gives view, mm, view, add. That decomposition is from memory of ATen's Linear.cpp and was not run.
    • Relation to the deferred fix: this is the dropped bias the author deferred, but it is reachable today without any LinearConfig change. The new test uses only 2-D inputs.
    • Fix: reword the comment, and add a 4-D case to the test. Fix this →

Recommendation

Needs Discussion

  • Samsung: decide whether to fix the gate in this PR or hand it to the Samsung maintainers. Moving the weight check into addmm_can_be_linear is small and in scope. The pass order needs the ENN SDK to verify.
  • Vulkan: a SwiftShader run of the changed path would settle the second item before merge, without a device.

Review steps

  • Get the PR diff and context
  • Run 3 independent reviewers
  • Merge their findings (7 candidates; 2 were reported by all 3 reviewers)
  • Fact-check the findings: 3 kept, 4 dropped. The dropped ones:
    • The view rule at addmm_mm_to_linear.py:92 also blocks a [1, N] bias. This is true, but it only keeps a view, and only in a rare graph.
    • The helper accepts a [1] bias that ENN's FC op might misread. This was not checked, and a kept linear with that bias reaches ENN the same way on main.
    • A static-quant [1, N] bias may not suit QuantParams.from_bias, which assumes a 1-D bias. This was not checked; the case is rare, and main accepts it the same way.
    • The replace_addmm_mm_with_linear docstring is stale. That is a wording note, which belongs in a detailed review.
  • Post the review

Not checked:

  • No tests or scripts were run, because this environment does not allow running Python.
  • Nothing was run on Vulkan or with the ENN SDK.
  • ATen's Linear.cpp, which decides how F.linear decomposes, is not in the checkout.

@shoumikhin
shoumikhin force-pushed the addmm-scales-and-bias branch from 274e6e8 to 2198156 Compare November 5, 2026 14:02
@shoumikhin
shoumikhin requested a review from SS-JIA as a code owner November 5, 2026 14:02
@shoumikhin shoumikhin changed the title Fix addmm lowering with beta or alpha, or a bias that is not 1-D Fix addmm lowering when beta or alpha is not 1, or the bias is not 1-D Nov 5, 2026
@shoumikhin

Copy link
Copy Markdown
Contributor Author

1. Samsung. The comment now says ENN takes only an addmm that preprocess removes. The weight check also moved into addmm_can_be_linear, so the partitioner leaves a standalone addmm(b, x, w), as in GPT-2's Conv1D, to the CPU. I checked that with the native modules stubbed. An addmm of a transposed constant weight is now left to the CPU too, because ConstantPropPass folds that transpose first. An addmm of constants is still taken and folded. With stubs, running the transform before that pass gives a linear. I did not swap the passes, because verifying that needs the ENN SDK. I left it to the Samsung maintainers.

2. Vulkan. I ran a Vulkan build on SwiftShader. On main, addmm(b, x, w.t()) with beta=2.0 was off by 1.7, and with alpha=0.5 by 3.5. With this change, both scales match eager. A [N], [1, N], [M, N] or [M, 1] bias also matches, as it already did on main. The suggested is_linear_permute change gave the same graph and outputs, so I did not add it. The new test_vulkan_backend_addmm passes on SwiftShader and fails without the fix. CI runs only the pt2e and torchao tests of that file, so it will not run this test. In these rare cases the weight is now transposed on every run instead of packed once, which may cost some speed.

3. mm with a linear's bias. Reproduced: a 3-D or 4-D F.linear with a [3, 8] bias through to_edge and partition drops the bias. The same happens on main, so this change does not cause it. I reworded the comment to say an mm has no bias argument. I did not add the 4-D test case, because it fails both here and on main. Fixing the drop belongs with the LinearConfig follow-up.

Copilot AI balanced review requested due to automatic review settings November 5, 2026 14:02
@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 5, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 20m 52s —— View job


Approve: the reviewers found no blockers and no major problems, and the 1 minor finding, that addmm_can_be_linear treats an identity permute_copy as a transpose, predates this PR.

Full review

PR Review: #24658

Summary

The PR stops an addmm from becoming a linear when its beta or alpha is not 1 or its bias is not 1-D, and keeps such an addmm out of the XNNPACK and Samsung delegates.

  • No blockers and no major problems were found.
  • There is 1 minor problem, and it predates the PR.
  • All 6 changed files were reviewed.
  • Nothing was run, so the finding comes from reading the code.

Code Quality

  • Minor, predates the PR: addmm_can_be_linear treats any permute_copy weight as a transpose (backends/transforms/addmm_mm_to_linear.py:125). 2 of the 3 reviewers reported this.
    • What the code does: the helper checks only the target of node.args[2]. Line 152 then drops the permute without reading its dims and builds linear(x, w, b), which computes x @ w.T + b.
    • Where it goes wrong: with an identity permute such as permute_copy(w, [0, 1]), the addmm computes x @ w + b. Then:
      • when K == N, the values are wrong and nothing reports an error;
      • otherwise, the fake-tensor call at lines 158-160 fails on the shapes, and the lowering stops.
    • Trigger: torch.addmm(b, x, w.permute(0, 1)), for example from generic code that permutes with a computed order. Any graph that runs the transform is affected, such as the LLM export's top-level ConvertToLinearPass (extension/llm/export/builder.py:558) or Vulkan's preprocess.
    • Not checked: whether export keeps an identity permute was not run. No pass in exir/passes/remove_noop_pass.py removes one.
    • Why it matters here: the mm branch at lines 162-169 has the same gap, and main has the same check, so this is not a regression. But the PR makes the helper the documented rule ("Returns whether linear(x, w, b) can replace addmm(b, x, w.t())"), and Samsung's partitioner now relies on it (enn_partitioner.py:92-95).
    • Fix: accept a permute_copy only when its dims, taken modulo 2, are [1, 0], and use the same check in the mm branch. Fix this →

Recommendation

Approve

Nothing blocks approval. The finding above predates the PR, so it can be fixed here or in a separate PR.

Review steps

  • Get the PR diff and context
  • Run 3 independent reviewers
  • Merge their findings (7 candidates; 2 were reported by all 3 reviewers)
  • Fact-check the findings: 1 kept, 6 dropped. The dropped ones:
    • Vulkan's permute check (all 3 reviewers). is_linear_permute still returns before the permute's own op checks (vulkan_partitioner.py:325-327), on the assumption that the permute fuses into a linear. That is true. But the author already tried the suggested change and got the same graph and outputs. The only new point is that t_copy is texture-only (op_registry.py:1524-1529). A default to_edge graph has a permute_copy there instead, which takes any storage (:1253-1260).
    • Vulkan's quantized fusion (all 3 reviewers). QuantizedLinearMatch traces the weight through the permute and the dequantize, and never reads beta or alpha (quantized_linear.py:49-68). Main drops the scales the same way, and the description already limits the Vulkan fix to float weights.
    • Vulkan speed. Vulkan now transposes the weight on every run for a 2-D bias that it already handled. The description says this.
    • Samsung's t_copy weight. Samsung may take an addmm whose t_copy weight ends up outside the partition. This was not confirmed. A default edge graph has a permute_copy there, and ENN has a builder for it.
    • A [1] bias. The helper accepts a [1] bias when N > 1, which ENN's or Vulkan's linear may misread. Main converts it the same way, and those kernels were not checked.
    • The Vulkan test in CI. The new Vulkan test does not run in CI. The description says this.
  • Post the review

Not checked:

  • No tests or scripts were run, because this environment does not allow running Python.
  • Nothing was run on Vulkan or with the ENN SDK.

AddmmToLinearTransform turns addmm(bias, x, w.t()) into
linear(x, w, bias). But addmm also takes beta and alpha, and computes
beta * bias + alpha * (x @ w.t()). The transform dropped both, so
torch.addmm(b, x, w.t(), beta=2.0) returned x @ w.t() + b instead of
x @ w.t() + 2 * b.

A linear cannot scale its bias or its product, so an addmm whose beta or
alpha is not 1 now stays an addmm. A new helper, addmm_can_be_linear,
holds the whole rule, including the existing check that the weight is a
t_copy or permute_copy. Vulkan's addmm applies beta and alpha. A new
Vulkan test lowers a scaled addmm and compares it with eager. On
SwiftShader it passes at this commit, and before it the output was off
by up to 3.5. CI does not run this test.

ENN has no addmm. The Samsung partitioner took every addmm, because
preprocess runs this transform. But preprocess failed the whole lowering
with "aten.addmm.default is not supported in ENN Delegate" for any addmm
the transform left alone.

The partitioner now takes an addmm of constants, which preprocess folds
away. Otherwise it takes an addmm only when addmm_can_be_linear allows
it and its weight is not constant. A constant weight is left out because
ConstantPropPass runs before the transform and folds its transpose. The
rest runs on the CPU.

The partitioner needs the ENN SDK to import. So it was checked only with
the native wrapper modules stubbed. A scaled addmm, a standalone
addmm(b, x, w) and an addmm of a transposed constant weight are now left
out. An addmm of a transposed runtime weight and an addmm of constants
are still taken. Running the transform before ConstantPropPass would let
ENN take the constant weight case. That needs the ENN SDK to verify, so
it is left to the Samsung maintainers.
addmm takes any bias that broadcasts to the output, for example [1, N],
[M, N], [M, 1] or a 0-D tensor. AddmmToLinearTransform turned such an
addmm into a linear with the same bias, but ExecuTorch's linear kernel
takes only a 1-D bias. So a torch.addmm that stays outside a delegate
and then goes through this transform, as the LLM export does with
ConvertToLinearPass, failed at run time with "Bias has wrong
dimensionality".

addmm_can_be_linear now also requires a 1-D bias, so such an addmm stays
an addmm and runs with the addmm kernel, and the Samsung partitioner
leaves it to the CPU. Vulkan's linear already handled [1, N], [M, N] and
[M, 1] biases. There such an addmm now runs as an addmm, which
transposes the weight on every run instead of packing it once. The
Vulkan addmm test gains an [M, N] bias case, which matches eager on
SwiftShader before and after this change. An F.linear with such a bias
is still turned into a linear by ConvertToLinearPass's own source-
partition step, which this change does not touch.
When a linear reads a dequantized tensor through views,
AddmmToLinearTransform can point the linear at the dequantized tensor
so that the view after the linear goes. A linear kept from export, for
example one a partitioner keeps whole, can have a bias of more than 1
dim that follows the rows of the flattened input, such as [M, N] or
[M, 1]. Such a bias does not broadcast to the dequantized shape, so with
a [6, 16] bias the program failed to run.

The transform now leaves a linear with such a bias reading its
flattened input, and keeps the view after it. This includes the
flattened input used as the bias. That case gave right results before,
but only because replace_input_with replaced the bias too. It now keeps
its views like any other bias of more than 1 dim.
When a linear reads a dequantized tensor through views,
AddmmToLinearTransform can point the linear at the dequantized tensor
so that the view after the linear goes. It did that with
replace_input_with, which replaces every argument that is the input
node. For flat @ flat.t() the weight is the same node as the input, so
the weight also became the 3-D dequantized tensor, and the program
failed to run.

The rewire now replaces only the input argument.
The docstring of replace_linear_view_copy_input_output still described
only the original pattern. It now says when the view after a linear
goes, when the linear reads the dequantized tensor instead of its
flattened input, and that with dynamic shapes the linear's input and
the view need symbolic shapes in meta["val"].

A new test case, for coverage only, checks that a linear whose output
has another reader besides the view keeps its input and its view.
addmm computes beta * bias + alpha * (x @ w). XNNPACK lowers it to a
fully connected op, which has no such scales, and the lowering dropped
them. So torch.addmm(b, x, w, beta=2.0) ran as x @ w + b inside the
XNNPACK delegate, with wrong values.

The XNNPACK partitioner now leaves such an addmm out of the delegate, as
it already does for an add whose alpha is not 1, so the addmm runs with
the portable kernels and gives the right values.
addmm adds a bias that can be any tensor that broadcasts to the output,
for example a full [M, N] matrix, or a single value when N > 1. XNNPACK
lowers addmm to a fully connected op, which reads exactly 1 bias value
per output channel. So an addmm with such a bias ran inside the XNNPACK
delegate with wrong values. This also happened for a bias that is a
program input, which force_non_static_weights_for_f32_linear lets in.

The XNNPACK partitioner now takes an addmm only when its bias holds
exactly N values, 1 per output channel: [N] or [1, N], or a single value
when N is 1. A bias whose size is not known when lowering is kept out as
well, and checking it does not fail the lowering. Any other addmm stays
out of the delegate and runs with the portable kernels. The check skips
mm, which inherits this config but has no bias argument; a new mm test
checks that mm is still delegated. Another test covers an F.linear
that to_edge decomposes into addmm(bias, x, weight.t()), which XNNPACK
takes through the linear source partition.
AddmmToLinearTransform turns addmm(b, x, w.t()) and mm(x, w.t()) into a
linear of w. It took any permute_copy as the transpose, but
permute_copy(w, [0, 1]) leaves w as it is. So
torch.addmm(b, x, w.permute(0, 1)) and x @ w.permute(0, 1) became
linears of w, which multiply by w.t() instead of w. With a square w the
values were wrong. With any other w the transform failed. XNNPACK's
ConvertToLinearPass, Samsung and Vulkan all use this transform, and the
LLM export runs ConvertToLinearPass too. On Vulkan with SwiftShader, the
addmm and the mm were off by up to 14.4, on main and on the parent
commit.

A new helper, is_transpose, accepts t_copy and a permute_copy whose dims
are [1, 0], also when written as negative dims. addmm_can_be_linear and
the mm branch both use it, so any other permute stays as it is. The
Samsung partitioner uses addmm_can_be_linear, so it now also leaves such
an addmm to the CPU when its weight is not a constant. On Vulkan the
same programs now match eager.

Vulkan's partitioner still treats such a permute as part of a linear and
skips its checks for it. The permute then runs as its own op. With a
check there, the graph and the outputs stay the same.
@shoumikhin
shoumikhin force-pushed the addmm-scales-and-bias branch from 2198156 to 4db2d9e Compare November 5, 2026 16:32
Copilot AI balanced review requested due to automatic review settings November 5, 2026 16:32
@shoumikhin shoumikhin changed the title Fix addmm lowering when beta or alpha is not 1, or the bias is not 1-D Fix addmm and mm lowering for scales, bias shapes and identity permutes Nov 5, 2026
@shoumikhin

Copy link
Copy Markdown
Contributor Author

The identity permute is fixed in this push. A new helper, is_transpose, accepts t_copy and a permute_copy with dims [1, 0], including negative dims. addmm_can_be_linear and the mm branch both use it.

A new test runs addmm and mm with a [0, 1], [1, 0] and [-1, -2] permute of a square weight, and with a t_copy. It checks that only the real transposes become linears, and that every output matches eager. The [0, 1] cases fail without the fix. With a non-square weight the transform used to fail, and now it keeps the op.

On Vulkan with SwiftShader, the addmm and mm with a [0, 1] permute were off by up to 14.4 before, and now match. Samsung now leaves such an addmm with a non-constant weight to the CPU through the same helper. With a constant weight it already did.

About the bias drop from the previous review (an F.linear with a 2-D bias on a 3-D or 4-D input): it is not in this PR. It lives in XNNPACK's ConvertToLinearPass and AddmmConfig's source-partition path, not in this transform, and it needs its own tests, so it will get its own PR.

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 5, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 20m 18s —— View job


Approve: the reviewers found no blocker or major problem; the 1 minor finding is that the new Vulkan test does not cover the [0, 1] permute that the latest push fixes.

Full review

PR Review: #24658

Summary

The PR makes an addmm or mm into a linear only when its weight is really transposed, its beta and alpha are 1 and its bias is 1-D. It also keeps the addmms that XNNPACK and Samsung cannot run out of those delegates.

  • No blocker or major problem was found.
  • There is 1 minor problem, in a test.
  • All 6 changed files were reviewed.
  • Nothing was run, so the finding comes from reading the code.

Testing

  • Minor: the new Vulkan test does not cover the [0, 1] permute or mm (backends/vulkan/test/test_vulkan_delegate.py:866-889). All 3 reviewers reported this.
    • What the test covers: test_vulkan_backend_addmm runs only addmm(b, x, w.t()), with the scales and an [8] or [4, 8] bias.
    • What it misses: the latest push fixes an addmm and an mm whose weight goes through a [0, 1] permute. You measured these on SwiftShader as off by up to 14.4 on main. That Vulkan result was checked only by hand.
    • Why the transform test is not enough: test_only_a_transposed_weight_becomes_a_linear_weight covers the graph change, but it compares the transformed program with eager on the CPU, not with the Vulkan output.
    • Limit: CI does not run this Vulkan test, so the new cases only help the SwiftShader run.
    • Fix: add subtests for torch.addmm(b, x, w.permute(0, 1)) and torch.mm(x, w.permute(0, 1)) with a square weight. Fix this →

Recommendation

Approve

Nothing blocks approval. The Testing item is small, so it can go in this PR or a later one.

Review steps

  • Get the PR diff and context
  • Run 3 independent reviewers
  • Merge their findings (7 candidates; 1 was reported by all 3 reviewers, and 3 by 2 of them)
  • Fact-check the findings: 1 kept, 6 dropped. The dropped ones:
    • The 1-D bias rule in a shared transform (2 reviewers). The rule comes from the CPU linear.out kernel. Vulkan's linear also takes a 2-D bias, so on Vulkan such an addmm now transposes its weight on every run. That only costs speed, and the description already says so.
    • Samsung's transpose outside the partition (2 reviewers). If the transpose before a delegated addmm stayed on the CPU, preprocess would keep the addmm, and ENN has no builder for it. But neither Samsung (enn_partitioner.py:202-219) nor a default to_edge keeps aten.t, so the transpose is a permute_copy, which has an ENN builder (backends/samsung/builders/op_permute.py:18). Main took every addmm, so this is not a regression.
    • No Samsung test (2 reviewers). You explained that a test needs the ENN SDK. The existing tests in backends/samsung/test/ops/ need it too, and CI runs only backends/samsung/test/models.
    • A [1] bias when N > 1 (1 reviewer). addmm_can_be_linear accepts it, and Vulkan or ENN might misread it. No misread was shown: Vulkan passes the bias sizes to its shader (backends/vulkan/runtime/graph/ops/impl/gemm/linear/Linear.cpp:120), and main converts the same addmm.
    • Vulkan's is_linear_permute (1 reviewer). It still skips the permute's own checks, because it assumes the permute fuses into a linear. You already tried that change and got the same graph and outputs. Vulkan does not keep aten.t, so the weight is a permute_copy.
    • No non-square [0, 1] case in the transform test (1 reviewer). The square case runs the same is_transpose check and fails without the fix.
  • Post the review

Not checked:

  • No tests or scripts were run, because running Python needs approval in this environment.
  • Nothing was run on Vulkan or with the ENN SDK.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

Thanks. That is right: test_vulkan_backend_addmm does not have a [0, 1] permute case or an mm case.

The [0, 1] fix is in the shared transform, and test_only_a_transposed_weight_becomes_a_linear_weight covers it for both addmm and mm. That test runs in CI and fails without the fix. The Vulkan test does not run in CI, so [0, 1] subtests there would only help a local Vulkan run, which is how I checked the Vulkan result by hand. So I'll leave them out of this PR.

@shoumikhin
shoumikhin merged commit 88aeb96 into pytorch:main Nov 5, 2026
JakeStevens added a commit to JakeStevens/executorch that referenced this pull request Nov 10, 2026
pytorch#24658 made the XNNPACK partitioner reject an addmm whose alpha or beta is
not 1, and made the addmm-to-linear transform keep such an addmm. These
tests also cover ConvertToLinearPass, which the LLM export builder runs on
the whole program, and beta=0, which makes addmm ignore its input.
ConvertToLinearPass keeps an addmm with a transposed weight and alpha or
beta, and still turns the default one into a linear. The partitioner leaves
an addmm with only alpha, only beta, or beta=0 on portable.

This change was authored with Claude Code.
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: xnnpack Changes to the XNNPack backend delegate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants