-
Notifications
You must be signed in to change notification settings - Fork 994
Expand file tree
/
Copy pathtest_batch_norm.py
More file actions
408 lines (345 loc) · 14 KB
/
test_batch_norm.py
File metadata and controls
408 lines (345 loc) · 14 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import torch
from executorch.backends.xnnpack.test.test_xnnpack_utils import randomize_bn
from executorch.backends.xnnpack.test.tester import Tester
class TestBatchNorm(unittest.TestCase):
"""
End-to-end tests for standalone BatchNorm operators lowered to XNNPACK.
"""
def setUp(self):
torch._dynamo.reset()
class BatchNorm1dNC(torch.nn.Module):
"""BatchNorm1d with NC input (batch, channels)."""
def __init__(self, num_features: int):
super().__init__()
self.num_features = num_features
self.bn = torch.nn.BatchNorm1d(num_features)
def forward(self, x):
return self.bn(x)
def get_inputs(self):
return (torch.randn(2, self.num_features),)
class BatchNorm1dNCL(torch.nn.Module):
"""BatchNorm1d with NCL input (batch, channels, length)."""
def __init__(self, num_features: int):
super().__init__()
self.num_features = num_features
self.bn = torch.nn.BatchNorm1d(num_features)
def forward(self, x):
return self.bn(x)
def get_inputs(self):
return (torch.randn(2, self.num_features, 8),)
class BatchNorm2d(torch.nn.Module):
"""BatchNorm2d with NCHW input (batch, channels, height, width)."""
def __init__(
self,
num_features: int,
dtype: torch.dtype = torch.float,
affine: bool = True,
):
super().__init__()
self.num_features = num_features
self.dtype = dtype
self.bn = torch.nn.BatchNorm2d(num_features, affine=affine).to(dtype)
def forward(self, x):
return self.bn(x)
def get_inputs(self):
return (torch.randn(2, self.num_features, 4, 4).to(self.dtype),)
def _test_batch_norm(self, model: torch.nn.Module):
"""
Test that a standalone BatchNorm is lowered to XNNPACK via decomposition
to depthwise convolution.
"""
# Warm up batch norm running stats
model.eval()
with torch.no_grad():
for _ in range(5):
model(*model.get_inputs())
(
Tester(model, model.get_inputs())
.export()
.to_edge_transform_and_lower()
.check_not(
[
"executorch_exir_dialects_edge__ops_aten__native_batch_norm_legit_no_training_default"
]
)
.check_count({"torch.ops.higher_order.executorch_call_delegate": 1})
.to_executorch()
.serialize()
.run_method_and_compare_outputs()
)
class LinearReluBatchNorm(torch.nn.Module):
"""
Linear followed by ReLU, BatchNorm, residual add, and a second Linear.
The BatchNorm is standalone (not fused) because ReLU breaks the fusion pattern.
"""
def __init__(self, features: int):
super().__init__()
self.features = features
self.linear1 = torch.nn.Linear(features, features)
self.relu = torch.nn.ReLU()
self.bn = randomize_bn(features, dimensionality=1)
self.linear2 = torch.nn.Linear(features, features)
def forward(self, x):
y = self.linear1(x)
y = self.relu(y)
y = self.bn(y)
y = y + x
y = self.linear2(y)
return y
def get_inputs(self):
return (torch.randn(2, self.features),)
def test_fp32_linear_relu_batch_norm(self):
"""
Test Linear + ReLU + BatchNorm where the BatchNorm is standalone (not fused
with linear) because ReLU breaks the fusion pattern. The standalone BatchNorm
should be decomposed to depthwise convolution.
"""
model = self.LinearReluBatchNorm(features=8)
model.eval()
(
Tester(model, model.get_inputs())
.export()
.to_edge_transform_and_lower()
# BatchNorm should be decomposed (not present in the graph)
.check_not(
[
"executorch_exir_dialects_edge__ops_aten__native_batch_norm_legit_no_training_default"
]
)
.check_count({"torch.ops.higher_order.executorch_call_delegate": 1})
.to_executorch()
.serialize()
.run_method_and_compare_outputs()
)
def test_fp32_batch_norm_nc(self):
"""Test BatchNorm1d with NC input is lowered to XNNPACK."""
self._test_batch_norm(self.BatchNorm1dNC(num_features=3))
def test_fp32_batch_norm_nc_dynamic_batch(self):
"""Test BatchNorm1d NC with dynamic batch, inference at batch=20."""
model = self.BatchNorm1dNC(num_features=3)
model.eval()
with torch.no_grad():
for _ in range(5):
model(*model.get_inputs())
batch = torch.export.Dim("batch", min=1, max=32)
(
Tester(
model,
model.get_inputs(),
dynamic_shapes=({0: batch},),
)
.export()
.to_edge_transform_and_lower()
.check_not(
[
"executorch_exir_dialects_edge__ops_aten__native_batch_norm_legit_no_training_default"
]
)
.check_count({"torch.ops.higher_order.executorch_call_delegate": 1})
.to_executorch()
.serialize()
.run_method_and_compare_outputs(inputs=(torch.randn(20, 3),))
)
def test_fp32_batch_norm_ncl(self):
"""Test BatchNorm1d with NCL input is lowered to XNNPACK."""
self._test_batch_norm(self.BatchNorm1dNCL(num_features=3))
def test_fp32_batch_norm_nchw(self):
"""Test BatchNorm2d with NCHW input is lowered to XNNPACK."""
self._test_batch_norm(self.BatchNorm2d(num_features=3))
def test_fp16_batch_norm_nchw(self):
"""Test BatchNorm2d with fp16 NCHW input is lowered to XNNPACK."""
self._test_batch_norm(self.BatchNorm2d(num_features=3, dtype=torch.float16))
def test_fp32_batch_norm_nchw_non_affine(self):
"""Test non-affine BatchNorm2d with NCHW input is lowered to XNNPACK."""
self._test_batch_norm(self.BatchNorm2d(num_features=3, affine=False))
class BatchNorm2dChannelsLast(torch.nn.Module):
"""BatchNorm2d with channels_last memory format input."""
def __init__(self, num_features: int):
super().__init__()
self.num_features = num_features
self.bn = torch.nn.BatchNorm2d(num_features)
def forward(self, x):
return self.bn(x)
def get_inputs(self):
return (
torch.randn(2, self.num_features, 4, 4).to(
memory_format=torch.channels_last
),
)
def test_fp32_batch_norm_nchw_channels_last(self):
"""Test BatchNorm2d with channels_last memory format input is lowered to XNNPACK."""
self._test_batch_norm(self.BatchNorm2dChannelsLast(num_features=3))
class BatchNorm3d(torch.nn.Module):
"""BatchNorm3d with NCDHW input (batch, channels, depth, height, width)."""
def __init__(self, num_features: int):
super().__init__()
self.num_features = num_features
self.bn = torch.nn.BatchNorm3d(num_features)
def forward(self, x):
return self.bn(x)
def get_inputs(self):
return (torch.randn(2, self.num_features, 4, 4, 4),)
def test_fp32_batch_norm3d_not_partitioned(self):
"""Test that BatchNorm3d is NOT partitioned to XNNPACK (unsupported)."""
model = self.BatchNorm3d(num_features=3)
model.eval()
with torch.no_grad():
for _ in range(5):
model(*model.get_inputs())
(
Tester(model, model.get_inputs())
.export()
.to_edge_transform_and_lower()
# BatchNorm3d should remain in the graph (not lowered to XNNPACK)
.check(
[
"executorch_exir_dialects_edge__ops_aten__native_batch_norm_legit_no_training_default"
]
)
# No delegate call should be present since nothing was partitioned
.check_not(["torch.ops.higher_order.executorch_call_delegate"])
.to_executorch()
.serialize()
.run_method_and_compare_outputs()
)
class Conv2dReluBatchNorm(torch.nn.Module):
"""Conv2d followed by ReLU and then BatchNorm (standalone BN, not fused)."""
def __init__(self, in_channels: int, out_channels: int):
super().__init__()
self.in_channels = in_channels
self.conv = torch.nn.Conv2d(
in_channels, out_channels, kernel_size=3, padding=1
)
self.relu = torch.nn.ReLU()
self.bn = randomize_bn(out_channels)
def forward(self, x):
x = self.conv(x)
x = self.relu(x)
x = self.bn(x)
return x
def get_inputs(self):
return (torch.randn(2, self.in_channels, 8, 8),)
def test_fp32_conv2d_relu_batch_norm(self):
"""
Test Conv2d + ReLU + BatchNorm where the BatchNorm is standalone (not fused
with conv) because ReLU breaks the fusion pattern. The standalone BatchNorm
should be decomposed to depthwise convolution.
"""
model = self.Conv2dReluBatchNorm(in_channels=3, out_channels=8)
model.eval()
(
Tester(model, model.get_inputs())
.export()
.to_edge_transform_and_lower()
# BatchNorm should be decomposed (not present in the graph)
.check_not(
[
"executorch_exir_dialects_edge__ops_aten__native_batch_norm_legit_no_training_default"
]
)
.check_count({"torch.ops.higher_order.executorch_call_delegate": 1})
.to_executorch()
.serialize()
.run_method_and_compare_outputs()
)
class Conv2dBatchNorm(torch.nn.Module):
"""Conv2d followed by BatchNorm (fuseable pattern)."""
def __init__(self, in_channels: int, out_channels: int):
super().__init__()
self.in_channels = in_channels
self.conv = torch.nn.Conv2d(
in_channels, out_channels, kernel_size=3, padding=1
)
self.bn = randomize_bn(out_channels)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
return x
def get_inputs(self):
return (torch.randn(2, self.in_channels, 8, 8),)
def test_fp32_conv2d_batch_norm_fused(self):
"""
Test Conv2d + BatchNorm where the BatchNorm is fused into the Conv2d.
This tests the existing fusion path (not decomposition).
"""
model = self.Conv2dBatchNorm(in_channels=3, out_channels=8)
model.eval()
(
Tester(model, model.get_inputs())
.export()
.to_edge_transform_and_lower()
# BatchNorm should be fused into conv (not present in the graph)
.check_not(
[
"executorch_exir_dialects_edge__ops_aten__native_batch_norm_legit_no_training_default"
]
)
.check_count({"torch.ops.higher_order.executorch_call_delegate": 1})
.to_executorch()
.serialize()
.run_method_and_compare_outputs()
)
class Conv2dBatchNormChannelsLast(torch.nn.Module):
"""Conv2d followed by BatchNorm (fuseable pattern) with channels_last input."""
def __init__(self, in_channels: int, out_channels: int):
super().__init__()
self.in_channels = in_channels
self.conv = torch.nn.Conv2d(
in_channels, out_channels, kernel_size=3, padding=1
)
self.bn = randomize_bn(out_channels)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
return x
def get_inputs(self):
return (
torch.randn(2, self.in_channels, 8, 8).to(
memory_format=torch.channels_last
),
)
def test_fp32_conv2d_batch_norm_fused_channels_last(self):
"""
Test Conv2d + BatchNorm with channels_last input where the BatchNorm is
fused into the Conv2d.
"""
model = self.Conv2dBatchNormChannelsLast(in_channels=3, out_channels=8)
model.eval()
(
Tester(model, model.get_inputs())
.export()
.to_edge_transform_and_lower()
# BatchNorm should be fused into conv (not present in the graph)
.check_not(
[
"executorch_exir_dialects_edge__ops_aten__native_batch_norm_legit_no_training_default"
]
)
.check_count({"torch.ops.higher_order.executorch_call_delegate": 1})
.to_executorch()
.serialize()
.run_method_and_compare_outputs()
)
def test_training_bn_not_partitioned(self):
"""Test that training mode BatchNorm is not partitioned."""
model = self.BatchNorm2d(num_features=3)
for _ in range(5):
model(*model.get_inputs())
(
Tester(model, model.get_inputs(), training=True)
.export()
.to_edge_transform_and_lower()
.check(
[
"executorch_exir_dialects_edge__ops_aten__native_batch_norm_legit_functional"
]
)
.check_count({"torch.ops.higher_order.executorch_call_delegate": 0})
.run_method_and_compare_outputs()
)