diff --git a/backends/xnnpack/_passes/remove_redundant_copy_pass.py b/backends/xnnpack/_passes/remove_redundant_copy_pass.py index e0289650081..abc0c03a146 100644 --- a/backends/xnnpack/_passes/remove_redundant_copy_pass.py +++ b/backends/xnnpack/_passes/remove_redundant_copy_pass.py @@ -71,6 +71,9 @@ def _try_remove_quantized_redundant_to_copy(self, node, graph): """ Try to remove redundant to_copy operations in quantized graphs with pattern dq1 -> to_copy1 -> q1 -> dq2 -> to_copy2 -> q2 """ + if is_dtype_cast(node): + return False + # Check if this to_copy is followed by a quantize node if len(node.users) != 1: return False @@ -97,6 +100,7 @@ def _try_remove_quantized_redundant_to_copy(self, node, graph): prev_to_copy = prev_q_node.args[0] if ( prev_to_copy.target == exir_ops.edge.aten._to_copy.default + and not is_dtype_cast(prev_to_copy) and ChannelsLastTaggedReshapePass.is_nchw_node(prev_to_copy) != ChannelsLastTaggedReshapePass.is_nchw_node(node) and len(prev_to_copy.users) == 1 diff --git a/backends/xnnpack/partition/config/__init__.py b/backends/xnnpack/partition/config/__init__.py index 38c641b95e6..40cc380c8c9 100644 --- a/backends/xnnpack/partition/config/__init__.py +++ b/backends/xnnpack/partition/config/__init__.py @@ -57,6 +57,7 @@ SquareRootConfig, SubConfig, TanhConfig, + ToCopyConfig, ToDimOrderCopyConfig, UnsqueezeCopyConfig, UpsampleBilinear2dConfig, @@ -115,6 +116,7 @@ ReciprocalSquareRootConfig, ReLUConfig, TanhConfig, + ToCopyConfig, ToDimOrderCopyConfig, SigmoidConfig, SiluConfig, diff --git a/backends/xnnpack/partition/config/generic_node_configs.py b/backends/xnnpack/partition/config/generic_node_configs.py index 4a2966631e0..bc43be8e8c7 100644 --- a/backends/xnnpack/partition/config/generic_node_configs.py +++ b/backends/xnnpack/partition/config/generic_node_configs.py @@ -20,6 +20,7 @@ from executorch.backends.xnnpack.utils.utils import ( get_input_node, get_param_tensor, + is_dtype_cast, is_foldable_broadcast_operand, is_param_node, normalize_mean_dims, @@ -705,10 +706,42 @@ def check_constraints(self, node: torch.fx.Node, ep: ExportedProgram) -> bool: return True + def get_node_and_deps( + self, node: torch.fx.Node, ep: ExportedProgram + ) -> List[torch.fx.Node]: + # A cast is serialized as a convert without quantization parameters, so + # a dq before it and a q after it stay explicit nodes. + if is_dtype_cast(node): + return [node] + return super().get_node_and_deps(node, ep) + def supported_precision_types(self) -> List[ConfigPrecisionType]: return [ConfigPrecisionType.FP32, ConfigPrecisionType.STATIC_QUANT] +class ToCopyConfig(ToDimOrderCopyConfig): + """ + Programs exported with skip_dim_order keep aten._to_copy for every copy. + Only dtype casts are partitioned, under the same dtype rules as + ToDimOrderCopyConfig: inside the delegate, ChannelsLastTaggedReshapePass, + RemoveRedundantCopyPass and ToCopyVisitor read any other _to_copy as an + NCHW <-> NHWC layout copy. + """ + + target_name = "_to_copy.default" + + def check_constraints(self, node: torch.fx.Node, ep: ExportedProgram) -> bool: + if not is_dtype_cast(node): + why(node, reason="only dtype casts are supported") + return False + return super().check_constraints(node, ep) + + def supported_precision_types(self) -> List[ConfigPrecisionType]: + # A cast never folds the q/dq around it (see get_node_and_deps), so + # static quantization adds nothing. + return [ConfigPrecisionType.FP32] + + class MeanDimConfig(GenericNodePartitionerConfig): target_name = "mean.dim" supports_bf16 = False diff --git a/backends/xnnpack/test/ops/test_to_copy_dtype.py b/backends/xnnpack/test/ops/test_to_copy_dtype.py index 4837d8b6e00..e0b826ac09c 100644 --- a/backends/xnnpack/test/ops/test_to_copy_dtype.py +++ b/backends/xnnpack/test/ops/test_to_copy_dtype.py @@ -10,6 +10,7 @@ from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner from executorch.backends.xnnpack.test.tester import Tester from executorch.backends.xnnpack.test.tester.tester import ToEdgeTransformAndLower +from executorch.backends.xnnpack.utils.configs import get_xnnpack_edge_compile_config from executorch.export.utils import is_fbcode @@ -38,15 +39,32 @@ def forward(self, x): "executorch_exir_dialects_edge__ops_aten__to_copy_default", ] - def _run(self, module, inputs, enable_bf16=False): - ( - Tester(module.eval(), inputs) + def _lower( + self, + module, + inputs, + enable_bf16=False, + skip_dim_order=False, + dynamic_shapes=None, + ): + return ( + Tester(module.eval(), inputs, dynamic_shapes=dynamic_shapes) .export() .to_edge_transform_and_lower( ToEdgeTransformAndLower( - partitioners=[XnnpackPartitioner(enable_bf16=enable_bf16)] + partitioners=[XnnpackPartitioner(enable_bf16=enable_bf16)], + edge_compile_config=get_xnnpack_edge_compile_config( + skip_dim_order=skip_dim_order + ), ) ) + ) + + def _run(self, module, inputs, enable_bf16=False, skip_dim_order=False): + ( + self._lower( + module, inputs, enable_bf16=enable_bf16, skip_dim_order=skip_dim_order + ) .check_not(self.cast_ops) .check_count({"torch.ops.higher_order.executorch_call_delegate": 1}) .to_executorch() @@ -54,59 +72,228 @@ def _run(self, module, inputs, enable_bf16=False): .run_method_and_compare_outputs(atol=2e-2, rtol=2e-2) ) + def _run_both(self, module, inputs, enable_bf16=False): + """ + With skip_dim_order, as LLMEdgeManager exports, casts stay aten._to_copy + instead of becoming _to_dim_order_copy. + """ + for skip_dim_order in (False, True): + with self.subTest(skip_dim_order=skip_dim_order): + self._run(module, inputs, enable_bf16, skip_dim_order) + + def _check_not_partitioned(self, module, inputs, enable_bf16=False, casts=1): + for skip_dim_order in (False, True): + with self.subTest(skip_dim_order=skip_dim_order): + self._lower( + module, + inputs, + enable_bf16=enable_bf16, + skip_dim_order=skip_dim_order, + ).check_count({self.cast_ops[skip_dim_order]: casts}) + def test_fp32_io_around_fp16_conv(self): - self._run(self.Fp16Inner(), (torch.randn(1, 3, 8, 8),)) + self._run_both(self.Fp16Inner(), (torch.randn(1, 3, 8, 8),)) def test_cast_only(self): - self._run(self.CastOnly(), (torch.randn(2, 5),)) + self._run_both(self.CastOnly(), (torch.randn(2, 5),)) + + def test_cast_only_dynamic(self): + batch = torch.export.Dim("batch", min=1, max=8) + for skip_dim_order in (False, True): + with self.subTest(skip_dim_order=skip_dim_order): + ( + self._lower( + self.CastOnly(), + (torch.randn(2, 5),), + skip_dim_order=skip_dim_order, + dynamic_shapes=({0: batch},), + ) + .check_not(self.cast_ops) + .check_count({"torch.ops.higher_order.executorch_call_delegate": 1}) + .to_executorch() + .serialize() + .run_method_and_compare_outputs(num_runs=5, atol=2e-2, rtol=2e-2) + ) + + def test_not_partitioned(self): + """ + Only fp32 <-> fp16 and fp32 <-> bf16 casts that keep the dim order are + partitioned, and with skip_dim_order no layout-only copy is. + """ - def test_int_cast_not_partitioned(self): class ToInt(torch.nn.Module): def forward(self, x): return x.to(torch.int32) - ( - Tester(ToInt().eval(), (torch.randn(2, 5),)) - .export() - .to_edge_transform_and_lower() - .check_not(["torch.ops.higher_order.executorch_call_delegate"]) - ) - - def test_dtype_cast_with_dim_order_change_not_partitioned(self): class ToHalfChannelsLast(torch.nn.Module): def forward(self, x): return x.to(torch.float16, memory_format=torch.channels_last) - ( - Tester(ToHalfChannelsLast().eval(), (torch.randn(1, 3, 4, 4),)) - .export() - .to_edge_transform_and_lower() - .check_not(["torch.ops.higher_order.executorch_call_delegate"]) - .check_count({self.cast_ops[0]: 1}) + for module in (ToInt(), ToHalfChannelsLast()): + with self.subTest(type(module).__name__): + self._check_not_partitioned(module, (torch.randn(1, 3, 4, 4),)) + + class ToChannelsLast(torch.nn.Module): + def forward(self, x): + return x.to(memory_format=torch.channels_last) + + self._lower( + ToChannelsLast(), (torch.randn(1, 3, 4, 4),), skip_dim_order=True + ).check_not(["torch.ops.higher_order.executorch_call_delegate"]).check_count( + {self.cast_ops[1]: 1} ) def test_dtype_cast_to_contiguous_from_channels_last_not_partitioned(self): + """ + With dim order, the layout-only copy is partitioned and the cast that + changes the dim order is not. With skip_dim_order, neither is. Such a + program only lowers there: a channels_last copy left outside the + delegate cannot be emitted without dim order. + """ + class ChannelsLastToHalfContiguous(torch.nn.Module): def forward(self, x): x = x.to(memory_format=torch.channels_last) return x.to(torch.float16, memory_format=torch.contiguous_format) + inputs = (torch.randn(1, 3, 4, 4),) ( - Tester(ChannelsLastToHalfContiguous().eval(), (torch.randn(1, 3, 4, 4),)) - .export() - .to_edge_transform_and_lower() + self._lower(ChannelsLastToHalfContiguous(), inputs) .check_count({self.cast_ops[0]: 1}) .to_executorch() .serialize() .run_method_and_compare_outputs(atol=2e-2, rtol=2e-2) ) + self._lower( + ChannelsLastToHalfContiguous(), inputs, skip_dim_order=True + ).check_not(["torch.ops.higher_order.executorch_call_delegate"]).check_count( + {self.cast_ops[1]: 2} + ) def test_dtype_cast_preserving_channels_last_partitioned(self): + """ + The cast reads a channels_last tensor and keeps its dim order, so it is + partitioned. With skip_dim_order, the layout-only copy before it stays + outside the delegate, which only lowers there, as above. + """ + class ChannelsLastToHalf(torch.nn.Module): def forward(self, x): return x.to(memory_format=torch.channels_last).to(torch.float16) - self._run(ChannelsLastToHalf(), (torch.randn(1, 3, 4, 4),)) + inputs = (torch.randn(1, 3, 4, 4),) + self._run(ChannelsLastToHalf(), inputs) + self._lower(ChannelsLastToHalf(), inputs, skip_dim_order=True).check_count( + { + self.cast_ops[1]: 1, + "torch.ops.higher_order.executorch_call_delegate": 1, + } + ) + + def test_cast_of_nhwc_conv_output(self): + """ + The cast reads the convolution's NHWC output inside the delegate, and + its result is converted back to NCHW at the delegate output. + """ + + class ConvToHalf(torch.nn.Module): + def __init__(self): + super().__init__() + self.conv = torch.nn.Conv2d(3, 8, 3) + + def forward(self, x): + return self.conv(x).to(torch.float16) + + for skip_dim_order in (False, True): + with self.subTest(skip_dim_order=skip_dim_order): + ( + self._lower( + ConvToHalf(), + (torch.randn(1, 3, 10, 10),), + skip_dim_order=skip_dim_order, + ) + .check_not(self.cast_ops) + .check_xnnpack_node_count( + {"XNNConv2d": 1, "XNNConvert": 1, "XNNStaticTranspose": 2} + ) + .to_executorch() + .serialize() + .run_method_and_compare_outputs(atol=2e-2, rtol=2e-2) + ) + + def test_integer_constant_cast_not_partitioned(self): + """ + Export lifts the 2 in x.float() * 2 as an integer constant and casts it + to float. XNNPACK does not convert integers, so that cast stays outside + the delegate, while the cast of x is partitioned. + """ + + class UpcastTimesInt(torch.nn.Module): + def forward(self, x): + return x.float() * 2 + + for skip_dim_order in (False, True): + with self.subTest(skip_dim_order=skip_dim_order): + ( + self._lower( + UpcastTimesInt(), + (torch.randn(2, 5).to(torch.float16),), + skip_dim_order=skip_dim_order, + ) + .check_count( + { + self.cast_ops[skip_dim_order]: 1, + "torch.ops.higher_order.executorch_call_delegate": 1, + } + ) + .to_executorch() + .serialize() + .run_method_and_compare_outputs(atol=2e-2, rtol=2e-2) + ) + + class RequantizeAroundCast(torch.nn.Module): + def forward(self, x): + qd = torch.ops.quantized_decomposed + x = qd.quantize_per_tensor.default(x, 0.04, 0, -128, 127, torch.int8) + x = qd.dequantize_per_tensor.default(x, 0.04, 0, -128, 127, torch.int8) + x = qd.quantize_per_tensor.default( + x.to(torch.float16), 0.1, 0, -128, 127, torch.int8 + ) + return qd.dequantize_per_tensor.default(x, 0.1, 0, -128, 127, torch.int8) + + class RequantizeAroundCastConv(torch.nn.Module): + def __init__(self): + super().__init__() + self.requantize = TestToCopyDtype.RequantizeAroundCast() + self.conv = torch.nn.Conv2d(4, 8, 3) + + def forward(self, x): + return self.conv(self.requantize(x)) + + def test_requantize_around_cast(self): + """ + The q/dq around a cast stay explicit, so the requantize from a scale of + 0.04 to 0.1 is kept. Before a convolution, the layout pass copies the + requantized value to NHWC between its own q/dq, and that copy must not + take the cast and the requantize with it when it is removed. + """ + cases = ( + (self.RequantizeAroundCast(), torch.randn(2, 8)), + (self.RequantizeAroundCastConv(), torch.randn(1, 4, 8, 8)), + ) + for module, x in cases: + for skip_dim_order in (False, True): + with self.subTest(type(module).__name__, skip_dim_order=skip_dim_order): + ( + self._lower(module, (x,), skip_dim_order=skip_dim_order) + .check_count( + {"torch.ops.higher_order.executorch_call_delegate": 1} + ) + .check_not(self.cast_ops) + .to_executorch() + .serialize() + .run_method_and_compare_outputs(atol=1e-3, rtol=1e-3) + ) class Bf16Inner(torch.nn.Module): def __init__(self): @@ -134,11 +321,11 @@ def forward(self, x): @unittest.skipIf(is_fbcode(), "skipping for fbcode") def test_fp32_io_around_bf16_linear(self): - self._run(self.Bf16Inner(), (torch.randn(4, 16),), enable_bf16=True) + self._run_both(self.Bf16Inner(), (torch.randn(4, 16),), enable_bf16=True) @unittest.skipIf(is_fbcode(), "skipping for fbcode") def test_bf16_upcast(self): - self._run( + self._run_both( self.Bf16Upcast(), (torch.randn(2, 5, dtype=torch.bfloat16),), enable_bf16=True, @@ -146,7 +333,7 @@ def test_bf16_upcast(self): @unittest.skipIf(is_fbcode(), "skipping for fbcode") def test_bf16_softmax_upcast(self): - self._run( + self._run_both( self.Bf16SoftmaxUpcast(), (torch.randn(2, 16, 32, dtype=torch.bfloat16),), enable_bf16=True, @@ -178,11 +365,8 @@ def test_fp32_to_bf16_rounds_like_pytorch(self): ) def test_bf16_cast_not_partitioned_without_enable_bf16(self): - ( - Tester(self.Bf16Upcast().eval(), (torch.randn(2, 5, dtype=torch.bfloat16),)) - .export() - .to_edge_transform_and_lower() - .check_count({self.cast_ops[0]: 2}) + self._check_not_partitioned( + self.Bf16Upcast(), (torch.randn(2, 5, dtype=torch.bfloat16),), casts=2 ) def test_fp16_bf16_cast_not_partitioned(self): @@ -190,13 +374,6 @@ class HalfToBf16(torch.nn.Module): def forward(self, x): return x.to(torch.bfloat16) - ( - Tester(HalfToBf16().eval(), (torch.randn(2, 5, dtype=torch.float16),)) - .export() - .to_edge_transform_and_lower( - ToEdgeTransformAndLower( - partitioners=[XnnpackPartitioner(enable_bf16=True)] - ) - ) - .check_not(["torch.ops.higher_order.executorch_call_delegate"]) + self._check_not_partitioned( + HalfToBf16(), (torch.randn(2, 5, dtype=torch.float16),), enable_bf16=True ) diff --git a/docs/source/backends/xnnpack/op-support.csv b/docs/source/backends/xnnpack/op-support.csv index 9bd121fa3d1..1124aa020da 100644 --- a/docs/source/backends/xnnpack/op-support.csv +++ b/docs/source/backends/xnnpack/op-support.csv @@ -1,5 +1,6 @@ Operator,Compute DType,Quantization,Constraints -_to_dim_order_copy,"fp16, fp32",,no dtype conversion +_to_copy,"bf16, fp16, fp32",,"dtype conversion only: fp32 <-> fp16, or fp32 <-> bf16 with enable_bf16; no dim order change" +_to_dim_order_copy,"bf16, fp16, fp32",,"dim order conversion, or fp32 <-> fp16 / fp32 <-> bf16 (with enable_bf16) without a dim order change" abs,"fp16, fp32",, add,"fp16, fp32",PT2E: static int8,alpha=1 avg_pool2d,"fp16, fp32",PT2E: static int8,"ceil_mode=False, count_include_pad=False, divisor_override=pooling_region"