-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy path_matmul_add_to_gemm_test.py
More file actions
316 lines (267 loc) · 11 KB
/
_matmul_add_to_gemm_test.py
File metadata and controls
316 lines (267 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import unittest
from typing import Sequence
import numpy as np
import onnx
from onnx_ir.passes.common import onnx_checker, shape_inference
from parameterized import parameterized
from onnxscript import ir
from onnxscript.rewriter import MatchingTracer, MatchStatus, testing
from onnxscript.rewriter.rules.common import _matmul_add_to_gemm
class _MatMulAddToGemmTestBase(unittest.TestCase):
@property
def rng(self):
return np.random.default_rng(20250607)
def clone_model(self, model: ir.Model) -> ir.Model:
return ir.from_proto(ir.to_proto(model))
def get_test_model(
self,
input_shape: ir.Shape,
weight_shape: ir.Shape,
transA: bool = False,
transB: bool = False,
permA: Sequence[int] = [1, 0],
permB: Sequence[int] = [1, 0],
weight_as_inputs: bool = False,
bias_as_inputs: bool = False,
):
"""Returns the following model:
Y = Add(MatMul(Transpose(X), Transpose(W)), B)
Where:
- Transpose(X) is applied only if `transA=True`
- Transpose(W) is applied only if `transB=True`
- W and B can be graph inputs or initializers
"""
tape = ir.tape.Tape()
inputs = []
bias_shape = weight_shape[0] if transB else weight_shape[-1]
output_shape = ir.Shape(("?",) * input_shape.rank())
x = ir.val("X", shape=input_shape, type=ir.TensorType(ir.DataType.FLOAT))
if weight_as_inputs:
w = ir.val("W", shape=weight_shape, type=ir.TensorType(ir.DataType.FLOAT))
inputs.append(w)
else:
w = ir.tensor(
self.rng.uniform(-0.5, 0.5, weight_shape).astype("float32"), name="W"
)
w = tape.initializer(w)
if bias_as_inputs:
b = ir.val(
"B", shape=ir.Shape([bias_shape]), type=ir.TensorType(ir.DataType.FLOAT)
)
inputs.append(b)
else:
b = ir.tensor(self.rng.uniform(-0.5, 0.5, bias_shape).astype("float32"), name="B")
b = tape.initializer(b)
x_t, w_t = None, None
if transA:
x_t = tape.op("Transpose", inputs=[x], attributes={"perm": permA})
if transB:
w_t = tape.op("Transpose", inputs=[w], attributes={"perm": permB})
y = tape.op("MatMul", inputs=[x_t if transA else x, w_t if transB else w])
y = tape.op(
"Add",
inputs=[y, b],
output=ir.val("Y", shape=output_shape, type=ir.TensorType(ir.DataType.FLOAT)),
)
# Build the model
ir_model = ir.Model(
ir.Graph(
inputs=[x, *inputs],
outputs=[y],
nodes=tape.nodes,
initializers=tape.initializers,
opset_imports={"": 20},
name="test_model",
),
ir_version=10,
)
onnx_checker.CheckerPass(True)(ir_model)
ir_model = shape_inference.infer_shapes(ir_model)
return ir_model
def check_matmul_add_to_gemm_incompatible_shapes(self, **kwargs):
base_model = self.get_test_model(**kwargs)
updated_model = self.clone_model(base_model)
tracer = MatchingTracer()
count = _matmul_add_to_gemm.matmul_add_to_gemm_rule.apply_to_model(
updated_model, tracer=tracer
)
# Check that the model is unchanged
self.assertEqual(count, 0)
# Check that the error message is the expected one
tracer_match = tracer.best_matches_map[_matmul_add_to_gemm.matmul_add_to_gemm_rule][0]
self.assertEqual(tracer_match.status.value, MatchStatus.CONDITION_FAILED)
self.assertRegex(
tracer_match.match_result.reason, "Rank of input_a and input_b must be 2"
)
class MatMulAddToGemmTest(_MatMulAddToGemmTestBase):
@parameterized.expand(
[
("initializers", False, False),
("inputs", True, True),
]
)
def test_matmul_add_to_gemm(self, _, weight_as_inputs, bias_as_inputs):
base_model = self.get_test_model(
input_shape=ir.Shape((512, 256)),
weight_shape=ir.Shape((256, 64)),
weight_as_inputs=weight_as_inputs,
bias_as_inputs=bias_as_inputs,
)
updated_model = self.clone_model(base_model)
count = _matmul_add_to_gemm.rules.apply_to_model(updated_model)
# Check MatMul + Add are fused into Gemm
self.assertEqual(count, 1)
self.assertEqual(len(updated_model.graph), 1)
# Prepare inputs
if weight_as_inputs and bias_as_inputs:
inputs = (
self.rng.random((512, 256), dtype=np.float32),
self.rng.random((256, 64), dtype=np.float32),
self.rng.random((64), dtype=np.float32),
)
else:
inputs = (self.rng.random((512, 256), dtype=np.float32),)
# Check inference
testing.assert_numerically_equal(base_model, updated_model, inputs)
# Validate serialized model
output_model_proto = ir.serde.serialize_model(updated_model)
onnx.checker.check_model(output_model_proto, full_check=True)
def test_matmul_add_to_gemm_incompatible_shapes(self):
kwargs = {
"input_shape": ir.Shape((1, 256, 512)),
"weight_shape": ir.Shape((1, 512, 64)),
}
return super().check_matmul_add_to_gemm_incompatible_shapes(**kwargs)
class TransAMatMulAddToGemmTest(_MatMulAddToGemmTestBase):
@parameterized.expand(
[
("initializers", False, False),
("inputs", True, True),
]
)
def test_transpose_a_matmul_add_to_gemm(self, _, weight_as_inputs, bias_as_inputs):
base_model = self.get_test_model(
input_shape=ir.Shape((256, 512)),
weight_shape=ir.Shape((256, 64)),
weight_as_inputs=weight_as_inputs,
bias_as_inputs=bias_as_inputs,
transA=True,
)
updated_model = self.clone_model(base_model)
count = _matmul_add_to_gemm.rules.apply_to_model(updated_model)
# Check MatMul(Transpose, W) + Add are fused into Gemm
self.assertEqual(count, 1)
self.assertEqual(len(updated_model.graph), 1)
# Prepare inputs
if weight_as_inputs and bias_as_inputs:
inputs = (
self.rng.random((256, 512), dtype=np.float32),
self.rng.random((256, 64), dtype=np.float32),
self.rng.random((64,), dtype=np.float32),
)
else:
inputs = (self.rng.random((256, 512), dtype=np.float32),)
# Check inference
testing.assert_numerically_equal(base_model, updated_model, inputs)
# Validate serialized model
output_model_proto = ir.serde.serialize_model(updated_model)
onnx.checker.check_model(output_model_proto, full_check=True)
def test_transpose_a_matmul_add_to_gemm_incompatible_shapes(self):
kwargs = {
"input_shape": ir.Shape((1, 256, 512)),
"weight_shape": ir.Shape((1, 256, 64)),
"transA": True,
"permA": [0, 2, 1],
}
return super().check_matmul_add_to_gemm_incompatible_shapes(**kwargs)
class TransBMatMulAddToGemmTest(_MatMulAddToGemmTestBase):
@parameterized.expand(
[
("initializers", False, False),
("inputs", True, True),
]
)
def test_transpose_b_matmul_add_to_gemm(self, _, weight_as_inputs, bias_as_inputs):
base_model = self.get_test_model(
input_shape=ir.Shape((512, 256)),
weight_shape=ir.Shape((64, 256)),
weight_as_inputs=weight_as_inputs,
bias_as_inputs=bias_as_inputs,
transB=True,
)
updated_model = self.clone_model(base_model)
count = _matmul_add_to_gemm.rules.apply_to_model(updated_model)
# Check MatMul(X, Transpose) + Add are fused into Gemm
self.assertEqual(count, 1)
self.assertEqual(len(updated_model.graph), 1)
# Prepare inputs
if weight_as_inputs and bias_as_inputs:
inputs = (
self.rng.random((512, 256), dtype=np.float32),
self.rng.random((64, 256), dtype=np.float32),
self.rng.random((64,), dtype=np.float32),
)
else:
inputs = (self.rng.random((512, 256), dtype=np.float32),)
# Check inference
testing.assert_numerically_equal(base_model, updated_model, inputs)
# Validate serialized model
output_model_proto = ir.serde.serialize_model(updated_model)
onnx.checker.check_model(output_model_proto, full_check=True)
def test_transpose_b_matmul_add_to_gemm_incompatible_shapes(self):
kwargs = {
"input_shape": ir.Shape((1, 512, 256)),
"weight_shape": ir.Shape((1, 64, 256)),
"transB": True,
"permB": [0, 2, 1],
}
return super().check_matmul_add_to_gemm_incompatible_shapes(**kwargs)
class TransABMatMulAddToGemmTest(_MatMulAddToGemmTestBase):
@parameterized.expand(
[
("initializers", False, False),
("inputs", True, True),
]
)
def test_transpose_ab_matmul_add_to_gemm(self, _, weight_as_inputs, bias_as_inputs):
base_model = self.get_test_model(
input_shape=ir.Shape((256, 512)),
weight_shape=ir.Shape((64, 256)),
weight_as_inputs=weight_as_inputs,
bias_as_inputs=bias_as_inputs,
transA=True,
transB=True,
)
updated_model = self.clone_model(base_model)
count = _matmul_add_to_gemm.rules.apply_to_model(updated_model)
# Check MatMul(Transpose, Transpose) + Add are fused into Gemm
self.assertEqual(count, 1)
self.assertEqual(len(updated_model.graph), 1)
# Prepare inputs
if weight_as_inputs and bias_as_inputs:
inputs = (
self.rng.random((256, 512), dtype=np.float32),
self.rng.random((64, 256), dtype=np.float32),
self.rng.random((64), dtype=np.float32),
)
else:
inputs = (self.rng.random((256, 512), dtype=np.float32),)
# Check inference
testing.assert_numerically_equal(base_model, updated_model, inputs)
# Validate serialized model
output_model_proto = ir.serde.serialize_model(updated_model)
onnx.checker.check_model(output_model_proto, full_check=True)
def test_transpose_ab_matmul_add_to_gemm_incompatible_shapes(self):
kwargs = {
"input_shape": ir.Shape((1, 256, 512)),
"weight_shape": ir.Shape((1, 64, 256)),
"transA": True,
"transB": True,
"permA": [0, 2, 1],
"permB": [0, 2, 1],
}
return super().check_matmul_add_to_gemm_incompatible_shapes(**kwargs)
if __name__ == "__main__":
unittest.main()