Skip to content

[PT2E][X86] Fall back to plain linear annotation for reused nn.Linear with fusable post op - #4480

Merged
Xia-Weiwen merged 2 commits into
pytorch:mainfrom
waynehacking8:fix-4478-reused-linear-fusion
Jun 15, 2026
Merged

Xia-Weiwen merged 2 commits into
pytorch:mainfrom
waynehacking8:fix-4478-reused-linear-fusion

Conversation

@waynehacking8

@waynehacking8 waynehacking8 commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #4478

Problem

prepare_pt2e with X86InductorQuantizer raises a ValueError whenever a single nn.Linear module has multiple call sites in the exported graph (e.g. it is called inside an unrolled loop — common for unrolled sampling loops of diffusion / flow-matching models) and any call site is followed by a fusable add/relu:

ValueError: Input partition has more than one output node          # linear + add
ValueError: Linear partition cannot have more than one output node # linear + relu

Root cause: under non-strict export (the current torch.export.export default), get_source_partitions groups all call sites of one module instance into a single SourcePartition, so the partition has one output node per call site. The linear fusion annotation passes (_annotate_linear_unary, _annotate_linear_binary_unary via _get_output_nodes_of_partitions) assume exactly one output node and raise, aborting quantization of the whole model. (Under strict=True each call site gets its own partition, which is why existing tests never hit this.)

Fix

  • _annotate_linear_unary / _annotate_linear_binary_unary: skip fused partition candidates where any partition has more than one output node (same continue style as the other pattern checks in this file) instead of raising.
  • _annotate_linear: annotate each linear call site (output node) of a partition instead of raising on multi-output partitions, so the skipped call sites still get plain (non-fused) linear annotation.

Behavior change: a reused linear with a fusable neighbor is now quantized without fusion (input q/dq per call site, per-channel weight dq per call site) instead of crashing prepare_pt2e. Fusion behavior for single-call-site modules is unchanged.

Note: the conv fusion paths share the same single-call-site assumption and would crash the same way for a reused conv; this PR is scoped to the linear paths reported in the issue, and I'm happy to extend to conv in a follow-up if desired.

Before / after

Minimal repro from the issue (x = x + self.projection(x) twice with one shared nn.Linear):

  • Before: ValueError: Input partition has more than one output node (and the relu variant fails with Linear partition cannot have more than one output node)
  • After: prepare_pt2e / convert_pt2e succeed; converted graph contains 2 quantized linear call sites (2 input q/dq pairs, 2 per-channel weight dq)

Test

  • Added TestHelperModules.SharedLinearModule and test_linear_reused_with_fusable_post_op in test/quantization/pt2e/test_x86inductor_quantizer.py, covering both add and relu post ops. The test checks node occurrence and annotation statistics (both call sites annotated as plain quantized linears, post ops unannotated).
  • _test_quantizer gained a strict parameter (default True, all existing callers unchanged); the new test uses strict=False since only non-strict export produces multi-output partitions.
  • The new test fails with the exact ValueErrors from the issue without the source change and passes with it.
  • Full test/quantization/pt2e/test_x86inductor_quantizer.py: 51 passed (CPU, torch 2.12).
  • ruff check / ruff format (0.11.6, per pre-commit) clean.

Note on export mode: this targets the default (non-strict) torch.export.export path. PT2E docs never pass strict= (all use torch.export.export(m, example_inputs).module()), and recent PyTorch defaults export to non-strict — so the documented happy path for any model that reuses an nn.Linear in a loop hits this crash. The prior tests only avoided it because _test_quantizer hard-codes strict=True.


This PR was written with the assistance of Claude (AI); I have reviewed and validated all changes.

Generated with Claude Code

… with fusable post op

Fixes pytorch#4478

Under non-strict export, get_source_partitions groups all call sites of a
reused nn.Linear module into a single SourcePartition with one output node
per call site. The linear fusion annotation passes assumed a single output
node and raised ValueError, aborting prepare_pt2e for the whole model
whenever any call site was followed by a fusable add/relu.

- _annotate_linear_unary / _annotate_linear_binary_unary: skip fused
  partition candidates where any partition has more than one output node
  instead of raising.
- _annotate_linear: annotate every linear call site (output node) of a
  partition instead of raising on multi-output partitions.

Reused linear call sites are now quantized without fusion; fusion behavior
for single-call-site modules is unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
@pytorch-bot

pytorch-bot Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/ao/4480

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ You can merge normally! (2 Unrelated Failures)

