From 26a25fd1cf8b2cee341a06dc37093daf2bee9ff5 Mon Sep 17 00:00:00 2001 From: Andrew Grebenisan Date: Wed, 25 Nov 2026 11:49:28 -0800 Subject: [PATCH] Absorb an input quantize read by several fused ops into all of them Summary: Input-side quant absorption (`absorb_into_inputs`) absorbs a dequantize -> quantize pair into the input qparams of the fused op that reads it, but only when the quantize has one reader. A model input read by several ops keeps the pair, which then becomes a requantize: with `--image-input`, XLSR's uint8 pixels feed its five parallel first-layer convs, so a uint8 -> int8 requantize (same scale, zero point 0 -> -128, exact) runs before them, while UNet's single first conv reads uint8 directly. `_try_absorb_input_fan_out` absorbs the pair into every reader, or into none: each reader must be a fused op that reads the quantize only through input slots, has per-tensor qparams, can represent its composed qparams, and keeps a zero point of 0 if it is in `symmetric_quant_input_ops`. Each reader composes its own qparams, as a single reader does. A reader behind a passthrough still does not qualify, since the chain itself would fork. The single-reader path is unchanged; the symmetric check is now made per reader, so `_try_absorb_input` takes the op set instead of a flag. It stays behind the `absorb_into_inputs` opt-in. Differential Revision: D134566322 --- .../optimization_passes/quant_absorption.py | 101 ++++++++++++++-- .../fused_quant/test/test_quant_absorption.py | 110 +++++++++++++----- 2 files changed, 176 insertions(+), 35 deletions(-) diff --git a/backends/transforms/fused_quant/optimization_passes/quant_absorption.py b/backends/transforms/fused_quant/optimization_passes/quant_absorption.py index 6928bcf6b5d..80230923170 100644 --- a/backends/transforms/fused_quant/optimization_passes/quant_absorption.py +++ b/backends/transforms/fused_quant/optimization_passes/quant_absorption.py @@ -498,12 +498,89 @@ def _set_qparams( set_arg(node, f"{prefix}_quant_max", quant_max) +def _count_uses(user: fx.Node, node: fx.Node) -> int: + """How many argument slots of ``user`` read ``node``.""" + uses = 0 + + def count(arg: fx.Node) -> fx.Node: + nonlocal uses + uses += arg is node + return arg + + fx.node.map_arg((user.args, user.kwargs), count) + return uses + + +def _try_absorb_input_fan_out( + exported_program: ExportedProgram, + quantize: fx.Node, + graph: fx.Graph, + symmetric_quant_input_ops: frozenset[EdgeOpOverload], +) -> bool: + """Absorb a dequantize→quantize read by several fused inputs into all of + them, or into none. + + Each reader composes its own input qparams, as a single reader does. If any + reader is not a fused op, reads the quantize in a non-input slot, or cannot + represent its composition, the pair stays for all of them. + """ + dequantize = get_arg(quantize, "input", Optional[fx.Node]) + if dequantize is None or dequantize.target != _DEQUANT_PER_TENSOR: + return False + source = get_arg(dequantize, "input", Optional[fx.Node]) + if source is None: + return False + + absorptions: list[tuple[fx.Node, str, tuple[float, int]]] = [] + for user in quantize.users: + if not _is_fused_quant_op(user): + return False + assert isinstance(user.target, EdgeOpOverload) + input_names, _ = split_fused_arg_names(user.target) + names = [ + name + for name in input_names + if get_arg(user, name, Optional[fx.Node]) is quantize + ] + if len(names) != _count_uses(user, quantize): + return False + for name in names: + qparams = get_qparams_from_node(user, name) + if qparams is None or not qparams.is_per_tensor(): + return False + replacement = _compose_input_qparams( + exported_program, dequantize, quantize, user, name + ) + if replacement is None: + return False + if user.target in symmetric_quant_input_ops and replacement[1] != 0: + return False + absorptions.append((user, name, replacement)) + + for user, name, (scale, zero_point) in absorptions: + set_arg(user, name, source) + _set_qparams( + exported_program, + user, + name, + scale=scale, + zero_point=zero_point, + dtype=dequantize.meta["val"].dtype, + quant_min=get_arg(dequantize, "quant_min", int), + quant_max=get_arg(dequantize, "quant_max", int), + ) + graph.erase_node(quantize) + if not dequantize.users: + graph.erase_node(dequantize) + return True + + def _try_absorb_input( exported_program: ExportedProgram, consumer: fx.Node, input_name: str, graph: fx.Graph, - keep_symmetric: bool, + symmetric_quant_input_ops: frozenset[EdgeOpOverload], ) -> bool: """Absorb an upstream dequantize→quantize into fused input qparams.""" consumer_qparams = get_qparams_from_node(consumer, input_name) @@ -514,8 +591,14 @@ def _try_absorb_input( if consumer_input is None: return False quantize, passthrough_chain = _find_quant_through_input_passthrough(consumer_input) - if quantize is None or len(quantize.users) != 1: + if quantize is None: return False + if len(quantize.users) != 1: + # A model input read by several ops, such as XLSR's parallel first + # convs. Through a passthrough, the chain itself would fork. + return not passthrough_chain and _try_absorb_input_fan_out( + exported_program, quantize, graph, symmetric_quant_input_ops + ) dequantize = get_arg(quantize, "input", Optional[fx.Node]) if dequantize is None or dequantize.target != _DEQUANT_PER_TENSOR: @@ -527,7 +610,7 @@ def _try_absorb_input( if replacement_qparams is None: return False replacement_scale, replacement_zp = replacement_qparams - if keep_symmetric and replacement_zp != 0: + if consumer.target in symmetric_quant_input_ops and replacement_zp != 0: return False source = get_arg(dequantize, "input", Optional[fx.Node]) @@ -575,8 +658,9 @@ class QuantAbsorptionPass(ExportedProgramPassBase): On the input side, when a dequant→quant pair feeds any fused_quant input with per-tensor qparams, this pass composes the dequantize, quantize, and consumer input qparams, then bypasses the pair. This handles graph inputs, which have - no fused producer into which the quantization can be absorbed. It is opt-in: - see ``absorb_into_inputs`` below. + no fused producer into which the quantization can be absorbed. A pair read + by several fused inputs is absorbed into each of them, or kept for all if any + one cannot take it. It is opt-in: see ``absorb_into_inputs`` below. It also absorbs a *bare* downstream quantize into a fused op whose output is currently unquantized (null out qparams), turning that op into a directly @@ -636,10 +720,13 @@ def call(self, exported_program: ExportedProgram) -> ExportedProgramPassResult: continue assert isinstance(node.target, EdgeOpOverload) input_names, _ = split_fused_arg_names(node.target) - keep_symmetric = node.target in self._symmetric_quant_input_ops for input_name in input_names: modified |= _try_absorb_input( - exported_program, node, input_name, graph, keep_symmetric + exported_program, + node, + input_name, + graph, + self._symmetric_quant_input_ops, ) if modified: diff --git a/backends/transforms/fused_quant/test/test_quant_absorption.py b/backends/transforms/fused_quant/test/test_quant_absorption.py index b304b21c562..31f7f4ddb96 100644 --- a/backends/transforms/fused_quant/test/test_quant_absorption.py +++ b/backends/transforms/fused_quant/test/test_quant_absorption.py @@ -1265,6 +1265,7 @@ def _build_dequant_quant_pool( expose_dequant: bool = False, input_passthrough: str | None = None, expose_passthrough: bool = False, + second_pool_input_zero_point: int | None = None, ) -> tuple[ExportedProgram, torch.Tensor]: builder = ProgramBuilder() inp = (torch.arange(16, dtype=torch.uint8) * input_step).reshape(1, 4, 4, 1) @@ -1304,34 +1305,39 @@ def _build_dequant_quant_pool( ) elif input_passthrough is not None: raise ValueError(f"Unsupported input passthrough: {input_passthrough}") - pool_input_qparams = create_per_tensor_qparams( - builder, - scale=consumer_input_scale, - zero_point=consumer_input_zero_point, - dtype=torch.float32, - ) - pool_output_qparams = create_per_tensor_qparams( - builder, - scale=0.1, - dtype=torch.uint8, - ) - pool = builder.call_operator( - op=exir_ops.edge.fused_quant.avg_pool2d_channels_last.default, - args=( - consumer_input, - *pool_input_qparams, - *pool_output_qparams[:3], - 0, - 255, - [2, 2], - [2, 2], - [0, 0], - False, - True, - None, - ), - ) - outputs = [pool] + + def add_pool(input_zero_point: int) -> torch.fx.Node: + pool_input_qparams = create_per_tensor_qparams( + builder, + scale=consumer_input_scale, + zero_point=input_zero_point, + dtype=torch.float32, + ) + pool_output_qparams = create_per_tensor_qparams( + builder, + scale=0.1, + dtype=torch.uint8, + ) + return builder.call_operator( + op=exir_ops.edge.fused_quant.avg_pool2d_channels_last.default, + args=( + consumer_input, + *pool_input_qparams, + *pool_output_qparams[:3], + 0, + 255, + [2, 2], + [2, 2], + [0, 0], + False, + True, + None, + ), + ) + + outputs = [add_pool(consumer_input_zero_point)] + if second_pool_input_zero_point is not None: + outputs.append(add_pool(second_pool_input_zero_point)) if expose_quant: outputs.append(quant) if expose_dequant: @@ -1679,6 +1685,54 @@ def test_does_not_absorb_unrepresentable_consumer_input_qparams(self) -> None: self.assertFalse(result.modified) + def test_absorbs_dequant_quant_read_by_several_fused_inputs(self) -> None: + ep, inp = self._build_dequant_quant_pool(second_pool_input_zero_point=-5) + + result = QuantAbsorptionPass(absorb_into_inputs=True)(ep) + + self.assertTrue(result.modified) + expected = self._direct_pool(inp) + for actual in result.exported_program.module()(inp): + self.assertTrue(torch.equal(expected, actual)) + graph = result.exported_program.graph + for target in ( + exir_ops.edge.quantized_decomposed.dequantize_per_tensor.default, + exir_ops.edge.quantized_decomposed.quantize_per_tensor.default, + ): + self.assertEqual([], graph.find_nodes(op="call_function", target=target)) + pools = graph.find_nodes( + op="call_function", + target=exir_ops.edge.fused_quant.avg_pool2d_channels_last.default, + ) + self.assertEqual(2, len(pools)) + for pool in pools: + self.assertEqual("placeholder", get_arg(pool, "inp", torch.fx.Node).op) + input_qparams = get_qparams_from_node(pool, "inp") + assert input_qparams is not None + self.assertAlmostEqual( + 0.25, get_scale(result.exported_program, input_qparams) + ) + self.assertEqual(0, get_zero_point(result.exported_program, input_qparams)) + result.exported_program.validate() + + def test_does_not_absorb_fan_out_unless_every_reader_can(self) -> None: + # The second pool's zero point composes to 1.6 on the dequantize's grid. + ep, _ = self._build_dequant_quant_pool( + quant_scale=0.4, + consumer_input_zero_point=-5, + second_pool_input_zero_point=-4, + ) + + result = QuantAbsorptionPass(absorb_into_inputs=True)(ep) + + self.assertFalse(result.modified) + graph = result.exported_program.graph + (quant,) = graph.find_nodes( + op="call_function", + target=exir_ops.edge.quantized_decomposed.quantize_per_tensor.default, + ) + self.assertEqual(2, len(quant.users)) + def test_symmetric_quant_input_op_keeps_requantize_for_nonzero_zero_point( self, ) -> None: