Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion backends/arm/quantizer/arm_quantizer_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,20 @@ def validate(self, model: torch.fx.GraphModule) -> bool: # type: ignore[overrid
return True


# Ops whose second operand contributes only its shape, never its values, so it
# must not be tied into the shared qparams of the first.
_SHAPE_AS_OPS = {
torch.ops.aten.expand_as.default,
torch.ops.aten.view_as.default,
}


# Whether ``node`` shares qparams with its input ``input_node``: always for an
# ordinary shared op, but for a shape-as op only through its data operand.
def _shares_qparams_with(node: Node, input_node: Node) -> bool:
return node.target not in _SHAPE_AS_OPS or input_node is node.args[0]


class SharedQspecQuantizer(Quantizer, QuantizerReporterUser):
"""Assures that specific ops share quantization parameters on all
inputs/outputs.
Expand Down Expand Up @@ -442,6 +456,7 @@ class SharedQspecQuantizer(Quantizer, QuantizerReporterUser):
torch.ops.aten.repeat_interleave.self_int,
torch.ops.aten.expand_copy.default,
torch.ops.aten.expand.default,
torch.ops.aten.expand_as.default,
torch.ops.aten.select.int,
torch.ops.aten.select_copy.int,
torch.ops.aten.slice.Tensor,
Expand Down Expand Up @@ -543,7 +558,11 @@ def _is_annotated(self, node: Node) -> bool:
return Q_ANNOTATION_KEY in node.meta

def _get_input_nodes_with_float_output(self, node: Node) -> list[Node]:
return [n for n in node.all_input_nodes if has_float_output(n)]
return [
n
for n in node.all_input_nodes
if has_float_output(n) and _shares_qparams_with(node, n)
]

def _get_user_nodes_with_float_input(self, node: Node) -> list[Node]:
return [n for n in node.users.keys() if has_float_output(node)]
Expand Down Expand Up @@ -640,6 +659,8 @@ def _get_shared_clique(
shared_nodes.add(node)

for input_node in node.all_input_nodes:
if not _shares_qparams_with(node, input_node):
continue
self._maybe_enqueue_shared_node(input_node, shared_nodes, bfs_queue)
self._append_output_qspec(input_node, adjacent_qspecs)
touches_quantized_io |= self._is_quantized_io_boundary(input_node)
Expand All @@ -648,6 +669,8 @@ def _get_shared_clique(
)

for output_node in node.users.keys():
if not _shares_qparams_with(output_node, node):
continue
self._maybe_enqueue_shared_node(output_node, shared_nodes, bfs_queue)
self._append_input_qspec(output_node, node, adjacent_qspecs)
touches_quantized_io |= self._is_quantized_io_boundary(output_node)
Expand Down
35 changes: 35 additions & 0 deletions backends/arm/test/misc/test_shared_qspecs.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
from executorch.backends.arm.test.tester.test_pipeline import QuantizationPipeline
from executorch.backends.arm.tosa import TosaSpecification
from executorch.backends.cortex_m.test.tester import McuTestCase, ramp_tensor
from torch.export import export
from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e


_QUANT_CONFIG_INT8 = get_symmetric_quantization_config()
Expand Down Expand Up @@ -734,3 +736,36 @@ def test_silu_does_not_share_input_qspec():
)
pipeline.run()
_check_quant_params(pipeline, model.quant_params)


class ShapeAsOperand(torch.nn.Module):
"""``op(x + x, other)`` reads only the shape of ``other``, so its qparams
must stay ``other``'s own rather than join those of ``x + x``.
"""

def __init__(self, op: str) -> None:
super().__init__()
self.op = op

def forward(self, x, y):
other = y + y
return getattr(x + x, self.op)(other) + other


@parametrize(
"test_data",
{"view_as": ("view_as", (2, 16)), "expand_as": ("expand_as", (1, 8))},
)
def test_shape_operand_does_not_share_qspec(test_data):
op, x_shape = test_data
inputs = (ramp_tensor(-1, 1, x_shape), ramp_tensor(-50, 50, (4, 8)))
model = ShapeAsOperand(op).eval()
prepared = prepare_pt2e(export(model, inputs).module(), _get_quantizer())
prepared(*inputs)
quantized = convert_pt2e(prepared)

(node,) = quantized.graph.find_nodes(
op="call_function", target=getattr(torch.ops.aten, op).default
)
data_dequantize, other_dequantize = node.args
assert data_dequantize.args[1] != other_dequantize.args[1]
3 changes: 1 addition & 2 deletions backends/arm/test/models/test_swin2sr_arm.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
]

# TODO/MLETORCH-2163: Investigate Swin2SR delegation gaps around index/view
# in FP and Q/DQ, clamp, and expand_copy in INT.
# in FP and Q/DQ and clamp in INT.
swin2sr_fp_lowered_outer_graph_ops = {
"torch.ops.higher_order.executorch_call_delegate": 2,
"executorch_exir_dialects_edge__ops_aten_index_Tensor": 2,
Expand All @@ -38,7 +38,6 @@
swin2sr_int_lowered_outer_graph_ops = {
"torch.ops.higher_order.executorch_call_delegate": 3,
"executorch_exir_dialects_edge__ops_aten_clamp_default": 4,
"executorch_exir_dialects_edge__ops_aten_expand_copy_default": 4,
"executorch_exir_dialects_edge__ops_quantized_decomposed_dequantize_per_tensor_default": 5,
"executorch_exir_dialects_edge__ops_quantized_decomposed_quantize_per_tensor_default": 5,
}
Expand Down
2 changes: 2 additions & 0 deletions backends/cortex_m/passes/BUCK
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ fbcode_target(_kind = runtime.python_library,
"activation_fusion_pass.py",
"aten_to_cortex_m_pass.py",
"clamp_hardswish_pass.py",
"compute_quantized_constant_ops_pass.py",
"cortex_m_pass.py",
"cortex_m_pass_manager.py",
"decompose_hardswish_pass.py",
Expand All @@ -56,6 +57,7 @@ fbcode_target(_kind = runtime.python_library,
"//executorch/backends/transforms:channels_last_layout",
"//executorch/backends/transforms:channels_last_ops",
"//executorch/backends/transforms:convert_conv1d_to_conv2d_pass",
"//executorch/backends/transforms:postpone_permute_below_squeeze_view",
"//executorch/backends/transforms:remove_getitem_op",
"//executorch/backends/transforms:remove_permutes_around_elementwise_ops",
"//executorch/backends/transforms:remove_unused_constants_pass",
Expand Down
34 changes: 34 additions & 0 deletions backends/cortex_m/passes/compute_quantized_constant_ops_pass.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

import torch
from executorch.backends.arm._passes import ComputeConstantOpsAOTPass
from executorch.exir.dialects._ops import ops as exir_ops


class ComputeQuantizedConstantOpsPass(ComputeConstantOpsAOTPass):
"""Give the quantized constant ops their int8 values.

