Skip to content

Commit 2ca252a

Browse files
committed
[Backend Tester] Add FACTO operator test skeleton
ghstack-source-id: 101d2b7 ghstack-comment-id: 3003288787 Pull-Request: #11953
1 parent 91c9ffa commit 2ca252a

File tree

4 files changed

+346
-10
lines changed

4 files changed

+346
-10
lines changed

backends/test/operators/__init__.py

Whitespace-only changes.
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import facto.specdb.function as fn
2+
import torch
3+
4+
from facto.inputgen.argument.type import ArgType
5+
from facto.inputgen.specs.model import ConstraintProducer as cp, InPosArg, OutArg, Spec
6+
7+
"""
8+
This file contains FACTO operator specs for ops not in the standard FACTO db. This mainly
9+
includes ops not in the Core ATen op set and preserved by a backend, such as linear.
10+
"""
11+
12+
LiNEAR_DEFAULT_SPEC = Spec(
13+
op="linear.default", # (Tensor input, Tensor weight, Tensor? bias=None) -> Tensor
14+
inspec=[
15+
InPosArg(
16+
ArgType.Tensor,
17+
name="input",
18+
deps=[1, 2],
19+
constraints=[
20+
cp.Dtype.Eq(lambda deps: deps[0].dtype),
21+
cp.Rank.Ge(lambda deps: 2),
22+
cp.Size.In(
23+
lambda deps, r, d: fn.broadcast_to(
24+
(fn.safe_size(deps[0], 0), fn.safe_size(deps[1], 1)), r, d
25+
)
26+
),
27+
],
28+
),
29+
InPosArg(
30+
ArgType.Tensor,
31+
name="weight",
32+
constraints=[
33+
cp.Dtype.Ne(lambda deps: torch.bool),
34+
cp.Rank.Eq(lambda deps: 2),
35+
],
36+
),
37+
InPosArg(
38+
ArgType.Tensor,
39+
name="bias",
40+
deps=[1],
41+
constraints=[
42+
cp.Dtype.Eq(lambda deps: deps[0].dtype),
43+
cp.Rank.Eq(lambda deps: 2),
44+
cp.Size.Eq(
45+
lambda deps, r, d: fn.safe_size(deps[0], 1) if d == 0 else None
46+
),
47+
],
48+
),
49+
],
50+
outspec=[
51+
OutArg(ArgType.Tensor),
52+
],
53+
)
54+
55+
_extra_specs = [
56+
LiNEAR_DEFAULT_SPEC,
57+
]
58+
59+
ExtraSpecDB: dict[str, Spec] = {s.op: s for s in _extra_specs}
Lines changed: 278 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
1+
# Copyright (c) Meta Platforms, Inc. and affiliates.
2+
# All rights reserved.
3+
#
4+
# This source code is licensed under the BSD-style license found in the
5+
# LICENSE file in the root directory of this source tree.
6+
7+
# pyre-strict
8+
9+
import copy
10+
import functools
11+
import traceback
12+
import unittest
13+
from typing import Any, Callable, Sequence
14+
15+
import torch
16+
from executorch.backends.apple.coreml.test.tester import CoreMLTester
17+
from executorch.backends.test.harness.tester import Tester as TesterBase
18+
from executorch.backends.xnnpack.test.tester.tester import Tester as XnnpackTester
19+
from facto.inputgen.argtuple.gen import ArgumentTupleGenerator
20+
from facto.inputgen.specs.model import ConstraintProducer as cp, Spec
21+
from facto.inputgen.utils.random_manager import random_manager
22+
from facto.specdb.db import SpecDictDB
23+
from torch._ops import OpOverload
24+
25+
from .facto_specs import ExtraSpecDB
26+
27+
CombinedSpecDB = SpecDictDB | ExtraSpecDB
28+
29+
COMMON_TENSOR_CONSTRAINTS = [
30+
cp.Rank.Ge(lambda deps: 1), # Avoid zero and high rank tensors.
31+
cp.Rank.Le(lambda deps: 4),
32+
cp.Size.Ge(lambda deps, r, d: 1), # Keep sizes reasonable.
33+
cp.Size.Le(lambda deps, r, d: 2**9),
34+
]
35+
36+
COMMON_SCALAR_CONSTRAINS = [
37+
cp.Value.Ge(lambda deps, dtype: -1000),
38+
cp.Value.Le(lambda deps, dtype: 1000),
39+
]
40+
41+
# Operator args are treated as runtime graph inputs if the argument name is
42+
# in this list.
43+
RUNTIME_INPUT_NAMES = {
44+
"self",
45+
"tensor",
46+
"other",
47+
}
48+
49+
50+
def _patch_spec(spec: Spec) -> Spec:
51+
spec = copy.deepcopy(spec)
52+
for inspec in spec.inspec:
53+
if inspec.type.is_tensor():
54+
inspec.constraints.extend(COMMON_TENSOR_CONSTRAINTS)
55+
elif inspec.type.is_scalar():
56+
inspec.constraints.extend(COMMON_SCALAR_CONSTRAINS)
57+
return spec
58+
59+
60+
class OpModel(torch.nn.Module):
61+
"""
62+
Wraps a single torch operator in an nn.Module.
63+
"""
64+
65+
def __init__(
66+
self,
67+
op: OpOverload,
68+
runtime_input_count: int,
69+
fixed_args: Sequence[Any],
70+
fixed_kwargs: dict[str, Any],
71+
):
72+
super().__init__()
73+
self.op = op
74+
self.runtime_input_count = runtime_input_count
75+
self.fixed_kwargs = fixed_kwargs
76+
77+
# Register parameters for fixed tensors. Some things will choke on
78+
# constant tensor weights, for example.
79+
new_args = []
80+
for i, arg in enumerate(fixed_args):
81+
if isinstance(arg, torch.Tensor):
82+
param = torch.nn.Parameter(arg, requires_grad=False)
83+
param_name = f"arg_{i}_param"
84+
setattr(self, param_name, param)
85+
self.register_parameter(param_name, param)
86+
new_args.append(param)
87+
else:
88+
new_args.append(arg)
89+
self.fixed_args = tuple(new_args)
90+
91+
def forward(self, *args, **kwargs):
92+
return self.op(*(args + self.fixed_args), **(kwargs | self.fixed_kwargs))
93+
94+
95+
class ConvModel(OpModel):
96+
def forward(self, *args, **kwargs):
97+
weight, bias, stride, padding, dilation, transposed, output_padding, groups = (
98+
self.fixed_args
99+
)
100+
101+
if not transposed:
102+
if len(weight.shape) == 3:
103+
op = torch.nn.functional.conv1d
104+
elif len(weight.shape) == 4:
105+
op = torch.nn.functional.conv2d
106+
elif len(weight.shape) == 5:
107+
op = torch.nn.functional.conv3d
108+
109+
return op(args[0], weight, bias, stride, padding, dilation, groups)
110+
else:
111+
if len(weight.shape) == 3:
112+
op = torch.nn.functional.conv_transpose1d
113+
elif len(weight.shape) == 4:
114+
op = torch.nn.functional.conv_transpose2d
115+
elif len(weight.shape) == 5:
116+
op = torch.nn.functional.conv_transpose3d
117+
118+
return op(
119+
args[0], weight, bias, stride, padding, output_padding, groups, dilation
120+
)
121+
122+
123+
def get_module_for_op(op: OpOverload):
124+
if op == torch.ops.aten.convolution.default:
125+
return ConvModel
126+
else:
127+
return OpModel
128+
129+
130+
class FactoTestsBase(unittest.TestCase):
131+
def __init__(self, tester_factory: Callable[[], TesterBase], *args, **kwargs):
132+
super().__init__(*args, **kwargs)
133+
self._tester_factory = tester_factory
134+
135+
@staticmethod
136+
def _generate_test(op_name: str) -> None:
137+
# Find the torch op with the given name.
138+
sections = op_name.split(".")
139+
torch_op = functools.reduce(getattr, sections, torch.ops.aten)
140+
141+
test_name = "test_" + op_name.replace(".", "_")
142+
143+
def test_body(self):
144+
self._test_op(torch_op)
145+
146+
setattr(FactoTestsBase, test_name, test_body)
147+
148+
@staticmethod
149+
def get_runtime_input_count(spec: Spec):
150+
# Determine which inputs are fixed at tracing time (weights, for example),
151+
# vs inputs to the runtime graph. We currently assume that the runtime graph
152+
# inputs start at the beginning of the arg list and are contiguous.
153+
#
154+
# Args are consider to be runtime inputs if they are positional and are named
155+
# one of RUNTIME_INPUT_NAMES. If none match, we assume only the first arg is a
156+
# runtime input.
157+
runtime_input_count = 0
158+
for inspec in spec.inspec:
159+
is_runtime_input = (
160+
inspec.type.is_tensor() and inspec.name.lower() in RUNTIME_INPUT_NAMES
161+
)
162+
if is_runtime_input:
163+
runtime_input_count += 1
164+
else:
165+
break
166+
167+
return max(1, runtime_input_count)
168+
169+
def setUp(self):
170+
torch.set_printoptions(threshold=3)
171+
172+
def _test_op(self, op: OpOverload) -> None: # noqa: C901
173+
random_manager.seed(0)
174+
175+
# Strip namespace
176+
op_name = op.name().split("::")[-1]
177+
178+
# Default to .default overload
179+
if "." not in op_name:
180+
op_name += ".default"
181+
182+
# Find and patch op spec
183+
if op_name not in CombinedSpecDB:
184+
raise ValueError(f"Operator {op_name} not found in SpecDictDB.")
185+
spec = _patch_spec(CombinedSpecDB[op_name])
186+
187+
runtime_input_count = FactoTestsBase.get_runtime_input_count(spec)
188+
189+
print(f"Op: {op_name}, {runtime_input_count} runtime inputs")
190+
191+
# Run test cases
192+
success_count_delegated = 0
193+
success_count_undelegated = 0
194+
fail_count = 0
195+
196+
i = 0
197+
for posargs, inkwargs, _ in ArgumentTupleGenerator(spec).gen():
198+
i += 1
199+
200+
try:
201+
if isinstance(posargs[0], torch.Tensor):
202+
# Temporary for getting around XNN crashes
203+
if posargs[0].dtype not in {torch.float32, torch.float16}:
204+
print("SKIPPING NON FLOAT CASE")
205+
continue
206+
207+
module_cls = get_module_for_op(op)
208+
model = module_cls(
209+
op, runtime_input_count, posargs[runtime_input_count:], inkwargs
210+
)
211+
212+
# Sanity check to make sure it runs in eager. This can present nicer error
213+
# messages sometimes compared to tracing.
214+
try:
215+
model(*posargs[:runtime_input_count])
216+
except Exception as e:
217+
print(f"Eager execution failed: {e}")
218+
continue
219+
220+
tester = (
221+
self._tester_factory(model, tuple(posargs[:runtime_input_count]))
222+
.export()
223+
.dump_artifact()
224+
.to_edge_transform_and_lower()
225+
)
226+
227+
is_delegated = any(
228+
n.target == torch._higher_order_ops.executorch_call_delegate
229+
for n in tester.stages[tester.cur].graph_module.graph.nodes
230+
if n.op == "call_function"
231+
)
232+
233+
# Only run the runtime test if the op was delegated.
234+
if is_delegated:
235+
(
236+
tester.to_executorch()
237+
.serialize()
238+
.run_method_and_compare_outputs()
239+
)
240+
241+
if is_delegated:
242+
success_count_delegated += 1
243+
else:
244+
success_count_undelegated += 1
245+
except Exception as e:
246+
fail_count += 1
247+
print(f"Error: {e}")
248+
print("Args:")
249+
for arg in posargs:
250+
if isinstance(arg, torch.Tensor):
251+
print(f" {arg.dtype} {arg.shape}")
252+
else:
253+
print(f" {arg}")
254+
255+
traceback.print_exc()
256+
257+
print(
258+
f"{success_count_delegated + success_count_undelegated} PASS, {fail_count} FAIL"
259+
)
260+
print(
261+
f" {success_count_delegated} DELEGATED, {success_count_undelegated} UNDELEGATED"
262+
)
263+
264+
265+
# Programatically generate tests for each operator.
266+
for op_name in CombinedSpecDB.keys():
267+
FactoTestsBase._generate_test(op_name)
268+
269+
270+
# TODO Figure out where to put these
271+
class FactoTestsXNNPACK(FactoTestsBase):
272+
def __init__(self, *args, **kwargs):
273+
super().__init__(XnnpackTester, *args, **kwargs)
274+
275+
276+
class FactoTestsCoreML(FactoTestsBase):
277+
def __init__(self, *args, **kwargs):
278+
super().__init__(CoreMLTester, *args, **kwargs)

backends/xnnpack/test/tester/__init__.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
# This source code is licensed under the BSD-style license found in the
55
# LICENSE file in the root directory of this source tree.
66

7-
# TODO: Be more delibrate on module structure
87
from executorch.backends.xnnpack.test.tester.tester import (
98
Export,
109
Partition,
@@ -18,13 +17,13 @@
1817
)
1918

2019
__all__ = [
21-
Export,
22-
ToEdge,
23-
Partition,
24-
Quantize,
25-
RunPasses,
26-
ToEdgeTransformAndLower,
27-
Tester,
28-
Serialize,
29-
ToExecutorch,
20+
"Export",
21+
"ToEdge",
22+
"Partition",
23+
"Quantize",
24+
"RunPasses",
25+
"ToEdgeTransformAndLower",
26+
"Tester",
27+
"Serialize",
28+
"ToExecutorch",
3029
]

0 commit comments

Comments
 (0)