As of commit 0b35d4d with merge base c42673d (image):

FLAKY - The following job failed but was likely due to flakiness present on trunk:

BROKEN TRUNK - The following job failed but was present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla

meta-cla Bot commented Jun 12, 2026

Copy link
Copy Markdown

Hi @waynehacking8!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@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 Jun 13, 2026
@meta-cla

meta-cla Bot commented Jun 13, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@Xia-Weiwen

Copy link
Copy Markdown
Collaborator

@claude review this. And also check: is strict=True of torch.export.export required for PT2E quantization in the documents?

@claude

claude Bot commented Jun 13, 2026 •

Copy link
Copy Markdown

Claude finished @Xia-Weiwen's task in 4m 27s —— View job


Code Review

  • Read the changed source file (x86_inductor_quantizer.py)
  • Read the changed test file
  • Review correctness of the fix
  • Investigate: is strict=True required for PT2E quantization in the docs?
  • Post review + answer

Summary

The fix is correct and well-scoped. The root-cause analysis is accurate: under non-strict export, get_source_partitions collapses all call sites of one reused nn.Linear into a single SourcePartition with one output node per call site, and the linear annotation paths assumed exactly one output node. The two-part fix (skip multi-output partitions in the fusion paths, iterate output nodes in _annotate_linear) is consistent with the existing continue idiom in this file.

Correctness

_annotate_linear (plain path) — x86_inductor_quantizer.py:1443-1457: iterating partition.output_nodes and annotating each call site is right. The _skip_annotate([linear_node], filter_fn) per-node check works correctly with both the module-name and operator-type filters.

_annotate_linear_unary / _annotate_linear_binary_unary guards — :1477 and :1521: the any(len(p.output_nodes) > 1 ...) early-continue is placed before _get_output_nodes_of_partitions, so the remaining ValueError("Input partition has more than one output node") raise in that helper (:646) can no longer be hit by linear. Good defensive ordering.

No issues with the core logic. The behavior change (reused linear + fusable neighbor → quantized without fusion) is reasonable and clearly documented.

Suggestions (non-blocking)

  1. The relu test case doesn't actually exercise the _annotate_linear_unary guard. The test model uses functional torch.relu(self.linear(x)), but _annotate_linear_unary only matches module post-ops (torch.nn.ReLU, LeakyReLU, Tanh, GELU) via find_sequential_partitions(gm, [torch.nn.Linear, postop]). A functional torch.relu never forms a [Linear, ReLU] partition, so the relu case only hits the _annotate_linear fix — it crashed via "Linear partition cannot have more than one output node", not the unary fusion path. The add case is the one that genuinely covers the _annotate_linear_binary_unary guard.

    Net effect: the new guard in _annotate_linear_unary (:1477) has no test coverage. To close that gap, use an nn.ReLU module in the shared module (e.g. self.act = torch.nn.ReLU() and x = self.act(self.linear(x))) for the relu variant. Fix this →

  2. Conv paths remain unfixed (_annotate_conv2d still raises at :1213, and the conv fusion paths share the assumption). The author already noted this and offered a follow-up — agreed that scoping to linear is fine, but a reused conv will still crash prepare_pt2e with the same class of error. Worth a tracking issue.

  3. Minor: the docstring on SharedLinearModule says "each followed by a fusable post op (add or relu)" — given point Adding gpu quantization workflows and apis #1, the relu form is not actually a fusable (module) post-op from the quantizer's perspective. Consider clarifying.

Answer: Is strict=True required for PT2E in the docs?

No. I searched all of docs/ — no PT2E doc passes strict= at all. Every example uses the default:

  • docs/source/pt2e_quantization/pt2e_quant_x86_inductor.rst:266
  • docs/source/pt2e_quantization/pt2e_quant_ptq.rst:67
  • docs/source/pt2e_quantization/pt2e_quant_qat.rst:38
  • docs/source/pt2e_quantization/pt2e_quant_openvino_inductor.rst:111

i.e. torch.export.export(m, example_inputs).module() with no strict argument. Since recent PyTorch defaults torch.export.export to non-strict, the documented flow is exactly the code path that triggers this bug. This actually strengthens the case for the PR: the crash affects the documented happy path for any model that reuses a linear in a loop, not some exotic opt-in mode. The existing tests only avoided it because _test_quantizer hard-coded strict=True.

Worth noting in the PR description that the fix targets the default export behavior, not an edge case.