Folding removes the Q node after these ops but leaves them producing float,
so the int8 kernels they feed would read float data. A ``full`` stays a
runtime fill with its fill value quantized, so it adds no constant data; the
other ops are computed in float and stored as quantized constants. Runs
after ``ConvertFullLikeToFullPass``, so a ``full_like`` arrives as ``full``.
"""

def compute_node_aot(self, node: torch.fx.Node) -> bool:
output_qparams = node.meta.get("output_qparams")
if not output_qparams:
return False
if node.target == exir_ops.edge.aten.full.default:
qparams = output_qparams[0]
fill_value = node.args[1]
assert isinstance(fill_value, (int, float))
fill = qparams.quantize_value(torch.tensor(float(fill_value)))
node.args = (node.args[0], int(fill.item()))
node.kwargs = {**node.kwargs, "dtype": qparams.dtype}
return True
return super().compute_node_aot(node)
9 changes: 9 additions & 0 deletions backends/cortex_m/passes/cortex_m_pass_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import torch
from executorch.backends.arm._passes import (
ConvertFullLikeToFullPass,
DeduplicateGetAttrPass,
FoldAndAnnotateQParamsPass,
ScalarsToAttributePass,
Expand Down Expand Up @@ -48,11 +49,13 @@
from .activation_fusion_pass import ActivationFusionPass
from .aten_to_cortex_m_pass import AtenToCortexMPass
from .clamp_hardswish_pass import ClampHardswishPass
from .compute_quantized_constant_ops_pass import ComputeQuantizedConstantOpsPass
from .decompose_hardswish_pass import DecomposeHardswishPass
from .decompose_mean_pass import DecomposeMeanPass
from .decompose_sdpa_pass import DecomposeSDPAPass
from .explicit_layout_pass import (
CortexMCanonicalizeViewCopyPermutePass,
CortexMPostponeLayoutCopyBelowSqueezePass,
CortexMReplaceOpsWithChannelsLastVariants,
ValidateCortexMExplicitLayoutPass,
)
Expand Down Expand Up @@ -149,6 +152,8 @@ class CortexMPassManager(ExportedProgramPassManager):
FoldAndAnnotateQParamsPass,
ActivationFusionPass,
QuantizedClampActivationPass,
ConvertFullLikeToFullPass,
ComputeQuantizedConstantOpsPass,
DecomposeHardswishPass,
AtenToCortexMPass,
# Retrace only after quantized ATen ops have become Cortex-M kernels.
Expand All @@ -165,10 +170,14 @@ class CortexMPassManager(ExportedProgramPassManager):
ReplaceScalarWithTensorArgPass,
ActivationFusionPass,
QuantizedClampActivationPass,
ConvertFullLikeToFullPass,
ComputeQuantizedConstantOpsPass,
DecomposeHardswishPass,
ConvertConv1dToConv2dPass,
CortexMReplaceOpsWithChannelsLastVariants,
ReplaceSqueezeAndUnsqueezeWithViewPass,
# Let elementwise regions meet layout copies of their own rank.
CortexMPostponeLayoutCopyBelowSqueezePass,
# Move layout copies across pads before singleton permutations become views.
RemovePermutesAroundElementwiseOps,
CortexMCanonicalizeViewCopyPermutePass,
Expand Down
31 changes: 31 additions & 0 deletions backends/cortex_m/passes/explicit_layout_pass.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,16 @@
LAYOUT_PERMUTE_COPY,
PERMUTE_COPY_TARGETS,
)
from executorch.backends.transforms.postpone_permute_below_squeeze_view import (
PostponePermuteOpBelowSqueezeOrUnsqueezeLikeView,
)
from executorch.backends.transforms.replace_ops_with_channels_last_variants import (
ChannelsLastOpSpec,
ReplaceOpsWithChannelsLastVariants,
)
from executorch.exir import ExportedProgram
from executorch.exir.dialects._ops import ops as exir_ops
from executorch.exir.dialects.edge._ops import EdgeOpOverload
from executorch.exir.pass_base import ExportPass, PassResult
from torch.fx import GraphModule, Node
from torch.fx.node import Target
Expand Down Expand Up @@ -117,6 +121,33 @@ def _set_node_op(self, node, target, input_node, arg) -> None:
)


class CortexMPostponeLayoutCopyBelowSqueezePass(
PostponePermuteOpBelowSqueezeOrUnsqueezeLikeView
):
"""Sink a layout copy below a following squeeze, never below an unsqueeze.

