Skip to content

Only fuse a ReLU whose zero point is the quantization minimum (#25308) - #25308

Open
apullin wants to merge 1 commit into
pytorch:mainfrom
apullin:export-D128386182
Open

apullin wants to merge 1 commit into
pytorch:mainfrom
apullin:export-D128386182

Conversation

@apullin

@apullin apullin commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

FuseQuantizedActivationPass removes a ReLU, or a hardtanh with a 0 lower bound, that follows a conv or a linear. Since #21974 it also does this when the activation's output zero point is above qmin, and sets the following quantize op's qmin to the zero point, which keeps the quantized model clamping at 0. The TOSA lowering drops that clamp: RewriteConvPass lowers the conv's output to a RESCALE, which saturates only at the int8 range. So negative values passed the removed ReLU whenever its output zero point was above -128, which happens when the ReLU's output shares its qparams with negative values. For torch.cat([y, torch.relu(conv(x))]) the TOSA graph was CONV2D -> RESCALE (zero point -3) -> CONCAT, without any clamp.

The pass again fuses only activations whose output zero point is qmin, as before #21974, so the RESCALE's saturation is the clamp. CheckProperQuantization now checks whether a conv or linear and its following 0-lower-bound activation are quantized together (_is_quantized_activation) separately from whether the activation can be erased (_is_fuseable_quantized_activation), so unfused pairs stay delegated instead of falling back to CPU, and FuseQuantizedActivationPass inserts the intermediate Q -> DQ pair on the quantized producer when the activation stays so both conv and linear lower cleanly with CLAMP.

Differential Revision: D128386182

@pytorch-bot

pytorch-bot Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ No Failures, 138 Pending

As of commit 8f4a6b6 with merge base 78e83b9 (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 19, 2026
@meta-codesync

meta-codesync Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

@apullin has exported this pull request. If you are a Meta employee, you can view the originating Diff in D128386182.

@github-actions github-actions Bot added ciflow/trunk-arm module: arm Issues related to arm backend labels Nov 19, 2026
@github-actions

Copy link
Copy Markdown

This PR needs a release notes: label

If your change should be included in the release notes (i.e. would users of this library care about this change?), please use a label starting with release notes:. This helps us keep track and include your important work in the next release notes.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "release notes: none"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@meta-codesync meta-codesync Bot changed the title Only fuse a ReLU whose zero point is the quantization minimum Only fuse a ReLU whose zero point is the quantization minimum (#25308) Nov 19, 2026
apullin added a commit to apullin/executorch that referenced this pull request Nov 19, 2026
…h#25308)

Summary:

`FuseQuantizedActivationPass` removes a ReLU, or a hardtanh with a 0 lower bound, that follows a conv or a linear. Since pytorch#21974 it also does this when the activation's output zero point is above qmin, and sets the following quantize op's qmin to the zero point, which keeps the quantized model clamping at 0. The TOSA lowering drops that clamp: `RewriteConvPass` lowers the conv's output to a RESCALE, which saturates only at the int8 range. So negative values passed the removed ReLU whenever its output zero point was above -128, which happens when the ReLU's output shares its qparams with negative values. For `torch.cat([y, torch.relu(conv(x))])` the TOSA graph was `CONV2D -> RESCALE (zero point -3) -> CONCAT`, without any clamp.

The pass again fuses only activations whose output zero point is qmin, as before pytorch#21974, so the RESCALE's saturation is the clamp. Other ReLUs stay, and are lowered as clamps.

The unit tests that expected fusion with a zero point above qmin now use a zero point of -128, or expect no fusion, and `test_relu_with_zero_point_above_qmin_tosa_INT` lowers `torch.cat([y, torch.relu(conv(x))])` for TOSA INT and compares the outputs.

Differential Revision: D128386182
@zingo zingo added the partner: arm For backend delegation, kernels, demo, etc. from the 3rd-party partner, Arm label Nov 19, 2026
@rascani
rascani requested a review from zingo November 20, 2026 18:35
@gggekov

gggekov commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

Hi @apullin ,
Thank you for the PR and apologies for the delay in coming back to you!

For your

class ConvReluCat(torch.nn.Module):
    """The ReLU output shares its qparams with negative values in the
    concatenation, so its zero point is above qmin.
    """
    def __init__(self) -> None:
        super().__init__()
        self.conv = torch.nn.Conv2d(4, 4, 1)
    def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
        return torch.cat([y, torch.relu(self.conv(x))])

model with the change in backends/arm/_passes/fuse_quantized_activation_pass.py, it seems like only the CONCAT is delegated and the conv_2d and relu are ran on CPU. I doubt that is expected ? Can you please make sure the full model remains delegated ? Also, could you add a unit test checking the model is delegated using the TosaPipelineINT to make sure you exercise the full lowering pipeline(quantisation, delegation + all passes). Have a look in https://github.com/pytorch/executorch/blob/main/backends/arm/test/misc/test_conv_relu_residual_add.py for inspiration for the unit test(perhaps you can even add a test case to that file)

apullin added a commit to apullin/executorch that referenced this pull request Dec 2, 2026
…h#25308)

Summary:

`FuseQuantizedActivationPass` removes a ReLU, or a hardtanh with a 0 lower bound, that follows a conv or a linear. Since pytorch#21974 it also does this when the activation's output zero point is above `qmin`, and sets the following quantize op's `qmin` to the zero point, which keeps the quantized model clamping at 0. The TOSA lowering drops that clamp: `RewriteConvPass` lowers the conv's output to a `RESCALE`, which saturates only at the `int8` range. So negative values passed the removed ReLU whenever its output zero point was above -128, which happens when the ReLU's output shares its qparams with negative values. For `torch.cat([y, torch.relu(conv(x))])` the TOSA graph was `CONV2D -> RESCALE (zero point -3) -> CONCAT`, without any clamp.

The pass again fuses only activations whose output zero point is `qmin`, as before pytorch#21974, so the `RESCALE`'s saturation is the clamp. `CheckProperQuantization` now checks whether a `conv` or `linear` and its following 0-lower-bound activation are quantized together (`_is_quantized_activation`) separately from whether the activation can be erased (`_is_fuseable_quantized_activation`), so unfused pairs stay delegated instead of falling back to CPU, and `FuseQuantizedActivationPass` inserts the intermediate `Q -> DQ` pair on the quantized producer when the activation stays so both `conv` and `linear` lower cleanly with `CLAMP`.

Differential Revision: D128386182
@apullin

apullin commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@gggekov Cleaned up now. And rebased.

This was pulled out of a much larger stack bugfind/fix stack where the test passed exir_op=[] to TosaPipelineINT, so CONCAT alone satisfied the single-delegate check while conv2d and relu fell back to CPU.

quantization_annotator annotates conv/linear + relu/hardtanh without an intermediate Q -> DQ, and CheckProperQuantization was reusing FuseQuantizedActivationPass._is_fuseable_quantized_activation to decide whether that pair is quantized for partitioning.
So returning False when zp != qmin caused TOSAPartitioner to reject both ops.

Updated and rebased the PR to:

  • Split _is_quantized_activation (used by CheckProperQuantization) from _is_fuseable_quantized_activation, and insert the intermediate Q -> DQ on the quantized producer when the activation stays unfused so both conv and linear lower inside the delegate (CONV2D -> RESCALE -> CLAMP -> CONCAT).
  • Check full delegation (exir_op CPU-fallback checks + count_tosa_ops) in TosaPipelineINT and add ConvReluCat test cases to backends/arm/test/misc/test_conv_relu_residual_add.py.

@gggekov

gggekov commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator

@claude review this

@claude

claude Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Claude finished @gggekov's task in 3m 43s —— View job


The fix looks correct and nothing blocks merging, but test coverage has gaps: int16 (a16w8) models now always take the new CLAMP path and no test covers it, and the new end-to-end test should be parametrized.

Detailed review

PR Review: #25308

Summary

The PR stops FuseQuantizedActivationPass from removing a ReLU or a 0-min hardtanh unless the output zero point equals qmin. When the activation is kept, it inserts a Q -> DQ pair after the conv/linear, and it splits the partitioner check so these pairs stay delegated. The core fix is correct: the clamp is no longer silently dropped. The remaining issues are a design question, test gaps and a few minor details.

Code Quality

  • The partitioner and the pass test "quantized producer" differently (backends/arm/operator_support/tosa_supported_operators.py:1213-1221 vs backends/arm/_passes/fuse_quantized_activation_pass.py:76-81). The partitioner accepts the activation if every conv/linear input is a DQ node or has an integer dtype. _has_quantized_producer only accepts is_foldable (Arm annotation meta present) or all inputs being DQ.
    • Failure case: a conv/linear with an integer input that has no DQ and no Arm annotation, followed by an activation with zp > qmin. The partitioner delegates both ops, but the pass neither fuses nor inserts Q -> DQ. The conv then reaches RewriteConvPass with no output_qparams.
    • This is unlikely with the Arm quantizer flow, so it is low confidence. One shared helper used by both sides would remove the drift.
  • RewriteConvPass._get_effective_output_qparams has a mostly dead branch (backends/arm/_passes/rewrite_conv_pass.py:427-455). Its clamp branch and its docstring ("If that activation is not fuseable, it survives as a quantized clamp and still owns the branch output qparams") describe the situation this PR removes: an unfused activation now always gets an explicit Q -> DQ on the producer. Either delete the branch or update the docstring to say which case still needs it.
  • The inserted Q, DQ and conv share one meta dict (fuse_quantized_activation_pass.py:104-109). insert_q_dq_pair does q.meta = anchor.meta; dq.meta = q.meta (arm_pass_utils.py:234,242), so the new Q's meta["val"] is the conv's float fake tensor.
    • This is harmless today because FoldAndAnnotateQParamsPass removes the pair.
    • This is the first time the helper runs before folding, though. Roughly ten passes run between FuseQuantizedActivationPass and FoldAndAnnotateQParamsPass, some of them clamp-related. If any of them reads or writes Q/DQ meta, it would also change the conv's meta. Consider copying the meta instead of aliasing it.
  • Dead per-channel check (fuse_quantized_activation_pass.py:44-45). After the quant_node.target != QUANT_PER_TENSOR_OP early return, quant_args.per_channel is always False, so this is effectively return True.

Testing

  • No int16 coverage.
    • Why it matters: with symmetric int16 activations, zp=0 while qmin=-32767/-32768, so zp != qmin always holds. Every a16w8 conv/linear + ReLU now stops fusing and takes the new Q -> DQ + CLAMP path. That is probably the most common real trigger for this code.
    • The old behaviour had the same leak for int16, so the change in behaviour is right. But no test checks that int16 output (including the INT48-bias RESCALE path) is numerically correct, or that it lowers on U55/U85.
  • test_relu_with_zero_point_above_qmin_tosa_INT loops instead of parametrizing (backends/arm/test/passes/test_fuse_quantized_activation_pass.py:279-304).
    • It loops over three models inside one test rather than using common.parametrize like the rest of the suite, so the first failure hides the others.
    • It only uses the default per-channel setting.
    • Its ConvReluCat case duplicates misc/test_conv_relu_residual_add.py::test_conv_relu_cat_tosa_INT, and ConvReluCat is defined in both files.
  • The hardtanh max check is never what decides the result (test_fuse_quantized_activation_pass.py:316-324).
    • test_hardtanh_with_non_saturating_max_is_not_fuseable uses the helper's default zp (not -128), so the new zp != qmin early return rejects it before the max check at lines 60-62 runs.
    • Add a zp == qmin case with a non-saturating max.
    • The leftover quant.args[3] == -128 asserts here and in test_relu_with_tensor_qparams_is_not_fuseable no longer test anything, since nothing changes qmin anymore.
  • No end-to-end fused case. Nothing checks that a ReLU with zp == qmin is still fused and lowers with zero CLAMPs, so a regression that stops fusing altogether would go unnoticed.
  • Missing targets. The new ConvReluCat tests in misc/test_conv_relu_residual_add.py cover TOSA FP/INT and U55. The existing model in that file also has U85, and there is no VGF case (the flow touched in test_rewrite_conv_pass.py).
  • Thin unit test for CheckProperQuantization (backends/arm/test/misc/test_tosa_operator_support.py). It has no linear case and no case where the activation has a non-Q user or more than one user.

Performance

  • Design question: why not honour qmin in the RESCALE? The root cause is that the conv/linear output RESCALE saturates at the dtype range and ignores the qmin in output_qparams. Making RewriteConvPass apply qmin/qmax there would keep the old fusion and avoid an extra CLAMP on every zp > qmin and every int16 conv/linear + ReLU. It would also protect any other producer that relies on a narrowed qmin. Please explain why you inserted Q -> DQ + CLAMP instead.

Recommendation

Needs Discussion. The fix is correct. Before merging, please answer the RESCALE question, since it decides whether the extra CLAMP cost is needed, and add int16 coverage and parametrize the end-to-end test.

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.

Should you not amend the copyright(make the year 2025-2026 and perhaps include the copyright of your company) ?

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.

Also, could you rename the file name to sth test_conv_relu_branch ?

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.

Could you parameterize these so that in case of failure, you see which model fails ?

@gggekov gggekov 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.

Could you also add a test case when quantizing the conv2d to 16x8 as per claude's suggestion ?

…h#25308)

Summary:
Pull Request resolved: pytorch#25308

`FuseQuantizedActivationPass` removes a ReLU, or a hardtanh with a 0 lower bound, that follows a conv or a linear. Since pytorch#21974 it also does this when the activation's output zero point is above `qmin`, and sets the following quantize op's `qmin` to the zero point, which keeps the quantized model clamping at 0. The TOSA lowering drops that clamp: `RewriteConvPass` lowers the conv's output to a `RESCALE`, which saturates only at the `int8` range. So negative values passed the removed ReLU whenever its output zero point was above -128, which happens when the ReLU's output shares its qparams with negative values. For `torch.cat([y, torch.relu(conv(x))])` the TOSA graph was `CONV2D -> RESCALE (zero point -3) -> CONCAT`, without any clamp.

The pass again fuses only activations whose output zero point is `qmin`, as before pytorch#21974, so the `RESCALE`'s saturation is the clamp. `CheckProperQuantization` now checks whether a `conv` or `linear` and its following 0-lower-bound activation are quantized together (`_is_quantized_activation`) separately from whether the activation can be erased (`_is_fuseable_quantized_activation`), so unfused pairs stay delegated instead of falling back to CPU, and `FuseQuantizedActivationPass` inserts the intermediate `Q -> DQ` pair on the quantized producer when the activation stays so both `conv` and `linear` lower cleanly with `CLAMP`.

Differential Revision: D128386182

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

ciflow/trunk-arm CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. meta-exported module: arm Issues related to arm backend partner: arm For backend delegation, kernels, demo, etc. from the 3rd-party partner, Arm

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants