-
Notifications
You must be signed in to change notification settings - Fork 996
Expand file tree
/
Copy pathtest_ops.py
More file actions
6652 lines (5500 loc) · 201 KB
/
test_ops.py
File metadata and controls
6652 lines (5500 loc) · 201 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
#!/usr/bin/env python3
# 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.
"""
Consolidated op tests for the MLX delegate.
This file contains all op tests organized by category. Each test class inherits
from OpTestCase and can be run via the run_all_tests.py script.
Usage:
# Run all tests (with 4 parallel workers, cleanup after)
python -m executorch.backends.mlx.test.run_all_tests -j4 --clean-after
# Run specific test
python -m executorch.backends.mlx.test.run_all_tests add
# List available tests
python -m executorch.backends.mlx.test.run_all_tests --list
See README.md in this directory for full documentation.
"""
from typing import Callable, Dict, List, Optional, Tuple
import torch
import torch.nn as nn
# Import custom ops for RoPE and KV cache tests
from executorch.backends.mlx import ( # noqa: F401 - registers mlx ops # noqa: F401 - registers mlx.rope
custom_ops,
ops,
)
from torch.export import Dim
from .test_utils import OpTestCase, register_test
class AddTensorModel(nn.Module):
"""Add two tensors, optionally with alpha."""
def __init__(self, alpha: Optional[float] = None):
super().__init__()
self.alpha = alpha
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
if self.alpha is not None:
return torch.add(x, y, alpha=self.alpha)
return x + y
class AddScalarModel(nn.Module):
"""Add tensor and scalar."""
def __init__(self, scalar: float = 1.0):
super().__init__()
self.scalar = scalar
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x + self.scalar
@register_test
class AddTest(OpTestCase):
"""Test case for add op."""
name = "add"
rtol = 1e-5
atol = 1e-5
def __init__(
self,
shape: Tuple[int, ...] = (2, 16, 64),
scalar: Optional[float] = None,
alpha: Optional[float] = None,
):
self.shape = shape
self.scalar = scalar
self.alpha = alpha
if alpha is not None:
self.name = "add_alpha"
elif scalar is not None:
self.name = "add_scalar"
else:
self.name = "add"
@classmethod
def get_test_configs(cls) -> List["AddTest"]:
return [
cls(), # tensor + tensor
cls(scalar=2.5), # tensor + scalar
cls(alpha=2.0), # tensor + alpha * tensor
]
def create_model(self) -> nn.Module:
if self.scalar is not None:
return AddScalarModel(self.scalar)
else:
return AddTensorModel(self.alpha)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
if self.scalar is not None:
return (x,)
else:
y = torch.randn(self.shape)
return (x, y)
class SubModel(nn.Module):
"""Model that performs element-wise subtraction, optionally with alpha."""
def __init__(self, alpha: Optional[float] = None):
super().__init__()
self.alpha = alpha
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
if self.alpha is not None:
return torch.sub(x, y, alpha=self.alpha)
return torch.sub(x, y)
@register_test
class SubTest(OpTestCase):
name = "sub"
rtol = 1e-5
atol = 1e-5
def __init__(
self,
shape: Tuple[int, ...] = (2, 3, 4),
scalar_sub: bool = False,
alpha: Optional[float] = None,
):
self.shape = shape
self.scalar_sub = scalar_sub
self.alpha = alpha
shape_str = "x".join(str(s) for s in shape)
if alpha is not None:
self.name = f"sub_{shape_str}_alpha"
elif scalar_sub:
self.name = f"sub_{shape_str}_scalar"
else:
self.name = f"sub_{shape_str}"
@classmethod
def get_test_configs(cls) -> List["SubTest"]:
return [
cls(shape=(2, 3, 4)),
cls(shape=(10,)),
cls(shape=(4, 8)),
cls(shape=(2, 8, 16)),
cls(shape=(1, 128, 128)),
cls(shape=(2, 3, 4), scalar_sub=True),
cls(shape=(2, 3, 4), alpha=2.0),
]
def create_model(self) -> nn.Module:
return SubModel(self.alpha)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
if self.scalar_sub:
y = torch.randn(())
else:
y = torch.randn(self.shape)
return (x, y)
class MulTensorModel(nn.Module):
"""Multiply two tensors."""
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
return x * y
class MulScalarModel(nn.Module):
"""Multiply tensor and scalar."""
def __init__(self, scalar: float = 1.0):
super().__init__()
self.scalar = scalar
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * self.scalar
@register_test
class MulTest(OpTestCase):
"""Test case for mul op."""
name = "mul"
rtol = 1e-5
atol = 1e-5
def __init__(
self,
shape: Tuple[int, ...] = (2, 16, 64),
scalar: Optional[float] = None,
):
self.shape = shape
self.scalar = scalar
if scalar is not None:
self.name = "mul_scalar"
else:
self.name = "mul"
@classmethod
def get_test_configs(cls) -> List["MulTest"]:
return [
cls(),
cls(scalar=2.5),
]
def create_model(self) -> nn.Module:
if self.scalar is not None:
return MulScalarModel(self.scalar)
else:
return MulTensorModel()
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
if self.scalar is not None:
return (x,)
else:
y = torch.randn(self.shape)
return (x, y)
class DivModel(nn.Module):
"""Model that performs element-wise division."""
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
return torch.div(x, y)
@register_test
class DivTest(OpTestCase):
name = "div"
rtol = 1e-5
atol = 1e-5
def __init__(
self,
shape: Tuple[int, ...] = (2, 3, 4),
scalar_divisor: bool = False,
):
self.shape = shape
self.scalar_divisor = scalar_divisor
shape_str = "x".join(str(s) for s in shape)
if scalar_divisor:
self.name = f"div_{shape_str}_scalar"
else:
self.name = f"div_{shape_str}"
@classmethod
def get_test_configs(cls) -> List["DivTest"]:
return [
cls(shape=(2, 3, 4)),
cls(shape=(10,)),
cls(shape=(4, 8)),
cls(shape=(2, 8, 16)),
cls(shape=(1, 128, 64)),
cls(shape=(2, 3, 4), scalar_divisor=True),
]
def create_model(self) -> nn.Module:
return DivModel()
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape) + 2.0
if self.scalar_divisor:
y = torch.randn(()) + 2.0
else:
y = torch.randn(self.shape) + 2.0
return (x, y)
class ClampModel(nn.Module):
"""Model that applies clamp with min and max."""
def __init__(self, min_val: Optional[float], max_val: Optional[float]):
super().__init__()
self.min_val = min_val
self.max_val = max_val
def forward(self, x: torch.Tensor) -> torch.Tensor:
return torch.clamp(x, min=self.min_val, max=self.max_val)
@register_test
class ClampTest(OpTestCase):
"""Test case for clamp op with various min/max combinations."""
name = "clamp"
rtol = 1e-5
atol = 1e-5
def __init__(
self,
shape: Tuple[int, ...] = (2, 3, 4),
min_val: Optional[float] = None,
max_val: Optional[float] = None,
):
self.shape = shape
self.min_val = min_val
self.max_val = max_val
# Build descriptive name
parts = ["clamp"]
if min_val is not None:
parts.append(f"min{min_val}")
if max_val is not None:
parts.append(f"max{max_val}")
if min_val is None and max_val is None:
parts.append("none")
shape_str = "x".join(str(s) for s in shape)
parts.append(shape_str)
self.name = "_".join(parts)
@classmethod
def get_test_configs(cls) -> List["ClampTest"]:
return [
# Only min specified
cls(shape=(2, 3, 4), min_val=-0.5, max_val=None),
# Only max specified
cls(shape=(2, 3, 4), min_val=None, max_val=0.5),
# Both min and max specified
cls(shape=(2, 3, 4), min_val=-0.5, max_val=0.5),
# Different shapes
cls(shape=(10,), min_val=-1.0, max_val=1.0),
cls(shape=(4, 8), min_val=0.0, max_val=None), # ReLU-like
cls(shape=(2, 8, 16), min_val=-0.25, max_val=0.75),
]
def create_model(self) -> nn.Module:
return ClampModel(self.min_val, self.max_val)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
# Create inputs with values that span beyond typical clamp range
x = torch.randn(self.shape) * 2 # values roughly in [-4, 4]
return (x,)
class GELUModel(nn.Module):
"""Simple model using GELU activation."""
def __init__(self, approximate: str = "none"):
super().__init__()
self.gelu = nn.GELU(approximate=approximate)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.gelu(x)
@register_test
class GELUTest(OpTestCase):
"""Test case for GELU activation."""
name = "gelu"
def __init__(self, shape: Tuple[int, ...] = (2, 16, 64), approximate: str = "none"):
self.shape = shape
self.approximate = approximate
self.name = f"gelu_{approximate}" if approximate != "none" else "gelu"
@classmethod
def get_test_configs(cls) -> List["GELUTest"]:
return [
cls(),
cls(shape=(4, 32, 128)),
cls(approximate="tanh"),
cls(shape=(4, 32, 128), approximate="tanh"),
]
def create_model(self) -> nn.Module:
return GELUModel(approximate=self.approximate)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
return (x,)
class SoftmaxModel(nn.Module):
"""Model that performs softmax along a specified dimension."""
def __init__(self, dim: int = -1):
super().__init__()
self.dim = dim
def forward(self, x: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.softmax(x, dim=self.dim)
@register_test
class SoftmaxTest(OpTestCase):
"""Test case for softmax op."""
name = "softmax"
rtol = 1e-4
atol = 1e-4
def __init__(
self,
shape: Tuple[int, ...] = (2, 3, 4),
dim: int = -1,
):
self.shape = shape
self.dim = dim
shape_str = "x".join(str(s) for s in shape)
self.name = f"softmax_{shape_str}_dim{dim}"
@classmethod
def get_test_configs(cls) -> List["SoftmaxTest"]:
return [
cls(shape=(2, 3, 4), dim=-1),
cls(shape=(2, 3, 4), dim=1),
cls(shape=(4, 8), dim=-1),
cls(shape=(2, 4, 8, 16), dim=-1),
]
def create_model(self) -> nn.Module:
return SoftmaxModel(dim=self.dim)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
return (x,)
class LogSoftmaxModel(nn.Module):
"""Model that applies log_softmax."""
def __init__(self, dim: int = -1):
super().__init__()
self.dim = dim
def forward(self, x: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.log_softmax(x, dim=self.dim)
@register_test
class LogSoftmaxTest(OpTestCase):
name = "log_softmax"
rtol = 1e-5
atol = 1e-5
def __init__(self, shape: Tuple[int, ...] = (2, 3, 4), dim: int = -1):
self.shape = shape
self.dim = dim
shape_str = "x".join(str(s) for s in shape)
self.name = f"log_softmax_{shape_str}_dim{dim}"
@classmethod
def get_test_configs(cls) -> List["LogSoftmaxTest"]:
return [
cls(shape=(2, 3, 4), dim=-1),
cls(shape=(10,), dim=0),
cls(shape=(4, 8), dim=1),
cls(shape=(2, 8, 16), dim=1),
cls(shape=(1, 128, 512), dim=-1),
]
def create_model(self) -> nn.Module:
return LogSoftmaxModel(dim=self.dim)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
return (x,)
class SqueezeModel(nn.Module):
"""Model that squeezes a tensor at specified dimensions."""
def __init__(self, dims: Optional[Tuple[int, ...]] = None):
super().__init__()
self.dims = dims
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.dims is None:
return torch.squeeze(x)
else:
return torch.squeeze(x, dim=self.dims)
@register_test
class SqueezeTest(OpTestCase):
"""Test case for squeeze op."""
name = "squeeze"
rtol = 1e-5
atol = 1e-5
def __init__(
self,
shape: Tuple[int, ...] = (1, 3, 1, 4),
dims: Optional[Tuple[int, ...]] = (0, 2),
):
self.shape = shape
self.dims = dims
shape_str = "x".join(str(s) for s in shape)
if dims is None:
dims_str = "all"
elif len(dims) == 0:
dims_str = "empty"
else:
dims_str = "_".join(str(d) for d in dims)
self.name = f"squeeze_{shape_str}_dims{dims_str}"
@classmethod
def get_test_configs(cls) -> List["SqueezeTest"]:
return [
cls(shape=(1, 3, 1, 4), dims=(0, 2)),
cls(shape=(1, 5, 1, 1), dims=(0,)),
cls(shape=(3, 1, 4), dims=(1,)),
cls(shape=(1, 1, 8), dims=(0, 1)),
cls(shape=(2, 1, 3, 1), dims=(1, 3)),
# Squeeze all singleton dims (no dims specified)
cls(shape=(1, 3, 1, 4), dims=None),
# Dims include non-size-1 axes (should be no-op for those axes)
cls(shape=(1, 1, 1, 8198), dims=(0, 1, 2, 3)),
]
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
return (x,)
def create_model(self) -> nn.Module:
return SqueezeModel(self.dims)
class UnsqueezeModel(nn.Module):
"""Model that unsqueezes a tensor at a given dimension."""
def __init__(self, dim: int = 0):
super().__init__()
self.dim = dim
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x.unsqueeze(self.dim)
@register_test
class UnsqueezeTest(OpTestCase):
"""Test case for unsqueeze op."""
name = "unsqueeze"
rtol = 1e-5
atol = 1e-5
def __init__(
self,
shape: Tuple[int, ...] = (2, 16, 64),
dim: int = 0,
):
self.shape = shape
self.dim = dim
self.name = f"unsqueeze_dim{dim}"
@classmethod
def get_test_configs(cls) -> List["UnsqueezeTest"]:
return [
cls(dim=0),
cls(dim=1),
cls(dim=-1),
]
def create_model(self) -> nn.Module:
return UnsqueezeModel(self.dim)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
return (x,)
class PermuteModel(nn.Module):
"""Model that permutes tensor dimensions."""
def __init__(self, dims: Tuple[int, ...] = (0, 2, 1, 3)):
super().__init__()
self.dims = dims
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x.permute(self.dims)
class TransposeModel(nn.Module):
"""Model that transposes two dimensions."""
def __init__(self, dim0: int = 1, dim1: int = 2):
super().__init__()
self.dim0 = dim0
self.dim1 = dim1
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x.transpose(self.dim0, self.dim1)
@register_test
class PermuteTest(OpTestCase):
"""Test case for permute and transpose ops."""
name = "permute"
rtol = 1e-5
atol = 1e-5
def __init__(
self,
shape: Tuple[int, ...] = (2, 8, 16, 64),
variant: str = "permute",
permute_dims: Tuple[int, ...] = (0, 2, 1, 3),
transpose_dims: Tuple[int, int] = (1, 2),
):
self.shape = shape
self.variant = variant
self.permute_dims = permute_dims
self.transpose_dims = transpose_dims
if variant == "transpose":
self.name = "transpose"
else:
self.name = "permute"
@classmethod
def get_test_configs(cls) -> List["PermuteTest"]:
return [
cls(variant="permute", permute_dims=(0, 2, 1, 3)),
cls(variant="transpose", transpose_dims=(1, 2)),
]
def create_model(self) -> nn.Module:
if self.variant == "transpose":
return TransposeModel(self.transpose_dims[0], self.transpose_dims[1])
else:
return PermuteModel(self.permute_dims)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
return (x,)
class NarrowModel(nn.Module):
"""Model that narrows a tensor along a dimension."""
def __init__(self, dim: int, start: int, length: int):
super().__init__()
self.dim = dim
self.start = start
self.length = length
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x.narrow(self.dim, self.start, self.length)
@register_test
class NarrowTest(OpTestCase):
"""Test case for tensor.narrow()."""
name = "narrow"
rtol = 1e-4
atol = 1e-4
def __init__(
self,
shape: Tuple[int, ...] = (4, 16, 8),
dim: int = 1,
start: int = 2,
length: int = 8,
):
self.shape = shape
self.dim = dim
self.start = start
self.length = length
self.name = f"narrow_dim{dim}_start{start}_len{length}"
@classmethod
def get_test_configs(cls) -> List["NarrowTest"]:
return [
cls(shape=(4, 16, 8), dim=1, start=2, length=8),
cls(shape=(8, 8), dim=0, start=1, length=4),
cls(shape=(2, 32, 4), dim=1, start=0, length=16),
]
def create_model(self) -> nn.Module:
return NarrowModel(self.dim, self.start, self.length)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
return (x,)
class SelectModel(nn.Module):
"""Model that selects a single index along a dimension.
torch.select(input, dim, index) returns input[..., index, ...] where
the indexing happens at dimension `dim`. The selected dimension is removed.
Maps to aten.select_copy.int -> MLX take(array, index, axis).
"""
def __init__(self, dim: int, index: int):
super().__init__()
self.dim = dim
self.index = index
def forward(self, x: torch.Tensor) -> torch.Tensor:
return torch.select(x, self.dim, self.index)
@register_test
class SelectTest(OpTestCase):
"""Test case for torch.select (aten.select_copy.int -> TakeNode)."""
name = "select"
rtol = 1e-5
atol = 1e-5
def __init__(
self,
shape: Tuple[int, ...] = (4, 8, 16),
dim: int = 1,
index: int = 3,
):
self.shape = shape
self.dim = dim
self.index = index
self.name = f"select_dim{dim}_idx{index}"
@classmethod
def get_test_configs(cls) -> List["SelectTest"]:
return [
cls(shape=(4, 8, 16), dim=0, index=2),
cls(shape=(4, 8, 16), dim=1, index=3),
cls(shape=(4, 8, 16), dim=2, index=0),
cls(shape=(4, 8, 16), dim=-1, index=5),
cls(shape=(2, 3), dim=0, index=1),
]
def create_model(self) -> nn.Module:
return SelectModel(self.dim, self.index)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
return (x,)
class SliceModel(nn.Module):
"""Model that slices a tensor along dimension 1."""
def __init__(self, start: int, stop: int):
super().__init__()
self.start = start
self.stop = stop
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x[:, self.start : self.stop]
class SliceDim0Model(nn.Module):
"""Model that slices a tensor along dimension 0."""
def __init__(self, start: int, stop: int):
super().__init__()
self.start = start
self.stop = stop
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x[self.start : self.stop]
@register_test
class SliceTest(OpTestCase):
"""Test case for tensor slicing."""
name = "slice"
rtol = 1e-4
atol = 1e-4
def __init__(
self,
shape: Tuple[int, ...] = (4, 16, 8),
dim: int = 1,
start: int = 2,
stop: int = 10,
):
self.shape = shape
self.dim = dim
self.start = start
self.stop = stop
self.name = f"slice_dim{dim}_{start}to{stop}"
@classmethod
def get_test_configs(cls) -> List["SliceTest"]:
return [
cls(shape=(4, 16, 8), dim=1, start=2, stop=10),
cls(shape=(8, 8), dim=0, start=1, stop=5),
cls(shape=(2, 32, 4), dim=1, start=0, stop=16),
]
def create_model(self) -> nn.Module:
if self.dim == 0:
return SliceDim0Model(self.start, self.stop)
return SliceModel(self.start, self.stop)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
return (x,)
class RepeatModel(nn.Module):
"""Model that repeats a tensor along specified dimensions."""
def __init__(self, repeats: Tuple[int, ...]):
super().__init__()
self.repeats = repeats
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x.repeat(*self.repeats)
@register_test
class RepeatTest(OpTestCase):
"""Test case for tensor.repeat()."""
name = "repeat"
rtol = 1e-4
atol = 1e-4
def __init__(
self,
input_shape: Tuple[int, ...] = (2, 3, 4),
repeats: Tuple[int, ...] = (2, 1, 3),
):
self.input_shape = input_shape
self.repeats = repeats
repeat_str = "x".join(str(r) for r in repeats)
self.name = f"repeat_{repeat_str}"
@classmethod
def get_test_configs(cls) -> List["RepeatTest"]:
return [
cls(input_shape=(2, 3), repeats=(2, 3)),
cls(input_shape=(2, 3, 4), repeats=(1, 2, 1)),
cls(input_shape=(4, 4), repeats=(3, 3)),
]
def create_model(self) -> nn.Module:
return RepeatModel(self.repeats)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.input_shape)
return (x,)
class CatNModel(nn.Module):
"""Model that concatenates N tensors along a dimension."""
def __init__(self, dim: int = 0, n: int = 3):
super().__init__()
self.dim = dim
self.n = n
def forward(self, *tensors: torch.Tensor) -> torch.Tensor:
return torch.cat(tensors[: self.n], dim=self.dim)
@register_test
class CatTest(OpTestCase):
name = "cat"
rtol = 1e-5
atol = 1e-5
def __init__(self, shapes: List[Tuple[int, ...]], dim: int = 0, tag: str = ""):
self.shapes = shapes
self.dim = dim
self.name = f"cat_{tag}" if tag else "cat"
@classmethod
def get_test_configs(cls) -> List["CatTest"]:
return [
cls(shapes=[(2, 3), (4, 3), (1, 3)], dim=0, tag="2d_dim0"),
cls(shapes=[(3, 2), (3, 4), (3, 1)], dim=1, tag="2d_dim1"),
cls(shapes=[(2, 3, 4), (5, 3, 4), (3, 3, 4)], dim=0, tag="3d_dim0"),
cls(shapes=[(3, 4), (2, 4)], dim=0, tag="two_tensors"),
cls(shapes=[(3, 2, 4), (3, 5, 4), (3, 1, 4)], dim=-2, tag="neg_dim"),
]
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
return tuple(torch.randn(s) for s in self.shapes)
def create_model(self) -> nn.Module:
return CatNModel(dim=self.dim, n=len(self.shapes))
class WhereModel(nn.Module):
"""Model that conditionally selects from x or y based on condition."""
def forward(
self, condition: torch.Tensor, x: torch.Tensor, y: torch.Tensor
) -> torch.Tensor:
return torch.where(condition, x, y)
@register_test
class WhereTest(OpTestCase):
"""Test case for where op."""
name = "where"
rtol = 1e-5
atol = 1e-5
def __init__(self, shape: Tuple[int, ...] = (2, 3, 4)):
self.shape = shape
shape_str = "x".join(str(s) for s in shape)
self.name = f"where_{shape_str}"
@classmethod
def get_test_configs(cls) -> List["WhereTest"]:
return [
cls(shape=(2, 3, 4)),
cls(shape=(4, 8)),
cls(shape=(2, 8, 16, 16)),
cls(shape=(1, 1, 128, 128)),
]
def create_model(self) -> nn.Module:
return WhereModel()
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
condition = torch.rand(self.shape) > 0.5
x = torch.randn(self.shape)
y = torch.randn(self.shape)
return (condition, x, y)
class PadModel(nn.Module):
"""Model that pads a tensor with a constant value."""
def __init__(self, pad: Tuple[int, ...], value: float = 0.0):
super().__init__()
self.pad = pad
self.value = value
def forward(self, x: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.pad(x, self.pad, mode="constant", value=self.value)
@register_test
class PadTest(OpTestCase):
name = "pad"
rtol = 1e-5
atol = 1e-5
def __init__(
self,
shape: Tuple[int, ...] = (2, 3, 4),
pad: Tuple[int, ...] = (1, 1, 1, 1),
value: float = 0.0,
):
self.shape = shape
self.pad = pad
self.value = value
shape_str = "x".join(str(s) for s in shape)
pad_str = "_".join(str(p) for p in pad)
self.name = f"pad_{shape_str}_p{pad_str}_v{int(value)}"
@classmethod
def get_test_configs(cls) -> List["PadTest"]:
return [
cls(shape=(2, 3, 4), pad=(1, 1, 1, 1), value=0.0),
cls(shape=(10,), pad=(2, 3), value=0.0),
cls(shape=(4, 8), pad=(1, 2), value=0.0),
cls(shape=(2, 8, 16), pad=(1, 1, 2, 2), value=0.0),
cls(shape=(1, 3, 32, 32), pad=(1, 1, 1, 1), value=0.0),
cls(shape=(2, 3, 4), pad=(1, 1, 1, 1), value=1.0),
]
def create_model(self) -> nn.Module:
return PadModel(self.pad, self.value)
def create_inputs(self) -> Tuple[torch.Tensor, ...]:
x = torch.randn(self.shape)
return (x,)
class LinearModel(nn.Module):
"""Simple linear layer for testing."""
def __init__(
self, in_features: int = 64, out_features: int = 128, bias: bool = True
):
super().__init__()
self.linear = nn.Linear(in_features, out_features, bias=bias)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.linear(x)