Note

I could not run the test suite here — torch is not installable in this environment, so the 51-passing claim and the node_occurrence expectations are unverified on my end. The logic and counts look correct by inspection (2 input q/dq pairs, 2 per-channel weight dq, post-ops unannotated).
• branch fix-4478-reused-linear-fusion

@Xia-Weiwen

Copy link
Copy Markdown
Collaborator

@waynehacking8 Thanks for the fix. Can you please take a look at the comments from claude? Seems the test case needs improvement.

The relu variant of SharedLinearModule used functional torch.relu, which
never forms a [Linear, nn.ReLU] sequential partition, so it only covered
the plain _annotate_linear fallback and left the new multi-output guard in
_annotate_linear_unary untested. Switch to a reused nn.ReLU module so a
[Linear, ReLU] partition forms and the guard is exercised.

Verified coverage: with the guard temporarily removed, the relu case fails
with "Input partition has more than one output node"; with it in place the
test passes. node_occurrence / annotation expectations are unchanged (relu
stays unannotated as the reused linear falls back to plain annotation).

Signed-off-by: Wayne Chiu <[email protected]>
@waynehacking8

Copy link
Copy Markdown
Contributor Author

Thanks @Xia-Weiwen, and thanks @claude for the careful review — both points are addressed in 0b35d4d.

