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
Original file line number Diff line number Diff line change
Expand Up @@ -498,12 +498,89 @@
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(

Check warning on line 578 in backends/transforms/fused_quant/optimization_passes/quant_absorption.py

View workflow job for this annotation

GitHub Actions / lintrunner

FLAKE8 C901

'_try_absorb_input' is too complex (13) See https://www.flake8rules.com/rules/C901.html.
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)
Expand All @@ -514,8 +591,14 @@
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:
Expand All @@ -527,7 +610,7 @@
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])
Expand Down Expand Up @@ -575,8 +658,9 @@
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
Expand Down Expand Up @@ -636,10 +720,13 @@
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:
Expand Down
110 changes: 82 additions & 28 deletions backends/transforms/fused_quant/test/test_quant_absorption.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
Loading