Only the layout copies this pipeline inserts are moved; user permutes keep
their place. Sinking below an unsqueeze would raise the copy's rank, up to
a rank-5 layout copy that Cortex-M cannot run.
"""

@property
def targets(self) -> list[EdgeOpOverload]:
return [LAYOUT_PERMUTE_COPY]

def maybe_remove_or_replace(self, node: Node) -> bool:
users = list(node.users)
user_value = users[0].meta.get("val") if len(users) == 1 else None
value = node.meta.get("val")
if (
isinstance(user_value, torch.Tensor)
and isinstance(value, torch.Tensor)
and user_value.dim() > value.dim()
):
return False
return super().maybe_remove_or_replace(node)


class ValidateCortexMExplicitLayoutPass(ExportPass):
def call(self, graph_module: GraphModule) -> PassResult:
for node in graph_module.graph.nodes:
Expand Down
6 changes: 6 additions & 0 deletions backends/cortex_m/test/misc/test_portable_int8.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,12 @@ def _quantize_and_export(
(torch.randn(1, 3, 4, 5), torch.randn(1, 3, 4, 5)),
None,
),
"expand_as": OpCase(
torch.ops.aten.expand_as.default,
_build_module(lambda x, y: torch.ops.aten.expand_as.default(x, y)),
(torch.randn(1, 3, 4, 5), torch.randn(2, 3, 4, 5)),
None,
),
"select": OpCase(
torch.ops.aten.select.int,
_build_module(lambda x, y: torch.ops.aten.select.int(x, 1, 0)),
Expand Down
8 changes: 2 additions & 6 deletions backends/cortex_m/test/misc/test_quantization.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import torch
from executorch.backends.arm._passes.arm_pass_utils import get_first_fake_tensor
from executorch.backends.arm.test.common import parametrize, xfail_type
from executorch.backends.arm.test.common import parametrize
from executorch.backends.cortex_m.test.tester import (
CortexMTester,
McuTestCase,
Expand Down Expand Up @@ -358,12 +358,8 @@ def forward(self, x):
),
}

xfails: dict[str, xfail_type] = {
"surrounded_quantized_op_constant": "Numerical error since the add is forced to have non-correct qparams.",
}


@parametrize("test_case", test_cases, xfails=xfails)
@parametrize("test_case", test_cases)
def test_shared_qspec_quantizer(test_case):
"""
Test that ops which does not change dynamic range are able to use int8 portable kernels.
Expand Down
2 changes: 2 additions & 0 deletions backends/cortex_m/test/targets.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ def define_common_targets(is_fbcode = False):
"//executorch/backends/cortex_m/passes:cortex_passes",
"//executorch/backends/cortex_m/quantizer:quantizer",
"//executorch/backends/test/harness:tester",
"//executorch/backends/test:graph_builder",
"//executorch/backends/transforms:channels_last_layout",
"//executorch/backends/transforms:remove_unused_constants_pass",
"//executorch/exir:lib",
"//executorch/exir/dialects:lib",
Expand Down
Loading
Loading