Test coverage fix (claude's point #1). You're right that the relu variant used functional torch.relu, which never forms a [Linear, nn.ReLU] partition, so it only hit the plain _annotate_linear fallback and left the new _annotate_linear_unary guard untested. SharedLinearModule now uses a reused nn.ReLU module, so a [Linear, ReLU] sequential partition forms and the guard at _annotate_linear_unary is exercised.

I verified the coverage is real, not just that the test still passes: with the _annotate_linear_unary multi-output guard temporarily removed, the relu case fails with ValueError: Input partition has more than one output node; with the guard in place it passes. The node_occurrence / annotation-stat expectations are unchanged (the reused linear still falls back to plain annotation, relu stays unannotated). I also tightened the SharedLinearModule docstring to make the module-vs-functional distinction explicit (claude's point #3).

strict=True for PT2E (your question + claude's answer). Confirmed: strict=True is not required and isn't used anywhere in the PT2E docs — every example (pt2e_quant_x86_inductor.rst:266, pt2e_quant_ptq.rst:67, pt2e_quant_qat.rst:38, pt2e_quant_openvino_inductor.rst:111) calls torch.export.export(m, example_inputs).module() with the default. Since torch.export.export now defaults to non-strict, the documented happy path is exactly the code path this bug hits — the existing tests only avoided it because _test_quantizer hard-codes strict=True. I'll note in the PR description that the fix targets the default (non-strict) export behavior, not an opt-in edge case.

Conv paths (claude's point #2). Agreed the conv annotation paths share the same single-output assumption (_annotate_conv2d raises at the same class of error for a reused conv). I scoped this PR to linear deliberately; happy to open a tracking issue and follow up with the conv fix in a separate PR.

@waynehacking8

Copy link
Copy Markdown
Contributor Author

Opened the conv follow-up as #4482 (stacked on this branch, since its test needs the strict=False helper param here). It mirrors this fix across _annotate_conv2d + the three conv fusion paths, with the same coverage-proof approach. Happy to fold it into this PR instead if you'd prefer a single "reused nn.Linear/nn.Conv2d" change — just let me know.

@Xia-Weiwen

Copy link
Copy Markdown
Collaborator

@claude review again

@claude

claude Bot commented Jun 13, 2026 •

Copy link
Copy Markdown

Claude finished @Xia-Weiwen's task in 56s —— View job


Re-review

  • Read the latest changed source file (x86_inductor_quantizer.py)
  • Read the latest test file & verify claude's point Adding gpu quantization workflows and apis #1 (relu now uses an nn.ReLU module) is addressed
  • Verify the _annotate_linear_unary guard is now exercised
  • Post review

Summary

The follow-up commit (0b35d4d) addresses my earlier review points. LGTM. The fix is correct, well-scoped, and now properly tested.

What changed since the last review

Point #1 — _annotate_linear_unary guard now has coverage. SharedLinearModule was switched from functional torch.relu to a reused nn.ReLU module (test_x86inductor_quantizer.py:483, used at :493). With the module form, find_sequential_partitions(gm, [torch.nn.Linear, torch.nn.ReLU]) now actually forms a [Linear, ReLU] partition, so the multi-output guard at x86_inductor_quantizer.py:1477 is exercised in the relu case. The author also confirmed the coverage is real by temporarily removing the guard and observing the exact ValueError: Input partition has more than one output node — that's the right way to prove a guard is tested, not just that the test passes.

Point #3 — docstring clarified. The SharedLinearModule docstring now explicitly distinguishes the add case (covers _annotate_linear_binary_unary) from the relu case (uses an nn.ReLU module to cover _annotate_linear_unary), and notes the module-vs-functional distinction. Clear and accurate.

Point #2 — conv paths. Tracked as a follow-up in #4482, stacked on this branch. Agreed this PR stays scoped to linear.

Correctness re-check

  • _annotate_linear (:1443-1457): iterating partition.output_nodes and annotating each call site, with the per-node _skip_annotate check, is correct. The non-aten-linear raise is preserved per node.
  • _annotate_linear_unary (:1477) and _annotate_linear_binary_unary (:1521): the any(len(p.output_nodes) > 1 ...) continue is placed before _get_output_nodes_of_partitions, so the legacy ValueError raise in that helper can no longer be reached by the linear paths. Correct ordering.

The node_occurrence / _check_annotation_stat expectations (2 input q/dq pairs, 2 per-channel weight dq, post-ops unannotated, both linear call sites annotated: 2 / is_quant_out: 2) match the documented "quantized without fusion" behavior.

strict=True for PT2E in the docs

Re-confirmed (unchanged from my prior answer): not required, and not used anywhere in the PT2E docs. Every example uses torch.export.export(m, example_inputs).module() with the default — pt2e_quant_x86_inductor.rst:266, pt2e_quant_ptq.rst:67, pt2e_quant_qat.rst:38, pt2e_quant_openvino_inductor.rst:111. Since torch.export.export now defaults to non-strict, the documented happy path is exactly the code path this bug hits; the existing tests only avoided it because _test_quantizer hard-coded strict=True (now parameterized with default True, so existing callers are unchanged).

Note

As before, I could not run the suite here (torch not installable in this environment), so the 51-passing claim and the node counts are verified by inspection only — they look correct.
• branch fix-4478-reused-linear-fusion

@Xia-Weiwen Xia-Weiwen added the module: not user facing Use this tag if you don't want this PR to show up in release notes label Jun 13, 2026

@Xia-Weiwen Xia-Weiwen left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix

@waynehacking8

Copy link
Copy Markdown
Contributor Author

CI note: the failing test_qconv2d_maxpool2d_linear_dynamic_cpu_cpp_wrapper ('quantized::max_pool2d' not found) also fails on clean main (c42673d) with no changes from this PR — i.e. it's pre-existing and unrelated. This PR only touches _annotate_linear / the linear fusion guards; the non-cpp-wrapper variant of that same test passes locally. Verified by running it on a clean main worktree.

@Xia-Weiwen
Xia-Weiwen merged commit 5647df9 into pytorch:main Jun 15, 2026
14 of 17 checks passed
waynehacking8 added a commit to waynehacking8/ao that referenced this pull request Jun 19, 2026
Follow-up to the reused nn.Linear fix (pytorch#4480): the conv annotation paths
share the same single-call-site assumption, so a reused nn.Conv2d (e.g.
called inside an unrolled loop) under non-strict export still crashes
prepare_pt2e with "conv partition has more than one output node" (plain
path) or "Input partition has more than one output node" (fusion paths).

Mirror the linear fix:
- _annotate_conv2d_binary_unary / _annotate_conv2d_binary /
  _annotate_conv2d_unary: skip fusion when any partition has multiple
  output nodes, so the reused conv falls back to plain annotation.
- _annotate_conv2d: iterate partition.output_nodes and annotate each call
  site instead of raising on multi-output partitions.

Adds SharedConvModule and test_conv2d_reused_with_fusable_post_op covering
the unary (relu), binary (add) and binary+unary (add+relu) fusion guards
plus the plain fallback. Verified the coverage is real: reverting the fix
makes the test crash with "more than one output node"; with the fix each
call site is annotated as plain conv and prepare_pt2e succeeds.

Signed-off-by: Wayne Chiu <[email protected]>
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. module: not user facing Use this tag if you don't want this PR to show up in release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

X86InductorQuantizer fusion annotation crashes when one nn.Linear has multiple call sites (unrolled loops, reused modules)

2 participants