forked from tile-ai/TileOPs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_instance_norm.py
More file actions
380 lines (318 loc) · 15 KB
/
Copy pathtest_instance_norm.py
File metadata and controls
380 lines (318 loc) · 15 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
from tileops.utils import get_backend_name
DEVICE = get_backend_name()
import inspect
import pytest
import torch
import torch.nn.functional as F
import yaml
from tests.test_base import FixtureBase, TestBase
from tileops.ops.norm.instance_norm import (
InstanceNormFwdOp,
InstanceNormFwdOpNoAffine,
)
from workloads.instance_norm import InstanceNormTest as _InstanceNormTestWorkload
class InstanceNormTest(_InstanceNormTestWorkload, TestBase):
def ref_program(self, x: torch.Tensor, weight: torch.Tensor,
bias: torch.Tensor) -> torch.Tensor:
return F.instance_norm(
x.float(),
weight=weight.float(),
bias=bias.float(),
eps=self.eps,
).to(x.dtype)
class InstanceNormFixture(FixtureBase):
PARAMS = [
("n, c, spatial, dtype, tune", [
# Small CI-friendly shapes -- fp32
pytest.param(2, 16, (8, 8), torch.float32, False, marks=pytest.mark.smoke),
# Small CI-friendly shapes -- fp16
pytest.param(2, 16, (8, 8), torch.float16, False, marks=pytest.mark.smoke),
# Small CI-friendly shapes -- bf16
pytest.param(2, 16, (8, 8), torch.bfloat16, False, marks=pytest.mark.smoke),
pytest.param(4, 8, (4, 4), torch.float32, False, marks=pytest.mark.full),
pytest.param(4, 8, (4, 4), torch.float16, False, marks=pytest.mark.full),
pytest.param(4, 8, (4, 4), torch.bfloat16, False, marks=pytest.mark.full),
# 1D spatial
pytest.param(2, 16, (16,), torch.float16, False, marks=pytest.mark.full),
# 3D spatial
pytest.param(2, 8, (4, 4, 4), torch.float16, False, marks=pytest.mark.full),
]),
]
def _get_tolerances(dtype: torch.dtype) -> tuple[float, float]:
if dtype == torch.float32:
return 1e-5, 1e-5
elif dtype == torch.float16:
return 1e-3, 1e-3
else: # bfloat16
return 1.6e-2, 1.6e-2
@InstanceNormFixture
def test_instance_norm_op(n: int, c: int, spatial: tuple,
dtype: torch.dtype, tune: bool) -> None:
test = InstanceNormTest(n, c, spatial, dtype)
op = InstanceNormFwdOp(N=n, C=c, spatial=spatial, dtype=dtype)
atol, rtol = _get_tolerances(dtype)
test.check(op, *test.gen_inputs(), atol=atol, rtol=rtol)
class InstanceNormNonContigFixture(FixtureBase):
PARAMS = [
("n, c, spatial, dtype", [
pytest.param(2, 16, (8, 8), torch.float16, marks=pytest.mark.smoke),
pytest.param(2, 16, (8, 8), torch.bfloat16, marks=pytest.mark.smoke),
]),
]
@InstanceNormNonContigFixture
def test_instance_norm_non_contiguous(n: int, c: int, spatial: tuple,
dtype: torch.dtype) -> None:
"""Test with non-contiguous input (sliced tensor)."""
shape = (n, c * 2, *spatial)
x_full = torch.randn(shape, dtype=dtype, device=DEVICE)
x = x_full[:, :c] # non-contiguous slice
weight = torch.randn(c, dtype=dtype, device=DEVICE)
bias = torch.randn(c, dtype=dtype, device=DEVICE)
op = InstanceNormFwdOp(N=n, C=c, spatial=spatial, dtype=dtype)
y_ref = F.instance_norm(
x.contiguous().float(),
weight=weight.float(), bias=bias.float(), eps=1e-5,
).to(dtype)
y = op(x, weight, bias)
atol, rtol = _get_tolerances(dtype)
assert torch.allclose(y, y_ref, atol=atol, rtol=rtol), \
f"Non-contiguous test failed, max err: {(y - y_ref).abs().max()}"
class InstanceNormNoAffineFixture(FixtureBase):
PARAMS = [
("n, c, spatial, dtype, tune", [
# Small CI-friendly shapes -- fp32
pytest.param(2, 16, (8, 8), torch.float32, False, marks=pytest.mark.smoke),
# Small CI-friendly shapes -- fp16
pytest.param(2, 16, (8, 8), torch.float16, False, marks=pytest.mark.smoke),
# Small CI-friendly shapes -- bf16
pytest.param(2, 16, (8, 8), torch.bfloat16, False, marks=pytest.mark.smoke),
pytest.param(4, 8, (4, 4), torch.float32, False, marks=pytest.mark.full),
pytest.param(4, 8, (4, 4), torch.float16, False, marks=pytest.mark.full),
pytest.param(4, 8, (4, 4), torch.bfloat16, False, marks=pytest.mark.full),
# 1D spatial
pytest.param(2, 16, (16,), torch.float16, False, marks=pytest.mark.full),
# 3D spatial
pytest.param(2, 8, (4, 4, 4), torch.float16, False, marks=pytest.mark.full),
]),
]
@InstanceNormNoAffineFixture
def test_instance_norm_no_affine_op(n: int, c: int, spatial: tuple,
dtype: torch.dtype, tune: bool) -> None:
"""Forward correctness for InstanceNormFwdOpNoAffine vs F.instance_norm(weight=None, bias=None)."""
op = InstanceNormFwdOpNoAffine(N=n, C=c, spatial=spatial, dtype=dtype)
x = torch.randn((n, c, *spatial), dtype=dtype, device=DEVICE)
# Running stats are required positional args (R16) but ignored on the
# use_input_stats=True path; pass placeholders.
rm = torch.zeros(c, dtype=torch.float32, device=DEVICE)
rv = torch.ones(c, dtype=torch.float32, device=DEVICE)
y = op(x, rm, rv)
y_ref = F.instance_norm(
x.float(), weight=None, bias=None, eps=1e-5,
).to(dtype)
atol, rtol = _get_tolerances(dtype)
assert torch.allclose(y, y_ref, atol=atol, rtol=rtol), \
f"NoAffine forward mismatch, max err: {(y - y_ref).abs().max()}"
@InstanceNormNoAffineFixture
def test_instance_norm_no_affine_running_stats(
n: int, c: int, spatial: tuple, dtype: torch.dtype, tune: bool,
) -> None:
"""use_input_stats=False uses running_mean/running_var; matches torch reference."""
op = InstanceNormFwdOpNoAffine(
N=n, C=c, spatial=spatial, dtype=dtype, use_input_stats=False,
)
x = torch.randn((n, c, *spatial), dtype=dtype, device=DEVICE)
running_mean = torch.randn(c, dtype=torch.float32, device=DEVICE)
running_var = torch.rand(c, dtype=torch.float32, device=DEVICE) + 0.1
y = op(x, running_mean, running_var)
y_ref = F.instance_norm(
x, running_mean=running_mean, running_var=running_var,
weight=None, bias=None, use_input_stats=False, eps=1e-5,
)
atol, rtol = _get_tolerances(dtype)
assert torch.allclose(y, y_ref, atol=atol, rtol=rtol), \
f"NoAffine running-stats mismatch, max err: {(y - y_ref).abs().max()}"
@pytest.mark.smoke
def test_instance_norm_rejects_none_weight_or_bias() -> None:
"""Affine op rejects ``weight=None`` / ``bias=None``; affine-free path lives on NoAffine."""
n, c, spatial, dtype = 2, 16, (8, 8), torch.float16
op = InstanceNormFwdOp(N=n, C=c, spatial=spatial, dtype=dtype)
x = torch.randn((n, c, *spatial), dtype=dtype, device=DEVICE)
weight = torch.randn((c,), dtype=dtype, device=DEVICE)
bias = torch.randn((c,), dtype=dtype, device=DEVICE)
with pytest.raises((ValueError, TypeError)):
op(x, None, bias)
with pytest.raises((ValueError, TypeError)):
op(x, weight, None)
with pytest.raises((ValueError, TypeError)):
op(x, None, None)
@pytest.mark.smoke
def test_instance_norm_forward_required_signature() -> None:
"""`forward` declares weight and bias as required (no Optional, no default)."""
sig = inspect.signature(InstanceNormFwdOp.forward)
weight_param = sig.parameters["weight"]
bias_param = sig.parameters["bias"]
assert weight_param.default is inspect.Parameter.empty
assert bias_param.default is inspect.Parameter.empty
@pytest.mark.smoke
def test_instance_norm_rejects_ctor_input_dtype_mismatch() -> None:
op = InstanceNormFwdOp.__new__(InstanceNormFwdOp)
op.dtype = torch.float16
fp16 = torch.empty(0, dtype=torch.float16)
bf16 = torch.empty(0, dtype=torch.bfloat16)
op._validate_dtypes(fp16, fp16, fp16)
with pytest.raises(ValueError, match="x.dtype"):
op._validate_dtypes(bf16, fp16, fp16)
with pytest.raises(ValueError, match="weight.dtype"):
op._validate_dtypes(fp16, bf16, fp16)
with pytest.raises(ValueError, match="bias.dtype"):
op._validate_dtypes(fp16, fp16, bf16)
@pytest.mark.smoke
def test_instance_norm_validate_dtypes_matches_manifest_inputs() -> None:
"""``_validate_dtypes`` accepts kwargs matching manifest ``signature.inputs``.
Regression guard for a signature drift where the hand-written override
accepted only ``x`` while the manifest declared ``x``, ``weight`` and
``bias``. The manifest-validator dtype-parity check binds by kwargs and
requires the impl to honor the manifest order.
"""
sig = inspect.signature(InstanceNormFwdOp._validate_dtypes)
params = [p for p in sig.parameters if p != "self"]
assert params == ["x", "weight", "bias"], (
f"_validate_dtypes params {params} must match manifest inputs "
"['x', 'weight', 'bias'] in order"
)
@pytest.mark.smoke
def test_instance_norm_rejects_device_mismatch() -> None:
"""Forward must raise ValueError when input device differs from kernel device.
The compiled kernel binds to the active CUDA device at construction
time, so callers must construct one op per device. Verify the op
surfaces a clean ValueError rather than letting the kernel layer
raise an opaque device-id error.
"""
if torch.cuda.device_count() < 2:
pytest.skip("device-mismatch test requires >= 2 CUDA devices")
n, c, spatial, dtype = 2, 32, (8, 8), torch.float16
with torch.cuda.device(0):
op = InstanceNormFwdOp(N=n, C=c, spatial=spatial, dtype=dtype)
x_other = torch.randn(
(n, c, *spatial), dtype=dtype, device=torch.device("cuda", 1),
)
weight_other = torch.randn(
(c,), dtype=dtype, device=torch.device("cuda", 1),
)
bias_other = torch.randn(
(c,), dtype=dtype, device=torch.device("cuda", 1),
)
with pytest.raises(ValueError, match="[Dd]evice mismatch"):
op(x_other, weight_other, bias_other)
@pytest.mark.smoke
def test_instance_norm_rejects_affine_device_mismatch() -> None:
"""Forward must raise ValueError when weight/bias live on a different CUDA device than x.
Without an explicit check the kernel call would either dispatch on
cross-device tensors (slow / wrong) or surface as an opaque CUDA
error; surface a clean ValueError instead.
"""
if torch.cuda.device_count() < 2:
pytest.skip("affine-device-mismatch test requires >= 2 CUDA devices")
n, c, spatial, dtype = 2, 32, (8, 8), torch.float16
with torch.cuda.device(0):
op = InstanceNormFwdOp(N=n, C=c, spatial=spatial, dtype=dtype)
x = torch.randn((n, c, *spatial), dtype=dtype, device=torch.device("cuda", 0))
weight_other = torch.randn((c,), dtype=dtype, device=torch.device("cuda", 1))
bias_other = torch.randn((c,), dtype=dtype, device=torch.device("cuda", 1))
bias_same = torch.randn((c,), dtype=dtype, device=torch.device("cuda", 0))
weight_same = torch.randn(
(c,), dtype=dtype, device=torch.device("cuda", 0),
)
with pytest.raises(ValueError, match="weight on"):
op(x, weight_other, bias_same)
with pytest.raises(ValueError, match="bias on"):
op(x, weight_same, bias_other)
_OP_CLASSES = [
pytest.param(InstanceNormFwdOp, "InstanceNormFwdOp", id="InstanceNormFwdOp"),
pytest.param(
InstanceNormFwdOpNoAffine,
"InstanceNormFwdOpNoAffine",
id="InstanceNormFwdOpNoAffine",
),
]
@pytest.mark.smoke
@pytest.mark.parametrize("op_cls, manifest_key", _OP_CLASSES)
def test_instance_norm_init_accepts_use_input_stats_and_momentum(
op_cls: type, manifest_key: str,
) -> None:
"""`__init__` must expose the manifest-declared params so L1 parity holds.
The manifest entry declares `use_input_stats` and `momentum` (matching
PyTorch's `torch.nn.functional.instance_norm` public API). The op must
accept both, defaulting to PyTorch's defaults.
"""
init_params = inspect.signature(op_cls.__init__).parameters
assert "use_input_stats" in init_params
assert "momentum" in init_params
assert init_params["use_input_stats"].default is True
assert init_params["momentum"].default == pytest.approx(0.1)
@pytest.mark.smoke
@pytest.mark.parametrize("op_cls, manifest_key", _OP_CLASSES)
def test_instance_norm_init_signature_covers_manifest_params(
op_cls: type, manifest_key: str,
) -> None:
"""Union of `__init__` and `forward` params must cover manifest params."""
from pathlib import Path
manifest_file = (
Path(__file__).resolve().parents[2]
/ "tileops" / "manifest" / "normalization.yaml"
)
with open(manifest_file) as fp:
manifest = yaml.safe_load(fp) or {}
manifest_params = set(
manifest[manifest_key]["signature"]["params"].keys()
)
init_params = set(inspect.signature(op_cls.__init__).parameters)
forward_params = set(inspect.signature(op_cls.forward).parameters)
code_params = (init_params | forward_params) - {"self"}
missing = manifest_params - code_params
assert not missing, f"manifest params not covered by code: {missing}"
@pytest.mark.smoke
def test_instance_norm_affine_rejects_running_stats_path() -> None:
"""The affine variant still defers `use_input_stats=False`."""
with pytest.raises(NotImplementedError, match="running-stats"):
InstanceNormFwdOp(
N=2, C=16, spatial=(8, 8), dtype=torch.float16,
use_input_stats=False,
)
@pytest.mark.smoke
def test_instance_norm_no_affine_accepts_running_stats_path() -> None:
"""No-affine variant supports `use_input_stats=False` end-to-end."""
n, c, spatial, dtype = 2, 16, (8, 8), torch.float16
op = InstanceNormFwdOpNoAffine(
N=n, C=c, spatial=spatial, dtype=dtype, use_input_stats=False,
)
assert op.use_input_stats is False
x = torch.randn((n, c, *spatial), dtype=dtype, device=DEVICE)
running_mean = torch.randn(c, dtype=torch.float32, device=DEVICE)
running_var = torch.rand(c, dtype=torch.float32, device=DEVICE) + 0.1
y = op(x, running_mean, running_var)
y_ref = F.instance_norm(
x, running_mean=running_mean, running_var=running_var,
weight=None, bias=None, use_input_stats=False, eps=1e-5,
)
atol, rtol = _get_tolerances(dtype)
assert torch.allclose(y, y_ref, atol=atol, rtol=rtol)
@pytest.mark.smoke
def test_instance_norm_default_momentum_does_not_change_output() -> None:
"""Per-batch path is independent of `momentum`; default value must match torch."""
n, c, spatial, dtype = 2, 16, (8, 8), torch.float16
op_default = InstanceNormFwdOp(N=n, C=c, spatial=spatial, dtype=dtype)
op_other = InstanceNormFwdOp(
N=n, C=c, spatial=spatial, dtype=dtype, momentum=0.5,
)
assert op_default.momentum == pytest.approx(0.1)
assert op_other.momentum == pytest.approx(0.5)
x = torch.randn((n, c, *spatial), dtype=dtype, device=DEVICE)
weight = torch.randn((c,), dtype=dtype, device=DEVICE)
bias = torch.randn((c,), dtype=dtype, device=DEVICE)
y1 = op_default(x, weight, bias)
y2 = op_other(x, weight, bias)
atol, rtol = _get_tolerances(dtype)
assert torch.allclose(y1, y2, atol=atol, rtol=rtol)
if __name__ == "__main__":
pytest.main([__file__, "-vvs"])