Skip to content

Commit abd274b

Browse files
aliafzalmeta-codesync[bot]
authored andcommitted
Fix Cadence compiler bugs that the backend test suite exposes (#24931)
Summary: Pull Request resolved: #24931 Running the backend test suite through the Cadence compiler (later in this stack) found four compiler bugs. Each fix has unit tests. Fused quantized linear and conv add the int32 bias to an accumulator whose scale is `input_scale * weight_scale`. torchao's implicit sharing gives every call of a shared module one bias observer, so the bias is quantized once, and `QuantizableLSTM` calls the same `Linear` at every time step with a different input scale. In a 10-step int8 LSTM, 18 of 20 fused linears used a bias scaled 0.03x to 1.14x off, and outputs were up to 0.44 off. `bias_at_scale` now rescales the bias constant to the accumulator scale when the two differ, which brings the int8 LSTM outputs within 0.007 of the quantized reference. Fixing this in the quantizer would also unshare the activation and add a dequantize/quantize pair per call. The fusion is shared by every Cadence backend, but a bias already at the accumulator scale, the usual single-use case, passes through unchanged; the 1e-5 match tolerance on the scale ratio is far above the float32 against float64 rounding, which is under 6e-8. In `CompileMode.SIZE`, the dispatch of `quantized_conv2d_nhwc` passed the generic op's 15th argument, `offset`, to the 14-argument typed variants, so every int8 model with a 2-D convolution failed to compile. The dispatch now drops unset arguments that the typed op doesn't have, and raises if one of them is set. The compiler picks `fully_connected` when the input's leading dimensions multiply to 1, but its 6 metas checked `size(0) == 1`, so a 1-D input, where `size(0)` is the feature count, failed to compile. The metas now check the product of the leading dimensions, the same rule the compiler uses. Memory planning can turn a contiguous `select` into a view of its input. The check read the output shape with the raw `dim`, and since `select` drops its dimension, `select(dim=-2)` on `[3, 4, 5]` checked the wrong dimensions and became a view at the wrong offset. The check now normalizes `dim` against the input's rank and reads the input shape. Positive dims and slices are unaffected. Authored with Claude Code. Reviewed By: DrJessop Differential Revision: D128295394
1 parent cb3e231 commit abd274b

8 files changed

Lines changed: 349 additions & 18 deletions

File tree

‎backends/cadence/aot/memory_constraints.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
import torch
1616
import torch.fx
17-
from executorch.backends.cadence.aot.pass_utils import CompileMode
17+
from executorch.backends.cadence.aot.pass_utils import CompileMode, get_arg
1818
from executorch.backends.cadence.aot.utils import get_shape, is_node_in_flattened_output
1919
from executorch.exir import memory
2020
from executorch.exir.pass_manager import PassManager
@@ -627,11 +627,11 @@ def removable_slice_or_select_op(
627627

628628
# A slice/select op is redundant only if (a) either the slicing/select
629629
# is along the outermost dimension, or (b) all dimensions previous to
630-
# slicing/select dimension are 0 or 1.
631-
node_spec = node.meta.get("spec")
632-
tensor_shape = list(node_spec.shape)
633-
dim = 0 if len(node.args) == 1 else node.args[1]
634-
if dim and not set(tensor_shape[0:dim]).issubset({0, 1}):
630+
# slicing/select dimension are 0 or 1. A select drops its dimension from
631+
# the output, so use the input shape.
632+
input_shape = input_node.meta["spec"].shape
633+
dim = get_arg(node, "dim", int) % len(input_shape)
634+
if not set(input_shape[0:dim]).issubset({0, 1}):
635635
return False
636636

637637
# The slice step should be 1 for contiguity.

‎backends/cadence/aot/ops_registrations.py‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2704,7 +2704,7 @@ def fully_connected_meta(
27042704
torch._check(
27052705
src.dtype in (torch.float32, torch.bfloat16), lambda: "expected float dtype"
27062706
)
2707-
torch._check(src.size(0) == 1, lambda: "expected batch size of 1")
2707+
torch._check(prod(src.shape[:-1]) == 1, lambda: "expected batch size of 1")
27082708
# src comes in shape [leading_dims, in_dim]
27092709
# weight comes in shape [out_dim, in_dim]
27102710
# output comes in empty with shape [leading_dims, out_dim]
@@ -2729,11 +2729,10 @@ def quantized_fully_connected_meta(
27292729
) -> torch.Tensor:
27302730
torch._check(bias.dtype == torch.int32, lambda: "expected int32")
27312731
torch._check(weight.dim() == 2, lambda: "expected 2D tensor")
2732-
torch._check(src.size(0) == 1, lambda: "expected batch size of 1")
2732+
torch._check(prod(src.shape[:-1]) == 1, lambda: "expected batch size of 1")
27332733
# src comes in shape [leading_dims, in_dim]
27342734
# weight comes in shape [out_dim, in_dim]
27352735
# output comes in empty with shape [leading_dims, out_dim]
2736-
assert src.shape[0] == 1
27372736
out_size = list(src.size())
27382737
weight_size = list(weight.size())
27392738
assert len(weight_size) == 2
@@ -2755,11 +2754,10 @@ def quantized_fully_connected_per_tensor_meta(
27552754
) -> torch.Tensor:
27562755
torch._check(bias.dtype == torch.int32, lambda: "expected int32")
27572756
torch._check(weight.dim() == 2, lambda: "expected 2D tensor")
2758-
torch._check(src.size(0) == 1, lambda: "expected batch size of 1")
2757+
torch._check(prod(src.shape[:-1]) == 1, lambda: "expected batch size of 1")
27592758
# src comes in shape [leading_dims, in_dim]
27602759
# weight comes in shape [out_dim, in_dim]
27612760
# output comes in empty with shape [leading_dims, out_dim]
2762-
assert src.shape[0] == 1
27632761
out_size = list(src.size())
27642762
weight_size = list(weight.size())
27652763
assert len(weight_size) == 2
@@ -2783,7 +2781,7 @@ def quantized_fully_connected_packed_meta(
27832781
) -> torch.Tensor:
27842782
torch._check(bias.dtype == torch.int32, lambda: "expected int32")
27852783
torch._check(weight.dim() == 2, lambda: "expected 2D tensor")
2786-
torch._check(src.size(0) == 1, lambda: "expected batch size of 1")
2784+
torch._check(prod(src.shape[:-1]) == 1, lambda: "expected batch size of 1")
27872785
# src comes in shape [leading_dims, in_dim]
27882786
# weight comes in shape [out_dim, packed_row_bytes], so out_dim is still
27892787
# size(0) - that is what packing per row buys us - but in_dim is an
@@ -2812,11 +2810,10 @@ def quantized_fully_connected_asym8sxasym8s_asym8s_per_tensor_meta(
28122810
)
28132811
torch._check(bias.dtype == torch.int32, lambda: "expected int32")
28142812
torch._check(weight.dim() == 2, lambda: "expected 2D tensor")
2815-
torch._check(src.size(0) == 1, lambda: "expected batch size of 1")
2813+
torch._check(prod(src.shape[:-1]) == 1, lambda: "expected batch size of 1")
28162814
# src comes in shape [leading_dims, in_dim]
28172815
# weight comes in shape [out_dim, in_dim]
28182816
# output comes in empty with shape [leading_dims, out_dim]
2819-
assert src.shape[0] == 1
28202817
out_size = list(src.size())
28212818
weight_size = list(weight.size())
28222819
assert len(weight_size) == 2
@@ -2842,11 +2839,10 @@ def quantized_fully_connected_asym8uxasym8u_asym8u_per_tensor_meta(
28422839
)
28432840
torch._check(bias.dtype == torch.int32, lambda: "expected int32")
28442841
torch._check(weight.dim() == 2, lambda: "expected 2D tensor")
2845-
torch._check(src.size(0) == 1, lambda: "expected batch size of 1")
2842+
torch._check(prod(src.shape[:-1]) == 1, lambda: "expected batch size of 1")
28462843
# src comes in shape [leading_dims, in_dim]
28472844
# weight comes in shape [out_dim, in_dim]
28482845
# output comes in empty with shape [leading_dims, out_dim]
2849-
assert src.shape[0] == 1
28502846
out_size = list(src.size())
28512847
weight_size = list(weight.size())
28522848
assert len(weight_size) == 2

‎backends/cadence/aot/quantizer/pattern_utils.py‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,46 @@ def get_weight_zero_point(gm: fx.GraphModule, dq_weight: fx.Node) -> int | torch
227227
return zps.to(torch.int32).flatten()
228228

229229

230+
# The quantizer computes the bias scale in float32 and fusion in float64, so a
231+
# bias at the accumulator scale gives a ratio within 6e-8 of 1.
232+
_BIAS_SCALE_RATIO_ATOL = 1e-5
233+
234+
235+
def bias_at_scale(
236+
gm: fx.GraphModule,
237+
dq_bias: fx.Node,
238+
bias_scale: float | torch.Tensor,
239+
like_node: fx.Node,
240+
) -> fx.Node:
241+
"""The int32 bias operand for an accumulator at ``bias_scale``.
242+
243+
Quantized linear and conv ops add the int32 bias straight to the int32
244+
accumulator, whose scale is input_scale * weight_scale. The quantizer derives
245+
the bias scale the same way, but quantizes a shared bias only once, so a
246+
Linear that runs on inputs with different scales (QuantizableLSTM runs one per
247+
time step) has a bias whose scale matches only one of them. For the others,
248+
this returns the bias constant rescaled to ``bias_scale``.
249+
"""
250+
bias_q = get_arg(dq_bias, "input", fx.Node)
251+
ratio = torch.as_tensor(get_weight_scale(gm, dq_bias), dtype=torch.float64) / (
252+
torch.as_tensor(bias_scale, dtype=torch.float64)
253+
)
254+
if torch.allclose(
255+
ratio, torch.ones_like(ratio), rtol=0, atol=_BIAS_SCALE_RATIO_ATOL
256+
):
257+
return bias_q
258+
values = resolve_constant(gm, bias_q)
259+
assert (
260+
values is not None
261+
), f"cannot rescale {bias_q}: the bias is not a constant of the program"
262+
rescaled = torch.round(values.to(torch.float64) * ratio)
263+
int32 = torch.iinfo(torch.int32)
264+
assert bool(
265+
((rescaled >= int32.min) & (rescaled <= int32.max)).all()
266+
), f"cannot rescale {bias_q}: the rescaled bias does not fit in int32"
267+
return add_constant_placeholder(gm, rescaled.to(torch.int32), like_node, "bias")
268+
269+
230270
def insert_node_with_meta(
231271
gm: fx.GraphModule,
232272
op: OpOverload,
@@ -296,7 +336,7 @@ def fuse_conv(
296336
input_scale = get_arg(dq_input, "scale", float)
297337
bias_scale = input_scale * weight_scale
298338
if dq_bias is not None:
299-
bias_q = get_arg(dq_bias, "input", fx.Node)
339+
bias_q = bias_at_scale(gm, dq_bias, bias_scale, conv_node)
300340
else:
301341
# Cadence quantized conv ops require a non-optional bias argument.
302342
weight_node = get_arg(dq_weight, "input", fx.Node)
@@ -387,7 +427,7 @@ def fuse_linear(
387427
)
388428
out_multiplier, out_shift = quantize_tensor_multiplier(requantize_scale_t)
389429
if dq_bias is not None:
390-
bias_q = get_arg(dq_bias, "input", fx.Node)
430+
bias_q = bias_at_scale(gm, dq_bias, bias_scale, op_node)
391431
else:
392432
# Cadence quantized linear ops require a non-optional bias argument.
393433
weight_node = get_arg(dq_weight, "input", fx.Node)

‎backends/cadence/aot/tests/test_memory_passes.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1016,6 +1016,67 @@ def test_optimize_select_non_outermost(self) -> None:
10161016
)
10171017
self.verify_nop_memory_alloc(graph_module)
10181018

1019+
def _plan_select_or_slice(
1020+
self,
1021+
input_shape: list[int],
1022+
op: torch._ops.OpOverload,
1023+
args: tuple[int, ...],
1024+
out_shape: list[int],
1025+
) -> torch.fx.GraphModule:
1026+
"""Memory-plans op(add(x, full), *args), whose input is planned."""
1027+
builder = GraphBuilder()
1028+
x = builder.placeholder("x", torch.ones(*input_shape, dtype=torch.float32))
1029+
to_add_to_x = builder.call_operator(
1030+
op=exir_ops.edge.aten.full.default,
1031+
args=(input_shape, 123.0),
1032+
kwargs={"dtype": torch.float32},
1033+
)
1034+
add_x = builder.call_operator(
1035+
op=exir_ops.edge.aten.add.Tensor, args=(x, to_add_to_x)
1036+
)
1037+
out = builder.call_operator(
1038+
op=exir_ops.edge.aten.full.default,
1039+
args=(out_shape, 0.0),
1040+
kwargs={"dtype": torch.float32},
1041+
)
1042+
result = builder.call_operator(op=op, args=(add_x, *args), kwargs={"out": out})
1043+
builder.output([result])
1044+
graph_module = self.run_memory_planning_only(
1045+
builder.get_graph_module(), alloc_graph_input=False
1046+
)
1047+
graph_module.graph.eliminate_dead_code()
1048+
return graph_module
1049+
1050+
def test_does_not_optimize_select_on_a_negative_inner_dim(self) -> None:
1051+
# dim=-2 of a [3, 4, 5] input is dim 1, behind a dim of size 3, so the
1052+
# selected values are not contiguous in the input.
1053+
graph_module = self._plan_select_or_slice(
1054+
[3, 4, 5], torch.ops.aten.select_copy.int_out, (-2, 1), [3, 5]
1055+
)
1056+
self.assertEqual(
1057+
count_node(graph_module, torch.ops.aten._select_copy_nop.int_out), 0
1058+
)
1059+
self.assertEqual(
1060+
count_node(graph_module, torch.ops.aten.select_copy.int_out), 1
1061+
)
1062+
1063+
def test_optimize_select_on_a_negative_outermost_dim(self) -> None:
1064+
graph_module = self._plan_select_or_slice(
1065+
[3, 6], torch.ops.aten.select_copy.int_out, (-2, 1), [6]
1066+
)
1067+
self.assertEqual(
1068+
count_node(graph_module, torch.ops.aten._select_copy_nop.int_out), 1
1069+
)
1070+
self.verify_nop_memory_alloc(graph_module)
1071+
1072+
def test_does_not_optimize_slice_on_a_negative_inner_dim(self) -> None:
1073+
graph_module = self._plan_select_or_slice(
1074+
[3, 6], torch.ops.aten.slice_copy.Tensor_out, (-1, 0, 2, 1), [3, 2]
1075+
)
1076+
self.assertEqual(
1077+
count_node(graph_module, torch.ops.aten._slice_copy_nop.Tensor_out), 0
1078+
)
1079+
10191080
def test_optimize_select_depending_on_mode(self) -> None:
10201081
builder = GraphBuilder()
10211082
x = builder.placeholder("x", torch.ones(2, 6, dtype=torch.float32))

‎backends/cadence/aot/tests/test_pattern_utils.py‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -917,3 +917,118 @@ def test_encoded_multiplier_shift_matches_reference(self) -> None:
917917
f"out_shift per channel: got {out_shift}, "
918918
f"expected {expected_shift.to(torch.int32)}",
919919
)
920+
921+
922+
class TestFusedBiasScale(unittest.TestCase):
923+
"""The fused int32 bias must be at the accumulator scale, input * weight.
924+
925+
The quantizer quantizes a shared bias once, so a Linear that runs on inputs
926+
with different scales (QuantizableLSTM runs one per time step) reaches fusion
927+
with a bias whose scale matches only one of its calls.
928+
"""
929+
930+
INPUT_SCALE = 0.1
931+
WEIGHT_SCALE = 0.05
932+
BIAS = torch.tensor([100, -50, 25, 0], dtype=torch.int32)
933+
934+
def _build_program(
935+
self, op: torch._ops.OpOverload, bias_scale: float, bias: torch.Tensor
936+
) -> tuple[ExportedProgram, torch.fx.Node]:
937+
"""A dq -> op(input, weight, bias) -> q program, the bias at bias_scale."""
938+
out_channels = bias.numel()
939+
is_conv = op == torch.ops.aten.conv1d.default
940+
builder = ProgramBuilder()
941+
x_q = builder.placeholder(
942+
"x_q",
943+
torch.randint(-8, 8, (1, 3, 5) if is_conv else (2, 3), dtype=torch.int8),
944+
)
945+
w_q = builder.placeholder(
946+
"w_q",
947+
torch.randint(
948+
-8, 8, (out_channels, 3, 1) if is_conv else (out_channels, 3)
949+
).to(torch.int8),
950+
input_kind=InputKind.CONSTANT_TENSOR,
951+
)
952+
b_q = builder.placeholder("b_q", bias, input_kind=InputKind.CONSTANT_TENSOR)
953+
dq_input = builder.call_operator(
954+
op=DQ_PER_TENSOR, args=(x_q, self.INPUT_SCALE, 0, -128, 127, torch.int8)
955+
)
956+
dq_weight = builder.call_operator(
957+
op=DQ_PER_TENSOR, args=(w_q, self.WEIGHT_SCALE, 0, -128, 127, torch.int8)
958+
)
959+
dq_bias = builder.call_operator(
960+
op=DQ_PER_TENSOR,
961+
args=(b_q, bias_scale, 0, -(2**31), 2**31 - 1, torch.int32),
962+
)
963+
anchor = builder.call_operator(op=op, args=(dq_input, dq_weight, dq_bias))
964+
q = builder.call_operator(
965+
op=Q_PER_TENSOR, args=(anchor, 0.2, 0, -128, 127, torch.int8)
966+
)
967+
builder.output([q])
968+
ep = builder.get_program()
969+
ep.graph_module.meta[EXPORTED_PROGRAM_META_KEY] = ep
970+
return ep, ep.graph.find_nodes(op="call_function", target=op)[0]
971+
972+
def _fused_bias(
973+
self, op: torch._ops.OpOverload, bias_scale: float, bias: torch.Tensor
974+
) -> tuple[ExportedProgram, torch.fx.Node]:
975+
ep, anchor = self._build_program(op, bias_scale, bias)
976+
pattern = (
977+
Conv1dPattern() if op == torch.ops.aten.conv1d.default else LinearPattern()
978+
)
979+
fused = pattern.fuse(ep.graph_module, anchor)
980+
self.assertIsNotNone(fused)
981+
bias_node = cast(torch.fx.Node, fused).args[2]
982+
self.assertIsInstance(bias_node, torch.fx.Node)
983+
return ep, cast(torch.fx.Node, bias_node)
984+
985+
def test_linear_rescales_a_bias_quantized_for_another_input_scale(self) -> None:
986+
# The bias was quantized at 0.4 times the accumulator scale of this call.
987+
bias_scale = 0.4 * self.INPUT_SCALE * self.WEIGHT_SCALE
988+
ep, bias_node = self._fused_bias(
989+
torch.ops.aten.linear.default, bias_scale, self.BIAS
990+
)
991+
992+
rescaled = resolve_constant(ep.graph_module, bias_node)
993+
994+
self.assertIsNotNone(rescaled)
995+
self.assertTrue(
996+
torch.equal(
997+
cast(torch.Tensor, rescaled),
998+
torch.tensor([40, -20, 10, 0], dtype=torch.int32),
999+
)
1000+
)
1001+
1002+
def test_conv_rescales_a_bias_quantized_for_another_input_scale(self) -> None:
1003+
bias_scale = 2.0 * self.INPUT_SCALE * self.WEIGHT_SCALE
1004+
ep, bias_node = self._fused_bias(
1005+
torch.ops.aten.conv1d.default, bias_scale, self.BIAS
1006+
)
1007+
1008+
rescaled = resolve_constant(ep.graph_module, bias_node)
1009+
1010+
self.assertIsNotNone(rescaled)
1011+
self.assertTrue(
1012+
torch.equal(
1013+
cast(torch.Tensor, rescaled),
1014+
torch.tensor([200, -100, 50, 0], dtype=torch.int32),
1015+
)
1016+
)
1017+
1018+
def test_bias_at_the_accumulator_scale_is_used_as_is(self) -> None:
1019+
_, bias_node = self._fused_bias(
1020+
torch.ops.aten.linear.default,
1021+
self.INPUT_SCALE * self.WEIGHT_SCALE,
1022+
self.BIAS,
1023+
)
1024+
1025+
self.assertEqual(bias_node.name, "b_q")
1026+
1027+
def test_rescaling_past_int32_raises(self) -> None:
1028+
bias = torch.tensor([2**30, 0, 0, 0], dtype=torch.int32)
1029+
with self.assertRaisesRegex(AssertionError, "does not fit in int32"):
1030+
self._fused_bias(
1031+
torch.ops.aten.linear.default,
1032+
4.0 * self.INPUT_SCALE * self.WEIGHT_SCALE,
1033+
bias,
1034+
)

0 commit comments

Comments
 (0)