forked from tile-ai/TileOPs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_binary_arith.py
More file actions
1374 lines (1118 loc) · 50.8 KB
/
Copy pathtest_binary_arith.py
File metadata and controls
1374 lines (1118 loc) · 50.8 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for binary arithmetic elementwise ops with broadcast.
Covers L1 smoke correctness for sub, mul, div, remainder, pow,
floor_divide, lerp, maximum, minimum (plus existing add).
Also includes L4 edge case tests for div, remainder, floor_divide, pow.
"""
import pytest
import torch
from tests.test_base import FixtureBase, TestBase
from tileops.kernels.elementwise import DivTruncFwdKernel, FloorDivideFwdKernel
from tileops.ops.elementwise import (
AddFwdOp,
DivFwdOp,
FloorDivideFwdOp,
LerpFwdOp,
LerpTensorFwdOp,
MaximumFwdOp,
MinimumFwdOp,
MulFwdOp,
PowFwdOp,
RemainderFwdOp,
SubFwdOp,
coalesce_broadcast_dims,
)
from tileops.ops.elementwise.arithmetic import _DIV_KERNEL_BY_ROUNDING_MODE
from tileops.utils import get_backend_name, is_available
from workloads.binary_arith import AddSameShapeTest as _AddSameShapeTestWorkload
DEVICE = get_backend_name()
class AddSameShapeTest(_AddSameShapeTestWorkload, TestBase):
def ref_program(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
return (a.float() + b.float()).to(a.dtype)
# ---------------------------------------------------------------------------
# coalesce_broadcast_dims unit tests
# ---------------------------------------------------------------------------
class CoalesceFixture(FixtureBase):
PARAMS = [
("a_shape, b_shape, expected_ndim", [
# same-shape: coalesces to 1D
pytest.param((1024, 1024), (1024, 1024), 1, marks=pytest.mark.smoke),
# bias-add: (B,S,D) + (1,1,D) -> 2 groups
pytest.param((2, 512, 768), (1, 1, 768), 2, marks=pytest.mark.full),
# row broadcast: (B,S,D) + (B,S,1) -> 2 groups
pytest.param((2, 512, 768), (2, 512, 1), 2, marks=pytest.mark.full),
# scalar: (M,N) + (1,1) -> 2 groups (M*N collapsed, 1 broadcast)
pytest.param((1024, 1024), (1, 1), 1, marks=pytest.mark.full),
# interleaved: (A,1,C) + (1,B,1) -> 3 groups
pytest.param((4, 1, 8), (1, 8, 1), 3, marks=pytest.mark.full),
# outer product: (M,1) + (1,N) -> 2 groups
pytest.param((64, 1), (1, 128), 2, marks=pytest.mark.full),
# non-broadcast size-1: (2,1,3) + (2,1,3) -> 1 (all contiguous)
pytest.param((2, 1, 3), (2, 1, 3), 1, marks=pytest.mark.full),
# scalar (0-dim) input: () + (4,) -> 1
pytest.param((), (4,), 1, marks=pytest.mark.full),
]),
]
@CoalesceFixture
def test_coalesce_broadcast_dims(a_shape, b_shape, expected_ndim) -> None:
"""Verify coalesce output shape count matches expected coalesced ndim."""
out_shape, coalesced_shape, a_strides, b_strides = coalesce_broadcast_dims(
a_shape, b_shape,
)
# Verify output shape matches torch broadcast
assert out_shape == torch.broadcast_shapes(a_shape, b_shape)
# Verify coalesced ndim
assert len(coalesced_shape) == expected_ndim, (
f"Expected {expected_ndim} coalesced dims, got {len(coalesced_shape)}: "
f"{coalesced_shape}"
)
# Verify strides have correct length
assert len(a_strides) == len(coalesced_shape)
assert len(b_strides) == len(coalesced_shape)
# ---------------------------------------------------------------------------
# Shared helpers
# ---------------------------------------------------------------------------
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
# ---------------------------------------------------------------------------
# Add op correctness tests
# ---------------------------------------------------------------------------
class AddSameShapeFixture(FixtureBase):
PARAMS = [
("n_total, dtype", [
pytest.param(4_096, torch.float16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.float32, marks=pytest.mark.smoke),
pytest.param(16_384, torch.float16, marks=pytest.mark.full),
]),
]
@AddSameShapeFixture
def test_add_same_shape(n_total: int, dtype: torch.dtype) -> None:
test = AddSameShapeTest(n_total, dtype)
shape = (n_total,)
op = AddFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
atol, rtol = _get_tolerances(dtype)
test.check(op, *test.gen_inputs(), atol=atol, rtol=rtol)
# ---------------------------------------------------------------------------
# Broadcast pattern tests (L3)
# ---------------------------------------------------------------------------
class AddBroadcastFixture(FixtureBase):
PARAMS = [
("a_shape, b_shape, dtype", [
pytest.param(
(2, 512, 768), (1, 1, 768), torch.float16, marks=pytest.mark.smoke,
),
pytest.param(
(2, 512, 768), (2, 512, 1), torch.float16, marks=pytest.mark.full,
),
pytest.param(
(1024, 1024), (1, 1), torch.float16, marks=pytest.mark.full,
),
pytest.param(
(4, 1, 8), (1, 8, 1), torch.float16, marks=pytest.mark.full,
),
]),
]
class AddBroadcastTest(TestBase):
def __init__(self, a_shape: tuple, b_shape: tuple, dtype: torch.dtype):
self.a_shape = a_shape
self.b_shape = b_shape
self.dtype = dtype
def gen_inputs(self) -> tuple[torch.Tensor, torch.Tensor]:
a = torch.randn(self.a_shape, dtype=self.dtype, device=DEVICE)
b = torch.randn(self.b_shape, dtype=self.dtype, device=DEVICE)
return a, b
def ref_program(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
return (a.float() + b.float()).to(a.dtype)
@AddBroadcastFixture
def test_add_broadcast(a_shape, b_shape, dtype: torch.dtype) -> None:
test = AddBroadcastTest(a_shape, b_shape, dtype)
op = AddFwdOp(a_shape=a_shape, b_shape=b_shape, dtype=dtype)
atol, rtol = _get_tolerances(dtype)
test.check(op, *test.gen_inputs(), atol=atol, rtol=rtol)
# ---------------------------------------------------------------------------
# Broadcast pattern tests for all binary arith ops (L3)
# ---------------------------------------------------------------------------
# Broadcast patterns: (a_shape, b_shape)
_BROADCAST_PATTERNS = [
# bias-add: (B,S,D) + (1,1,D)
((2, 64, 128), (1, 1, 128)),
# row broadcast: (B,S,D) + (B,S,1)
((2, 64, 128), (2, 64, 1)),
# scalar broadcast: (M,N) + (1,1)
((64, 128), (1, 1)),
]
# (op_name, op_cls, ref_fn, gen_a, gen_b)
_ARITH_BROADCAST_OPS = [
("sub", SubFwdOp, lambda a, b: (a.float() - b.float()).to(a.dtype),
lambda s, d: torch.randn(*s, dtype=d, device=DEVICE),
lambda s, d: torch.randn(*s, dtype=d, device=DEVICE)),
("mul", MulFwdOp, lambda a, b: (a.float() * b.float()).to(a.dtype),
lambda s, d: torch.randn(*s, dtype=d, device=DEVICE),
lambda s, d: torch.randn(*s, dtype=d, device=DEVICE)),
("div", DivFwdOp, lambda a, b: (a.float() / b.float()).to(a.dtype),
lambda s, d: torch.rand(*s, dtype=d, device=DEVICE) + 0.1,
lambda s, d: torch.rand(*s, dtype=d, device=DEVICE) + 0.1),
("remainder", RemainderFwdOp,
lambda a, b: a - torch.floor(a.float() / b.float()).to(a.dtype) * b,
lambda s, d: torch.rand(*s, dtype=d, device=DEVICE) + 0.1,
lambda s, d: torch.rand(*s, dtype=d, device=DEVICE) + 0.1),
("pow", PowFwdOp, lambda a, b: torch.pow(a.float(), b.float()).to(a.dtype),
lambda s, d: torch.rand(*s, dtype=d, device=DEVICE) + 0.5,
lambda s, d: torch.rand(*s, dtype=d, device=DEVICE) * 2.0),
("floor_divide", FloorDivideFwdOp,
lambda a, b: torch.floor(a.float() / b.float()).to(a.dtype),
lambda s, d: torch.rand(*s, dtype=d, device=DEVICE) + 0.1,
lambda s, d: torch.rand(*s, dtype=d, device=DEVICE) + 0.1),
("lerp", LerpFwdOp, lambda a, b: torch.lerp(a.float(), b.float(), 0.5).to(a.dtype),
lambda s, d: torch.randn(*s, dtype=d, device=DEVICE),
lambda s, d: torch.randn(*s, dtype=d, device=DEVICE)),
("maximum", MaximumFwdOp, lambda a, b: torch.maximum(a.float(), b.float()).to(a.dtype),
lambda s, d: torch.randn(*s, dtype=d, device=DEVICE),
lambda s, d: torch.randn(*s, dtype=d, device=DEVICE)),
("minimum", MinimumFwdOp, lambda a, b: torch.minimum(a.float(), b.float()).to(a.dtype),
lambda s, d: torch.randn(*s, dtype=d, device=DEVICE),
lambda s, d: torch.randn(*s, dtype=d, device=DEVICE)),
]
class ArithBroadcastFixture(FixtureBase):
PARAMS = [
("op_name, op_cls, ref_fn, gen_a, gen_b, a_shape, b_shape", [
pytest.param(name, cls, ref, ga, gb, a_s, b_s,
marks=pytest.mark.smoke if i == 0 and j == 0
else pytest.mark.full)
for j, (name, cls, ref, ga, gb) in enumerate(_ARITH_BROADCAST_OPS)
for i, (a_s, b_s) in enumerate(_BROADCAST_PATTERNS)
]),
]
@ArithBroadcastFixture
def test_binary_arith_broadcast(
op_name, op_cls, ref_fn, gen_a, gen_b, a_shape, b_shape,
) -> None:
dtype = torch.float16
a = gen_a(a_shape, dtype)
b = gen_b(b_shape, dtype)
op = op_cls(a_shape=a_shape, b_shape=b_shape, dtype=dtype)
ref = ref_fn(a, b)
with torch.no_grad():
out = op(a, b)
atol, rtol = _get_tolerances(dtype)
if op_name == "floor_divide":
atol = 1.0 # floor rounding tolerance
torch.testing.assert_close(out, ref, atol=atol, rtol=rtol)
class AddStrategyFixture(FixtureBase):
PARAMS = [
("n_total, dtype, strategy", [
pytest.param(4_096, torch.float16, "direct", marks=pytest.mark.smoke),
pytest.param(16_384, torch.float16, "explicit_parallel", marks=pytest.mark.full),
]),
]
@AddStrategyFixture
def test_add_strategies(n_total: int, dtype: torch.dtype, strategy: str) -> None:
"""Verify both binary strategies produce correct results."""
test = AddSameShapeTest(n_total, dtype)
shape = (n_total,)
op = AddFwdOp(a_shape=shape, b_shape=shape, dtype=dtype, strategy=strategy)
atol, rtol = _get_tolerances(dtype)
test.check(op, *test.gen_inputs(), atol=atol, rtol=rtol)
# ---------------------------------------------------------------------------
# Generic binary test helper
# ---------------------------------------------------------------------------
class BinarySameShapeTest(TestBase):
"""Reusable test body for binary same-shape ops."""
def __init__(self, n_total: int, dtype: torch.dtype, ref_fn):
self.n_total = n_total
self.dtype = dtype
self.ref_fn = ref_fn
def gen_inputs(self) -> tuple[torch.Tensor, torch.Tensor]:
a = torch.randn(self.n_total, dtype=self.dtype, device=DEVICE)
b = torch.randn(self.n_total, dtype=self.dtype, device=DEVICE)
return a, b
def ref_program(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
return self.ref_fn(a.float(), b.float()).to(a.dtype)
class BinaryPositiveTest(TestBase):
"""Test body for ops that need positive inputs (div, remainder, pow, etc.)."""
def __init__(self, n_total: int, dtype: torch.dtype, ref_fn):
self.n_total = n_total
self.dtype = dtype
self.ref_fn = ref_fn
def gen_inputs(self) -> tuple[torch.Tensor, torch.Tensor]:
a = torch.rand(self.n_total, dtype=self.dtype, device=DEVICE) + 0.1
b = torch.rand(self.n_total, dtype=self.dtype, device=DEVICE) + 0.1
return a, b
def ref_program(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
return self.ref_fn(a.float(), b.float()).to(a.dtype)
# ---------------------------------------------------------------------------
# Sub op
# ---------------------------------------------------------------------------
class SubFixture(FixtureBase):
PARAMS = [
("n_total, dtype", [
pytest.param(4_096, torch.float16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.float32, marks=pytest.mark.smoke),
]),
]
@SubFixture
def test_sub_op(n_total: int, dtype: torch.dtype) -> None:
test = BinarySameShapeTest(n_total, dtype, lambda a, b: a - b)
shape = (n_total,)
op = SubFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
atol, rtol = _get_tolerances(dtype)
test.check(op, *test.gen_inputs(), atol=atol, rtol=rtol)
# ---------------------------------------------------------------------------
# Mul op
# ---------------------------------------------------------------------------
class MulFixture(FixtureBase):
PARAMS = [
("n_total, dtype", [
pytest.param(4_096, torch.float16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.float32, marks=pytest.mark.smoke),
]),
]
@MulFixture
def test_mul_op(n_total: int, dtype: torch.dtype) -> None:
test = BinarySameShapeTest(n_total, dtype, lambda a, b: a * b)
shape = (n_total,)
op = MulFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
atol, rtol = _get_tolerances(dtype)
test.check(op, *test.gen_inputs(), atol=atol, rtol=rtol)
# ---------------------------------------------------------------------------
# Div op
# ---------------------------------------------------------------------------
class DivFixture(FixtureBase):
PARAMS = [
("n_total, dtype", [
pytest.param(4_096, torch.float16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.float32, marks=pytest.mark.smoke),
]),
]
@DivFixture
def test_div_op(n_total: int, dtype: torch.dtype) -> None:
test = BinaryPositiveTest(n_total, dtype, lambda a, b: a / b)
shape = (n_total,)
op = DivFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
atol, rtol = _get_tolerances(dtype)
test.check(op, *test.gen_inputs(), atol=atol, rtol=rtol)
# ---------------------------------------------------------------------------
# Remainder op
# ---------------------------------------------------------------------------
class RemainderFixture(FixtureBase):
PARAMS = [
("n_total, dtype", [
pytest.param(4_096, torch.float16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.float32, marks=pytest.mark.smoke),
]),
]
class RemainderTest(TestBase):
"""Remainder reference matches the kernel: fp32 division+floor, native multiply-subtract."""
def __init__(self, n_total: int, dtype: torch.dtype):
self.n_total = n_total
self.dtype = dtype
def gen_inputs(self) -> tuple[torch.Tensor, torch.Tensor]:
a = torch.rand(self.n_total, dtype=self.dtype, device=DEVICE) + 0.1
b = torch.rand(self.n_total, dtype=self.dtype, device=DEVICE) + 0.1
return a, b
def ref_program(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
# fp32 division+floor, cast back, native multiply-subtract
floored = torch.floor(a.float() / b.float()).to(a.dtype)
return a - floored * b
@RemainderFixture
def test_remainder_op(n_total: int, dtype: torch.dtype) -> None:
test = RemainderTest(n_total, dtype)
shape = (n_total,)
op = RemainderFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
atol, rtol = _get_tolerances(dtype)
test.check(op, *test.gen_inputs(), atol=atol, rtol=rtol)
# ---------------------------------------------------------------------------
# Pow op
# ---------------------------------------------------------------------------
class PowFixture(FixtureBase):
PARAMS = [
("n_total, dtype", [
pytest.param(4_096, torch.float16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.float32, marks=pytest.mark.smoke),
]),
]
class PowPositiveTest(TestBase):
"""Pow needs positive base and small exponent to avoid overflow in fp16."""
def __init__(self, n_total: int, dtype: torch.dtype):
self.n_total = n_total
self.dtype = dtype
def gen_inputs(self) -> tuple[torch.Tensor, torch.Tensor]:
a = torch.rand(self.n_total, dtype=self.dtype, device=DEVICE) + 0.5
b = torch.rand(self.n_total, dtype=self.dtype, device=DEVICE) * 2.0
return a, b
def ref_program(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
return torch.pow(a.float(), b.float()).to(a.dtype)
@PowFixture
def test_pow_op(n_total: int, dtype: torch.dtype) -> None:
test = PowPositiveTest(n_total, dtype)
shape = (n_total,)
op = PowFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
atol, rtol = _get_tolerances(dtype)
test.check(op, *test.gen_inputs(), atol=atol, rtol=rtol)
# ---------------------------------------------------------------------------
# FloorDivide op
# ---------------------------------------------------------------------------
class FloorDivideFixture(FixtureBase):
PARAMS = [
("n_total, dtype", [
pytest.param(4_096, torch.float16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.float32, marks=pytest.mark.smoke),
]),
]
class FloorDivideTest(TestBase):
"""Floor divide reference matches the kernel: fp32 division+floor, cast back."""
def __init__(self, n_total: int, dtype: torch.dtype):
self.n_total = n_total
self.dtype = dtype
def gen_inputs(self) -> tuple[torch.Tensor, torch.Tensor]:
a = torch.rand(self.n_total, dtype=self.dtype, device=DEVICE) + 0.1
b = torch.rand(self.n_total, dtype=self.dtype, device=DEVICE) + 0.1
return a, b
def ref_program(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
# fp32 division+floor, cast back to native dtype
return torch.floor(a.float() / b.float()).to(a.dtype)
@FloorDivideFixture
def test_floor_divide_op(n_total: int, dtype: torch.dtype) -> None:
test = FloorDivideTest(n_total, dtype)
shape = (n_total,)
op = FloorDivideFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
# Floor divide in reduced precision can differ by 1; use atol=1.0
atol = 1.0 if dtype != torch.float32 else 1e-5
test.check(op, *test.gen_inputs(), atol=atol, rtol=0.0)
# ---------------------------------------------------------------------------
# Lerp op (ternary in PyTorch; compile-time weight=0.5)
# ---------------------------------------------------------------------------
class LerpFixture(FixtureBase):
PARAMS = [
("n_total, dtype", [
pytest.param(4_096, torch.float16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.float32, marks=pytest.mark.smoke),
]),
]
class LerpTest(TestBase):
def __init__(self, n_total: int, dtype: torch.dtype, weight: float = 0.5):
self.n_total = n_total
self.dtype = dtype
self.weight = weight
def gen_inputs(self) -> tuple[torch.Tensor, torch.Tensor]:
a = torch.randn(self.n_total, dtype=self.dtype, device=DEVICE)
b = torch.randn(self.n_total, dtype=self.dtype, device=DEVICE)
return a, b
def ref_program(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
return torch.lerp(a.float(), b.float(), self.weight).to(a.dtype)
@LerpFixture
def test_lerp_op(n_total: int, dtype: torch.dtype) -> None:
"""Validate lerp across multiple construction-time weight values."""
# Lerp computes a + w*(b-a) in native dtype; the intermediate multiply
# adds rounding error proportional to weight magnitude in fp16.
if dtype == torch.float32:
atol, rtol = 1e-5, 1e-5
elif dtype == torch.float16:
atol, rtol = 5e-3, 5e-3
else: # bfloat16
atol, rtol = 1.6e-2, 1.6e-2
for weight in [0.0, 0.3, 0.5, 0.7, 1.0]:
test = LerpTest(n_total, dtype, weight=weight)
shape = (n_total,)
op = LerpFwdOp(a_shape=shape, b_shape=shape, dtype=dtype, weight=weight)
test.check(op, *test.gen_inputs(), atol=atol, rtol=rtol)
# ---------------------------------------------------------------------------
# Maximum op
# ---------------------------------------------------------------------------
class MaximumFixture(FixtureBase):
PARAMS = [
("n_total, dtype", [
pytest.param(4_096, torch.float16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.float32, marks=pytest.mark.smoke),
]),
]
@MaximumFixture
def test_maximum_op(n_total: int, dtype: torch.dtype) -> None:
test = BinarySameShapeTest(n_total, dtype, lambda a, b: torch.maximum(a, b))
shape = (n_total,)
op = MaximumFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
atol, rtol = _get_tolerances(dtype)
test.check(op, *test.gen_inputs(), atol=atol, rtol=rtol)
# ---------------------------------------------------------------------------
# Minimum op
# ---------------------------------------------------------------------------
class MinimumFixture(FixtureBase):
PARAMS = [
("n_total, dtype", [
pytest.param(4_096, torch.float16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(4_096, torch.float32, marks=pytest.mark.smoke),
]),
]
@MinimumFixture
def test_minimum_op(n_total: int, dtype: torch.dtype) -> None:
test = BinarySameShapeTest(n_total, dtype, lambda a, b: torch.minimum(a, b))
shape = (n_total,)
op = MinimumFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
atol, rtol = _get_tolerances(dtype)
test.check(op, *test.gen_inputs(), atol=atol, rtol=rtol)
# ---------------------------------------------------------------------------
# Maximum/Minimum NaN propagation tests
# ---------------------------------------------------------------------------
class MaxMinNanFixture(FixtureBase):
PARAMS = [
("dtype", [
pytest.param(torch.float16, marks=pytest.mark.smoke),
pytest.param(torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(torch.float32, marks=pytest.mark.smoke),
]),
]
@MaxMinNanFixture
def test_maximum_nan_propagation(dtype: torch.dtype) -> None:
"""Verify maximum propagates NaN when either operand is NaN."""
nan = float("nan")
a = torch.tensor([nan, 1.0, nan, 2.0], dtype=dtype, device=DEVICE)
b = torch.tensor([3.0, nan, nan, 1.0], dtype=dtype, device=DEVICE)
shape = (4,)
op = MaximumFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
ref = torch.maximum(a, b)
with torch.no_grad():
out = op(a, b)
# NaN positions must match: both output and ref should be NaN at same indices
assert torch.equal(torch.isnan(out), torch.isnan(ref)), (
f"NaN positions differ: out={out}, ref={ref}"
)
# Non-NaN values must match exactly
mask = ~torch.isnan(ref)
assert torch.equal(out[mask], ref[mask]), (
f"Non-NaN values differ: out={out[mask]}, ref={ref[mask]}"
)
@MaxMinNanFixture
def test_minimum_nan_propagation(dtype: torch.dtype) -> None:
"""Verify minimum propagates NaN when either operand is NaN."""
nan = float("nan")
a = torch.tensor([nan, 1.0, nan, 2.0], dtype=dtype, device=DEVICE)
b = torch.tensor([3.0, nan, nan, 1.0], dtype=dtype, device=DEVICE)
shape = (4,)
op = MinimumFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
ref = torch.minimum(a, b)
with torch.no_grad():
out = op(a, b)
# NaN positions must match
assert torch.equal(torch.isnan(out), torch.isnan(ref)), (
f"NaN positions differ: out={out}, ref={ref}"
)
# Non-NaN values must match exactly
mask = ~torch.isnan(ref)
assert torch.equal(out[mask], ref[mask]), (
f"Non-NaN values differ: out={out[mask]}, ref={ref[mask]}"
)
# ---------------------------------------------------------------------------
# Maximum/Minimum signed-zero regression tests
# ---------------------------------------------------------------------------
class SignedZeroFixture(FixtureBase):
PARAMS = [
("dtype", [
pytest.param(torch.float16, marks=pytest.mark.smoke),
pytest.param(torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(torch.float32, marks=pytest.mark.smoke),
]),
]
@SignedZeroFixture
def test_maximum_signed_zero(dtype: torch.dtype) -> None:
"""maximum(+0.0, -0.0) must return +0.0 (IEEE / PyTorch semantics)."""
pos_zero = torch.tensor(0.0, dtype=dtype, device=DEVICE)
neg_zero = torch.tensor(-0.0, dtype=dtype, device=DEVICE)
# Both orderings: (+0, -0) and (-0, +0)
a = torch.stack([pos_zero, neg_zero, pos_zero, neg_zero])
b = torch.stack([neg_zero, pos_zero, pos_zero, neg_zero])
shape = (4,)
op = MaximumFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
ref = torch.maximum(a, b)
with torch.no_grad():
out = op(a, b)
# Value equality
torch.testing.assert_close(out, ref, atol=0, rtol=0)
# Sign-bit equality: +0 and -0 compare equal but have different sign bits
out_signbits = torch.signbit(out)
ref_signbits = torch.signbit(ref)
assert torch.equal(out_signbits, ref_signbits), (
f"Signed-zero mismatch: out signs={out_signbits}, ref signs={ref_signbits}"
)
@SignedZeroFixture
def test_minimum_signed_zero(dtype: torch.dtype) -> None:
"""minimum(-0.0, +0.0) must return -0.0 (IEEE / PyTorch semantics)."""
pos_zero = torch.tensor(0.0, dtype=dtype, device=DEVICE)
neg_zero = torch.tensor(-0.0, dtype=dtype, device=DEVICE)
# Both orderings: (-0, +0) and (+0, -0)
a = torch.stack([neg_zero, pos_zero, neg_zero, pos_zero])
b = torch.stack([pos_zero, neg_zero, neg_zero, pos_zero])
shape = (4,)
op = MinimumFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
ref = torch.minimum(a, b)
with torch.no_grad():
out = op(a, b)
# Value equality
torch.testing.assert_close(out, ref, atol=0, rtol=0)
# Sign-bit equality
out_signbits = torch.signbit(out)
ref_signbits = torch.signbit(ref)
assert torch.equal(out_signbits, ref_signbits), (
f"Signed-zero mismatch: out signs={out_signbits}, ref signs={ref_signbits}"
)
@SignedZeroFixture
def test_maximum_signed_zero_with_nan(dtype: torch.dtype) -> None:
"""Signed-zero fix must not regress NaN propagation."""
nan = float("nan")
# Mix of NaN pairs and non-NaN signed-zero pairs so both code paths execute
a = torch.tensor([nan, 1.0, -0.0, 0.0, nan, 3.0], dtype=dtype, device=DEVICE)
b = torch.tensor([1.0, nan, 0.0, -0.0, -0.0, 2.0], dtype=dtype, device=DEVICE)
shape = (6,)
op = MaximumFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
ref = torch.maximum(a, b)
with torch.no_grad():
out = op(a, b)
# NaN positions must match
assert torch.equal(torch.isnan(out), torch.isnan(ref)), (
f"NaN positions differ: out={out}, ref={ref}"
)
# Non-NaN values must exist and match (including sign bits for zeros)
mask = ~torch.isnan(ref)
assert mask.any(), "Test bug: expected some non-NaN reference values"
torch.testing.assert_close(out[mask], ref[mask], atol=0, rtol=0)
assert torch.equal(torch.signbit(out[mask]), torch.signbit(ref[mask])), (
f"Signed-zero mismatch in non-NaN values: "
f"out signs={torch.signbit(out[mask])}, ref signs={torch.signbit(ref[mask])}"
)
@SignedZeroFixture
def test_minimum_signed_zero_with_nan(dtype: torch.dtype) -> None:
"""Signed-zero fix must not regress NaN propagation."""
nan = float("nan")
# Mix of NaN pairs and non-NaN signed-zero pairs so both code paths execute
a = torch.tensor([nan, -0.0, 0.0, 1.0, nan, 2.0], dtype=dtype, device=DEVICE)
b = torch.tensor([1.0, nan, -0.0, 0.0, 0.0, 3.0], dtype=dtype, device=DEVICE)
shape = (6,)
op = MinimumFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
ref = torch.minimum(a, b)
with torch.no_grad():
out = op(a, b)
# NaN positions must match
assert torch.equal(torch.isnan(out), torch.isnan(ref)), (
f"NaN positions differ: out={out}, ref={ref}"
)
# Non-NaN values must exist and match (including sign bits for zeros)
mask = ~torch.isnan(ref)
assert mask.any(), "Test bug: expected some non-NaN reference values"
torch.testing.assert_close(out[mask], ref[mask], atol=0, rtol=0)
assert torch.equal(torch.signbit(out[mask]), torch.signbit(ref[mask])), (
f"Signed-zero mismatch in non-NaN values: "
f"out signs={torch.signbit(out[mask])}, ref signs={torch.signbit(ref[mask])}"
)
# ---------------------------------------------------------------------------
# L4 edge case tests (fp32, 4K)
# ---------------------------------------------------------------------------
class EdgeCaseFixture(FixtureBase):
PARAMS = [
("op_cls, ref_fn, gen_fn", [
# div: avoid div-by-zero
pytest.param(
DivFwdOp,
lambda a, b: a / b,
lambda n, d: (
torch.randn(n, dtype=d, device=DEVICE),
torch.rand(n, dtype=d, device=DEVICE) + 0.1,
),
marks=pytest.mark.smoke,
),
# remainder: positive inputs
pytest.param(
RemainderFwdOp,
lambda a, b: a % b,
lambda n, d: (
torch.rand(n, dtype=d, device=DEVICE) + 0.1,
torch.rand(n, dtype=d, device=DEVICE) + 0.1,
),
marks=pytest.mark.full,
),
# floor_divide: positive inputs
pytest.param(
FloorDivideFwdOp,
lambda a, b: torch.floor(a / b),
lambda n, d: (
torch.rand(n, dtype=d, device=DEVICE) + 0.1,
torch.rand(n, dtype=d, device=DEVICE) + 0.1,
),
marks=pytest.mark.full,
),
# pow: positive base, small exponent
pytest.param(
PowFwdOp,
lambda a, b: torch.pow(a, b),
lambda n, d: (
torch.rand(n, dtype=d, device=DEVICE) + 0.5,
torch.rand(n, dtype=d, device=DEVICE) * 2.0,
),
marks=pytest.mark.full,
),
# maximum: mixed sign
pytest.param(
MaximumFwdOp,
lambda a, b: torch.maximum(a, b),
lambda n, d: (
torch.randn(n, dtype=d, device=DEVICE),
torch.randn(n, dtype=d, device=DEVICE),
),
marks=pytest.mark.full,
),
]),
]
@EdgeCaseFixture
def test_binary_arith_edge_cases(op_cls, ref_fn, gen_fn) -> None:
"""L4 edge case tests: fp32, 4K elements."""
n = 4096
dtype = torch.float32
shape = (n,)
a, b = gen_fn(n, dtype)
op = op_cls(a_shape=shape, b_shape=shape, dtype=dtype)
ref = ref_fn(a, b)
with torch.no_grad():
out = op(a, b)
torch.testing.assert_close(out, ref, atol=1e-5, rtol=1e-5)
# ---------------------------------------------------------------------------
# Dtype contract tests
# ---------------------------------------------------------------------------
class FloatOnlyBinaryRejectFixture(FixtureBase):
PARAMS = [
("op_cls, dtype", [
pytest.param(DivFwdOp, torch.int32, marks=pytest.mark.smoke),
pytest.param(RemainderFwdOp, torch.int32, marks=pytest.mark.smoke),
pytest.param(PowFwdOp, torch.int32, marks=pytest.mark.smoke),
pytest.param(FloorDivideFwdOp, torch.int64, marks=pytest.mark.smoke),
pytest.param(LerpFwdOp, torch.int32, marks=pytest.mark.smoke),
]),
]
@FloatOnlyBinaryRejectFixture
def test_float_only_binary_ops_reject_integer_dtype(op_cls, dtype: torch.dtype) -> None:
"""Float-only binary ops must reject integer dtypes at construction time."""
shape = (16,)
with pytest.raises(ValueError, match="does not support dtype"):
op_cls(a_shape=shape, b_shape=shape, dtype=dtype)
@pytest.mark.smoke
def test_binary_op_rejects_runtime_dtype_mismatch() -> None:
"""Runtime inputs should fail fast instead of reaching backend lowering."""
op = SubFwdOp(a_shape=(16,), b_shape=(16,), dtype=torch.float16)
a = torch.randn(16, device=DEVICE, dtype=torch.float32)
b = torch.randn(16, device=DEVICE, dtype=torch.float16)
with pytest.raises(ValueError, match="Expected input.dtype"):
op(a, b)
# ---------------------------------------------------------------------------
# BinaryKernel autotune_configs tests
# ---------------------------------------------------------------------------
@pytest.mark.smoke
def test_binary_kernel_has_autotune_configs() -> None:
"""BinaryKernel subclasses must expose autotune_configs with >= 3 entries."""
shape = (4096,)
for op_cls in (MaximumFwdOp, MinimumFwdOp, AddFwdOp, SubFwdOp, MulFwdOp):
op = op_cls(a_shape=shape, b_shape=shape, dtype=torch.float16)
# Access autotune_configs from the underlying kernel object
kernel = op.kernel
configs = kernel.autotune_configs
assert configs is not None, (
f"{kernel.__class__.__name__} must define autotune_configs"
)
assert len(configs) >= 3, (
f"{kernel.__class__.__name__}.autotune_configs has {len(configs)} entries, need >= 3"
)
# Each config must have "threads" and "num_per_thread" keys
for cfg in configs:
assert "threads" in cfg, f"Config missing 'threads': {cfg}"
assert "num_per_thread" in cfg, f"Config missing 'num_per_thread': {cfg}"
@pytest.mark.smoke
def test_binary_kernel_autotune_configs_distinct() -> None:
"""autotune_configs entries must be distinct (no duplicates)."""
shape = (4096,)
op = AddFwdOp(a_shape=shape, b_shape=shape, dtype=torch.float16)
configs = op.kernel.autotune_configs
config_tuples = [(c["threads"], c["num_per_thread"]) for c in configs]
assert len(config_tuples) == len(set(config_tuples)), (
f"Duplicate configs found: {config_tuples}"
)
# ---------------------------------------------------------------------------
# Optimized maximum/minimum correctness on larger shapes
# ---------------------------------------------------------------------------
class OptimizedMaxMinFixture(FixtureBase):
PARAMS = [
("n_total, dtype", [
pytest.param(1024 * 4096, torch.float16, marks=pytest.mark.smoke),
pytest.param(1024 * 4096, torch.bfloat16, marks=pytest.mark.smoke),
pytest.param(1024 * 10240, torch.float16, marks=pytest.mark.full),
]),
]
@OptimizedMaxMinFixture
def test_maximum_optimized_large(n_total: int, dtype: torch.dtype) -> None:
"""Optimized maximum matches torch.maximum on large DNN-realistic shapes."""
shape = (n_total,)
a = torch.randn(*shape, device=DEVICE, dtype=dtype)
b = torch.randn(*shape, device=DEVICE, dtype=dtype)
op = MaximumFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
ref = torch.maximum(a, b)
with torch.no_grad():
out = op(a, b)
torch.testing.assert_close(out, ref, atol=0, rtol=0)
@OptimizedMaxMinFixture
def test_minimum_optimized_large(n_total: int, dtype: torch.dtype) -> None:
"""Optimized minimum matches torch.minimum on large DNN-realistic shapes."""
shape = (n_total,)
a = torch.randn(*shape, device=DEVICE, dtype=dtype)
b = torch.randn(*shape, device=DEVICE, dtype=dtype)
op = MinimumFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
ref = torch.minimum(a, b)
with torch.no_grad():
out = op(a, b)
torch.testing.assert_close(out, ref, atol=0, rtol=0)
# ---------------------------------------------------------------------------
# register_copy broadcast downgrade regression test
# ---------------------------------------------------------------------------
@pytest.mark.smoke
def test_register_copy_downgrades_on_broadcast() -> None:
"""Explicitly requesting register_copy on broadcast shapes must not crash.
register_copy only works for same-shape contiguous inputs. When the
caller passes strategy='register_copy' with broadcast shapes, the kernel
must silently downgrade to explicit_parallel and produce correct results.
"""
a_shape = (2, 64, 128)
b_shape = (1, 1, 128)
dtype = torch.float16
for op_cls, ref_fn in [
(AddFwdOp, lambda a, b: a + b),
(MaximumFwdOp, lambda a, b: torch.maximum(a, b)),
]:
op = op_cls(
a_shape=a_shape, b_shape=b_shape, dtype=dtype,
strategy="register_copy",
)
# Strategy must have been downgraded
assert op.kernel.strategy == "explicit_parallel", (
f"{op_cls.__name__} did not downgrade register_copy for broadcast inputs"
)
a = torch.randn(*a_shape, device=DEVICE, dtype=dtype)
b = torch.randn(*b_shape, device=DEVICE, dtype=dtype)
ref = ref_fn(a, b)
with torch.no_grad():
out = op(a, b)
torch.testing.assert_close(out, ref, atol=1e-3, rtol=1e-3)