forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_foreach.py
1570 lines (1463 loc) · 57.6 KB
/
test_foreach.py
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
# Owner(s): ["module: mta"]
import itertools
import os
import random
import re
import unittest
import weakref
from contextlib import nullcontext
from numbers import Number
import torch
from torch.testing import make_tensor
from torch.testing._comparison import default_tolerances
from torch.testing._internal.common_cuda import TEST_MULTIGPU
from torch.testing._internal.common_device_type import (
dtypes,
instantiate_device_type_tests,
onlyCUDA,
OpDTypes,
ops,
)
from torch.testing._internal.common_dtype import (
all_types_and_complex_and,
floating_types,
floating_types_and,
integral_types_and,
)
from torch.testing._internal.common_methods_invocations import (
foreach_binary_op_db,
foreach_other_op_db,
foreach_pointwise_op_db,
foreach_reduce_op_db,
foreach_unary_op_db,
)
from torch.testing._internal.common_utils import (
gradcheck,
parametrize,
run_tests,
skipIfRocmVersionLessThan,
skipIfTorchDynamo,
TEST_WITH_ROCM,
TestCase,
)
_BOOL_SUB_ERR_MSG = "Subtraction, the `-` operator"
class RegularFuncWrapper:
def __init__(self, func):
self.func = func
def __call__(self, inputs, scalars=None, **kwargs):
if scalars is not None:
assert len(inputs) == 3
# We need to distribute each scalar to the regular func and it needs
# special consideration as it is a keyword only argument to the
# regular func. (Strangely, it is not a keyword only argument to the
# foreach func)
return [
self.func(*i, value=scalars[idx], **kwargs)
for idx, i in enumerate(zip(*inputs))
]
if len(inputs) == 2 and isinstance(inputs[1], (Number, torch.Tensor)):
# binary op with tensorlist and scalar.
inputs[1] = [inputs[1] for _ in range(len(inputs[0]))]
return [self.func(*i, **kwargs) for i in zip(*inputs)]
class ForeachFuncWrapper:
def __init__(self, func):
self.func = func
# Some foreach functions don't have in-place implementations.
self.is_inplace = False if func is None else func.__name__.endswith("_")
def __call__(self, inputs, is_cuda, expect_fastpath, **kwargs):
actual = None
zero_size = kwargs.pop("zero_size", False)
if (
is_cuda
and torch.autograd.kineto_available()
and torch.profiler.ProfilerActivity.CUDA
in torch.profiler.supported_activities()
):
with torch.profiler.profile() as p:
actual = self.func(*inputs, **kwargs)
keys = tuple([e.key for e in p.key_averages()])
mta_called = any("multi_tensor_apply_kernel" in k for k in keys)
assert (
mta_called == (expect_fastpath and (not zero_size))
), f"{mta_called=}, {expect_fastpath=}, {zero_size=}, {self.func.__name__=}, {keys=}"
else:
actual = self.func(*inputs, **kwargs)
if self.is_inplace:
assert id(inputs[0]) == id(actual)
return actual
class InplaceForeachVersionBumpCheck:
def __init__(
self,
testcase: TestCase,
tensorlist: "List[torch.Tensor]", # noqa: F821
) -> None:
self._testcase = testcase
self._tensorlist = tensorlist
self._orig_version_counts = [t._version for t in tensorlist]
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
# note(crcrpar): some methods e.g. `_binary_test` could call the given inplace function multiple times
self._testcase.assertGreaterEqual(
[t._version for t in self._tensorlist], self._orig_version_counts
)
def get_transform_func(num_tensors, dtype, device, is_fastpath):
def transform(t):
if not torch.is_tensor(t):
return t
if torch.is_tensor(t) and t.ndim == 0:
return t
return make_tensor(
(num_tensors, num_tensors),
dtype=dtype,
device=device,
requires_grad=True,
noncontiguous=not is_fastpath,
)
return transform
# note(crcrpar): `zero_size` is `False` unless (dtype, device) == (torch.float32, "cuda")
# as the pair would go through `multi_tensor_apply_kernel` if inputs are not zero size.
@unittest.mock.patch.dict(os.environ, {"KINETO_LOG_LEVEL": "5"})
class TestForeach(TestCase):
@property
def is_cuda(self):
return self.device_type == "cuda"
def _get_funcs(self, op):
return (
ForeachFuncWrapper(op.method_variant),
RegularFuncWrapper(op.ref),
ForeachFuncWrapper(op.inplace_variant),
RegularFuncWrapper(op.ref_inplace),
)
# note(crcrpar): Make sure 0-size tensors are appropriately ignored by `multi_tensor_apply`
# which is originally reported in https://github.com/pytorch/pytorch/issues/94865.
# rel:
# - https://github.com/pytorch/pytorch/pull/94655
# - https://github.com/pytorch/pytorch/issues/100701
# - https://github.com/pytorch/pytorch/pull/100811
@onlyCUDA
@ops(
foreach_unary_op_db
+ foreach_binary_op_db
+ foreach_pointwise_op_db
+ foreach_reduce_op_db
+ foreach_other_op_db,
dtypes=(torch.float32,),
)
def test_all_zero_size_tensors_do_not_launch_kernel(self, device, dtype, op):
wrapped_op, _, inplace_op, _ = self._get_funcs(op)
for sample in op.sample_zero_size_inputs(device, dtype):
if op.method_variant is not None:
wrapped_op(
(sample.input, *sample.args),
is_cuda=self.is_cuda,
expect_fastpath=True,
zero_size=True,
)
if op.inplace_variant is not None:
with InplaceForeachVersionBumpCheck(self, sample.input):
inplace_op(
(sample.input, *sample.args),
is_cuda=self.is_cuda,
expect_fastpath=True,
zero_size=True,
)
@skipIfRocmVersionLessThan((6, 0))
@ops(
foreach_unary_op_db
+ foreach_binary_op_db
+ foreach_pointwise_op_db
+ foreach_reduce_op_db
+ foreach_other_op_db,
)
@parametrize(
"noncontiguous,inplace",
[(False, False), (False, True), (True, False), (True, True)],
name_fn=lambda x, y: "{}_{}".format(
"fastpath" if not x else "slowpath", "inplace" if y else "outplace"
),
)
def test_parity(self, device, dtype, op, noncontiguous, inplace):
if inplace:
_, _, func, ref = self._get_funcs(op)
else:
func, ref, _, _ = self._get_funcs(op)
for sample in op.sample_inputs(
device, dtype, noncontiguous=noncontiguous, allow_higher_dtype_scalars=True
):
ref_kwargs = sample.kwargs
# div promotes ints to floats, so we cannot go on the fastpath there
div_slowpath = (
dtype in integral_types_and(torch.bool) and op.name == "_foreach_div"
)
expect_fastpath = not (
noncontiguous or sample.disable_fastpath or div_slowpath
)
ref_input, ctxmgr = sample.input, nullcontext()
if inplace:
with torch.no_grad():
ref_input = [t.detach().clone() for t in sample.input]
ctxmgr = InplaceForeachVersionBumpCheck(self, sample.input)
try:
with ctxmgr:
actual = func(
[sample.input, *sample.args],
self.is_cuda,
expect_fastpath,
**sample.kwargs,
)
except Exception as e:
with self.assertRaises(type(e)):
ref([ref_input, *sample.ref_args], **ref_kwargs)
else:
expected = ref([ref_input, *sample.ref_args], **ref_kwargs)
self.assertEqual(expected, actual)
def _binary_test(
self,
dtype,
op,
ref,
inputs,
is_fastpath,
is_inplace,
*,
alpha,
scalar_self_arg: bool,
):
ref_inputs = (
[[t.detach().clone() for t in inputs[0]], inputs[1]]
if is_inplace
else inputs
)
try:
with InplaceForeachVersionBumpCheck(
self, inputs[0]
) if op.is_inplace else nullcontext():
actual = op(inputs, self.is_cuda, is_fastpath)
except RuntimeError as e:
with self.assertRaisesRegex(type(e), re.escape(str(e).splitlines()[0])):
if not scalar_self_arg:
ref(ref_inputs)
else:
[ref.func(ref_inputs[0], t) for t in ref_inputs[1]]
else:
expected = (
ref(ref_inputs)
if not scalar_self_arg
else [ref.func(ref_inputs[0], t) for t in ref_inputs[1]]
)
self.assertEqual(actual, expected)
if alpha is not None and not scalar_self_arg:
kwargs = {"alpha": alpha}
ref_inputs = inputs
try:
op_kwargs = {}
op_kwargs.update(kwargs)
with InplaceForeachVersionBumpCheck(
self, inputs[0]
) if op.is_inplace else nullcontext():
actual = op(inputs, self.is_cuda, is_fastpath, **op_kwargs)
except RuntimeError as e:
with self.assertRaisesRegex(type(e), re.escape(str(e).splitlines()[0])):
ref(ref_inputs, **kwargs)
else:
expected = ref(ref_inputs, **kwargs)
if dtype in (torch.float16, torch.bfloat16) and TEST_WITH_ROCM:
self.assertEqual(
expected, actual, atol=1.0e-3, rtol=default_tolerances(dtype)[0]
)
else:
self.assertEqual(expected, actual)
@ops(filter(lambda op: op.supports_scalar_self_arg, foreach_binary_op_db))
@parametrize("is_fastpath", (True, False))
def test_binary_op_with_scalar_self_support(self, device, dtype, op, is_fastpath):
def clone(arg):
if isinstance(arg, (list, tuple)):
return [clone(a) for a in arg]
if torch.is_tensor(arg):
return arg.detach().clone().requires_grad_()
else:
return arg
scalar_self_arg_test_complete = False
for i, sample in enumerate(
op.sample_inputs(
device,
dtype,
noncontiguous=not is_fastpath,
allow_higher_dtype_scalars=True,
)
):
(rhs_arg,) = sample.args
kwargs = {} or sample.kwargs
alpha = kwargs.pop("alpha", None)
wrapped_op, ref, inplace_op, inplace_ref = self._get_funcs(op)
if isinstance(rhs_arg, Number) and not scalar_self_arg_test_complete:
scalar_self_arg_test_complete = True
self._binary_test(
dtype,
wrapped_op,
ref,
[rhs_arg, sample.input],
is_fastpath,
False,
alpha=alpha,
scalar_self_arg=True,
)
if op.supports_autograd and dtype == torch.float32:
transformed_sample = sample.transform(
get_transform_func(
len(sample.input), dtype, device, is_fastpath
)
)
tensors = transformed_sample.input
(rhs_arg,) = transformed_sample.args
ref_tensors, ref_rhs_arg = clone(tensors), clone(rhs_arg)
sum(
wrapped_op(
[rhs_arg, tensors], is_cuda=False, expect_fastpath=False
)
).mean().backward()
sum(ref.func(ref_rhs_arg, t) for t in ref_tensors).mean().backward()
self.assertEqual(
[t.grad for t in tensors], [t.grad for t in ref_tensors]
)
@ops(foreach_pointwise_op_db)
@parametrize("is_fastpath", (True, False))
def test_pointwise_op_with_tensor_of_scalarlist_overload(
self, device, dtype, op, is_fastpath
):
for sample in op.sample_inputs(
device,
dtype,
noncontiguous=not is_fastpath,
allow_higher_dtype_scalars=True,
):
assert isinstance(sample.args, tuple)
assert len(sample.args) == 2
inputs = [sample.input, *sample.args]
kwargs = sample.kwargs.copy()
disable_fastpath = sample.disable_fastpath and is_fastpath
wrapped_op, ref, inplace_op, inplace_ref = self._get_funcs(op)
scalars = kwargs.pop("scalars", None)
if is_fastpath and scalars:
sample = sample.transform(
lambda t: t.detach().clone() if torch.is_tensor(t) else t
)
inputs = [sample.input, *sample.args]
tensor_values = torch.tensor(scalars)
# 1D Tensor of scalars
for is_inplace, op_, ref_ in (
(False, wrapped_op, ref),
(True, inplace_op, inplace_ref),
):
self._pointwise_test(
op_,
ref_,
inputs,
is_fastpath and not disable_fastpath,
is_inplace,
scalars=tensor_values,
**kwargs,
)
self._pointwise_test(
op_,
ref_,
inputs,
is_fastpath and not disable_fastpath,
is_inplace,
scalars=tensor_values[0],
custom_values_err="Expected packed scalar Tensor to be of dimension 1. Got 0 instead.",
**kwargs,
)
if self.is_cuda:
self._pointwise_test(
op_,
ref_,
inputs,
is_fastpath and not disable_fastpath,
is_inplace,
scalars=tensor_values.cuda(),
custom_values_err="Expected scalars to be on CPU, got cuda:0 instead.",
**kwargs,
)
self._pointwise_test(
op_,
ref_,
inputs,
is_fastpath and not disable_fastpath,
is_inplace,
scalars=tensor_values[:2],
custom_values_err=f"Expected length of scalars to match input of length {len(scalars)} but got 2 instead.",
**kwargs,
)
self._pointwise_test(
op_,
ref_,
inputs,
is_fastpath and not disable_fastpath,
is_inplace,
scalars=torch.tensor([[0, 1], [2, 3]])[:, 1],
custom_values_err="Expected scalars to be contiguous.",
**kwargs,
)
# Tests of implicit broadcasting
N = len(sample.input)
inputs = [
[
make_tensor(
(N, N),
device=device,
dtype=dtype,
noncontiguous=not is_fastpath,
)
for _ in range(N)
],
[
make_tensor(
(N - i, 1),
device=device,
dtype=dtype,
noncontiguous=not is_fastpath,
)
for i in range(N)
],
[
make_tensor(
(1, N - i),
device=device,
dtype=dtype,
noncontiguous=not is_fastpath,
)
for i in range(N)
],
]
self._pointwise_test(
wrapped_op,
ref,
inputs,
is_fastpath and disable_fastpath,
is_inplace=False,
scalars=scalars,
**kwargs,
)
self._pointwise_test(
inplace_op,
inplace_ref,
inputs,
is_fastpath and disable_fastpath,
is_inplace=True,
scalars=scalars,
**kwargs,
)
def _pointwise_test(
self,
op,
ref,
inputs,
is_fastpath,
is_inplace,
*,
scalars=None,
custom_values_err=None,
**kwargs,
):
ref_inputs = (
[[t.detach().clone() for t in inputs[0]], inputs[1], inputs[2]]
if is_inplace
else inputs
)
try:
with (
InplaceForeachVersionBumpCheck(self, inputs[0])
if is_inplace
else nullcontext()
):
actual = op(inputs, self.is_cuda, is_fastpath, **kwargs)
except RuntimeError as e:
with self.assertRaisesRegex(type(e), re.escape(str(e).splitlines()[0])):
ref(ref_inputs, **kwargs)
else:
expected = ref(ref_inputs, **kwargs)
self.assertEqual(expected, actual)
if scalars is not None:
kwargs = kwargs.copy()
kwargs["scalars"] = scalars
try:
actual = op(inputs, self.is_cuda, is_fastpath, **kwargs)
except RuntimeError as e:
# Match with error messages from regular non-foreach reference if no
# custom error message was provided.
if custom_values_err is None:
with self.assertRaisesRegex(
type(e), re.escape(str(e).splitlines()[0])
):
ref(ref_inputs, **kwargs)
else:
self.assertEqual(re.escape(str(e)), re.escape(custom_values_err))
else:
expected = ref(ref_inputs, **kwargs)
self.assertEqual(expected, actual)
@dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))
def test_add_scalar_with_empty_list_and_empty_tensor(self, device, dtype):
# TODO: enable empty list case
for tensors in [
[torch.randn([0], device=device, dtype=dtype)],
[torch.empty_strided((0, 1), (0, 0), dtype=dtype, device=device)],
]:
res = torch._foreach_add(tensors, 1)
self.assertEqual(res, tensors)
torch._foreach_add_(tensors, 1)
self.assertEqual(res, tensors)
# Regression test for https://github.com/pytorch/pytorch/issues/113156
torch._foreach_mul_(tensors, 1)
@onlyCUDA
@dtypes(torch.float32)
def test_foreach_check_stride_ignore_dims_of_one(self, device, dtype):
# default tensor stride is (9, 9, 3, 1).
tensor = torch.ones((2, 1, 3, 3), device=device, dtype=dtype)
strided_tensor = torch.ones(
(2, 1, 3, 3), device=device, dtype=dtype
).as_strided((2, 1, 3, 3), (9, 1, 3, 1))
left_inputs = [tensor, strided_tensor]
right_inputs = [strided_tensor, tensor]
compare_result = tensor + strided_tensor
foreach_add_check_ = ForeachFuncWrapper(torch._foreach_add)
out = foreach_add_check_(
(left_inputs, right_inputs), is_cuda=True, expect_fastpath=True
)
for res in out:
self.assertEqual(res, compare_result)
@ops(
filter(lambda op: op.supports_out, foreach_binary_op_db),
dtypes=OpDTypes.supported,
)
def test_binary_op_scalar_with_overlapping_tensors(self, device, dtype, op):
foreach_op, ref = op.method_variant, op.ref
tensors = [torch.ones(1, 1, device=device, dtype=dtype).expand(2, 1, 3)]
if ref == torch.sub and dtype == torch.bool:
with self.assertRaisesRegex(RuntimeError, re.escape(_BOOL_SUB_ERR_MSG)):
[ref(t, 1) for t in tensors]
with self.assertRaisesRegex(RuntimeError, re.escape(_BOOL_SUB_ERR_MSG)):
foreach_op(tensors, 1)
return
expected = [ref(t, 1) for t in tensors]
res = foreach_op(tensors, 1)
self.assertEqual(res, expected)
@ops(
filter(lambda op: op.supports_out, foreach_binary_op_db),
allowed_dtypes=[torch.float],
)
def test_binary_op_scalar_with_different_tensor_dtypes(self, device, dtype, op):
foreach_op = op.method_variant
tensors = [
torch.tensor([1.1], dtype=torch.float, device=device),
torch.tensor([1], dtype=torch.long, device=device),
]
runtime_error = None
try:
foreach_op(tensors, 1)
except RuntimeError as e:
runtime_error = e
self.assertIsNone(runtime_error)
@skipIfTorchDynamo("Different error msgs, TODO")
@ops(
filter(lambda op: op.supports_out, foreach_binary_op_db),
dtypes=OpDTypes.supported,
)
def test_binary_op_list_error_cases(self, device, dtype, op):
foreach_op, foreach_op_, ref, ref_ = (
op.method_variant,
op.inplace_variant,
op.ref,
op.ref_inplace,
)
tensors1 = []
tensors2 = []
ops_to_test = [foreach_op, foreach_op_]
# Empty lists
for fop in ops_to_test:
with self.assertRaisesRegex(
RuntimeError, "Tensor list must have at least one tensor."
):
fop(tensors1, tensors2)
# One empty list
tensors1.append(torch.tensor([1], device=device, dtype=dtype))
for fop in ops_to_test:
with self.assertRaisesRegex(
RuntimeError,
"Tensor list must have same number of elements as scalar list.",
):
fop(tensors1, tensors2)
# Lists have different amount of tensors
tensors2.append(torch.tensor([1], device=device))
tensors2.append(torch.tensor([1], device=device))
for fop in ops_to_test:
with self.assertRaisesRegex(
RuntimeError,
"Tensor lists must have the same number of tensors, got 1 and 2",
):
fop(tensors1, tensors2)
with self.assertRaisesRegex(
RuntimeError,
"Tensor lists must have the same number of tensors, got 2 and 1",
):
fop(tensors2, tensors1)
# Corresponding tensors with different sizes that aren't compatible with broadcast
# If sizes are different then foreach chooses slow path, thus error messages are expected
# to be the same as torch regular function.
tensors1 = [torch.zeros(10, 10, device=device, dtype=dtype) for _ in range(10)]
tensors2 = [torch.ones(11, 11, device=device, dtype=dtype) for _ in range(10)]
if dtype == torch.bool and foreach_op == torch._foreach_sub:
for fop in ops_to_test:
with self.assertRaisesRegex(RuntimeError, re.escape(_BOOL_SUB_ERR_MSG)):
fop(tensors1, tensors2)
return
with self.assertRaisesRegex(
RuntimeError,
r"The size of tensor a \(10\) must match the size of tensor b \(11\) at non-singleton dimension 1",
):
foreach_op(tensors1, tensors2)
with self.assertRaisesRegex(
RuntimeError,
r"The size of tensor a \(10\) must match the size of tensor b \(11\) at non-singleton dimension 1",
):
foreach_op_(tensors1, tensors2)
# different devices
if self.device_type == "cuda" and torch.cuda.device_count() > 1:
tensor1 = torch.zeros(10, 10, device="cuda:0", dtype=dtype)
tensor2 = torch.ones(10, 10, device="cuda:1", dtype=dtype)
with self.assertRaisesRegex(
RuntimeError, "Expected all tensors to be on the same device"
):
foreach_op([tensor1], [tensor2])
if (
dtype in integral_types_and(torch.bool)
and foreach_op == torch._foreach_div
):
with self.assertRaisesRegex(RuntimeError, "result type"):
foreach_op_([tensor1], [tensor2])
else:
with self.assertRaisesRegex(
RuntimeError, "Expected all tensors to be on the same device"
):
foreach_op_([tensor1], [tensor2])
@unittest.skipIf(not torch.cuda.is_available(), "CUDA not found")
@ops(
filter(lambda op: op.supports_out, foreach_binary_op_db),
dtypes=OpDTypes.supported,
)
def test_binary_op_list_slow_path(self, device, dtype, op):
foreach_op, native_op, foreach_op_, native_op_ = self._get_funcs(op)
# 0-strides
tensor1 = make_tensor((10, 10), dtype=dtype, device=device)
tensor2 = make_tensor((1,), device=device, dtype=dtype).expand_as(tensor1)
inputs = ([tensor1], [tensor2])
self._binary_test(
dtype,
foreach_op,
native_op,
inputs,
is_fastpath=False,
is_inplace=False,
alpha=None,
scalar_self_arg=False,
)
self._binary_test(
dtype,
foreach_op_,
native_op_,
inputs,
is_fastpath=False,
is_inplace=True,
alpha=None,
scalar_self_arg=False,
)
# different strides
tensor1 = torch.zeros(10, 10, device=device, dtype=dtype)
tensor2 = torch.ones(10, 10, device=device, dtype=dtype)
inputs = ([tensor1], [tensor2.t()])
self._binary_test(
dtype,
foreach_op,
native_op,
inputs,
is_fastpath=False,
is_inplace=False,
alpha=None,
scalar_self_arg=False,
)
self._binary_test(
dtype,
foreach_op_,
native_op_,
inputs,
is_fastpath=False,
is_inplace=True,
alpha=None,
scalar_self_arg=False,
)
# non contiguous
tensor1 = make_tensor(
(5, 2, 1, 3), device=device, dtype=dtype, noncontiguous=True
)
tensor2 = make_tensor(
(5, 2, 1, 3), device=device, dtype=dtype, noncontiguous=True
)
self.assertFalse(tensor1.is_contiguous())
self.assertFalse(tensor2.is_contiguous())
inputs = ([tensor1], [tensor2])
self._binary_test(
dtype,
foreach_op,
native_op,
inputs,
is_fastpath=False,
is_inplace=False,
alpha=None,
scalar_self_arg=False,
)
self._binary_test(
dtype,
foreach_op_,
native_op_,
inputs,
is_fastpath=False,
is_inplace=True,
alpha=None,
scalar_self_arg=False,
)
# sliced tensor
tensor1 = make_tensor((5, 2, 1, 3), device=device, dtype=dtype)
tensor2 = make_tensor((5, 2, 1, 3 * 7), device=device, dtype=dtype)[
:, :, :, ::7
]
inputs = ([tensor1], [tensor2])
self._binary_test(
dtype,
foreach_op,
native_op,
inputs,
is_fastpath=False,
is_inplace=False,
alpha=None,
scalar_self_arg=False,
)
self._binary_test(
dtype,
foreach_op_,
native_op_,
inputs,
is_fastpath=False,
is_inplace=True,
alpha=None,
scalar_self_arg=False,
)
@ops(
filter(lambda op: op.supports_out, foreach_binary_op_db),
dtypes=floating_types_and(torch.half, torch.bfloat16),
)
def test_binary_op_float_inf_nan(self, device, dtype, op):
inputs = (
[
torch.tensor([float("inf")], device=device, dtype=dtype),
torch.tensor([-float("inf")], device=device, dtype=dtype),
torch.tensor([float("nan")], device=device, dtype=dtype),
torch.tensor([float("nan")], device=device, dtype=dtype),
],
[
torch.tensor([-float("inf")], device=device, dtype=dtype),
torch.tensor([float("inf")], device=device, dtype=dtype),
torch.tensor([float("inf")], device=device, dtype=dtype),
torch.tensor([float("nan")], device=device, dtype=dtype),
],
)
op, ref, inplace_op, inplace_ref = self._get_funcs(op)
self._binary_test(
dtype, op, ref, inputs, True, False, alpha=None, scalar_self_arg=False
)
self._binary_test(
dtype,
inplace_op,
inplace_ref,
inputs,
True,
True,
alpha=None,
scalar_self_arg=False,
)
# note: Below three tests (postfixed with `_tensors_on_different_devices`)
# checks whether foreach works with lists of tensors on different devices
# but tensors of the same index are on the same device, e.g., ['cuda', 'cpu].
@onlyCUDA
@ops(foreach_unary_op_db)
def test_unary_op_tensors_on_different_devices(self, device, dtype, op):
method, ref, inplace_method, ref_inplace = self._get_funcs(op)
# tensors: ['cuda', 'cpu]
tensors = next(
iter(
op.sample_inputs(
device,
dtype,
num_input_tensors=[2],
allow_higher_dtype_scalars=True,
)
)
).input
tensors[1] = tensors[1].to("cpu")
if not op.supports_out:
try:
actual = method((tensors,), False, False, zero_size=False)
except RuntimeError as e:
with self.assertRaisesRegex(type(e), str(e).splitlines()[0]):
ref((tensors,))
else:
expected = ref((tensors,))
self.assertEqual(expected, actual)
try:
inplace_method((tensors,), False, False, zero_size=False)
except RuntimeError as e:
with self.assertRaisesRegex(type(e), str(e).splitlines()[0]):
ref_inplace((tensors,))
else:
if not op.supports_out:
self.assertEqual(expected, tensors)
else:
self.assertEqual([torch.zeros_like(t) for t in tensors], tensors)
@onlyCUDA
@ops(filter(lambda op: op.supports_out, foreach_binary_op_db))
def test_binary_op_tensors_on_different_devices(self, device, dtype, op):
_cuda_tensors = next(
iter(
op.sample_inputs(
device,
dtype,
num_input_tensors=[2],
same_size=True,
allow_higher_dtype_scalars=True,
)
)
).input
_cpu_tensors = next(
iter(
op.sample_inputs(
"cpu",
dtype,
num_input_tensors=[2],
same_size=True,
allow_higher_dtype_scalars=True,
)
)
).input
tensors1, tensors2 = list(zip(_cuda_tensors, _cpu_tensors))
foreach_op, foreach_op_ = op.method_variant, op.inplace_variant
native_op, native_op_ = op.ref, op.ref_inplace
try:
actual = foreach_op(tensors1, tensors2)
except RuntimeError as e:
with self.assertRaisesRegex(type(e), re.escape(str(e).splitlines()[0])):
[native_op(t1, t2) for t1, t2 in zip(tensors1, tensors2)]
else:
expected = [native_op(t1, t2) for t1, t2 in zip(tensors1, tensors2)]
self.assertEqual(expected, actual)
try:
foreach_op_(tensors1, tensors2)
except RuntimeError as e:
with self.assertRaisesRegex(type(e), re.escape(str(e).splitlines()[0])):
[native_op_(t1, t2) for t1, t2 in zip(tensors1, tensors2)]
else:
self.assertEqual(actual, tensors1)
@onlyCUDA
@ops(foreach_pointwise_op_db, allowed_dtypes=floating_types())
def test_pointwise_op_tensors_on_different_devices(self, device, dtype, op):
# tensors1: ['cuda', 'cpu]
# tensors2: ['cuda', 'cpu]
# tensors3: ['cuda', 'cpu]
# first tensorlist is zero-size when float32
_cuda_tensors = list(
op.sample_inputs(
device,
dtype,
num_input_tensors=[3],
same_size=True,
allow_higher_dtype_scalars=True,
)
)[int(dtype == torch.float32)].input
_cpu_tensors = next(
iter(
op.sample_inputs(
"cpu",
dtype,
num_input_tensors=[3],
same_size=True,
allow_higher_dtype_scalars=True,
)
)
).input
tensors1, tensors2, tensors3 = list(zip(_cuda_tensors, _cpu_tensors))
foreach_op, foreach_op_, native_op = (
op.method_variant,
op.inplace_variant,
op.ref,
)
actual = foreach_op(tensors1, tensors2, tensors3)
expected = [native_op(*_cuda_tensors), native_op(*_cpu_tensors)]
self.assertEqual(expected, actual)
# note(mkozuki): Limiting dtypes to FP32&FP64, we can safely run inplace ops.
foreach_op_(tensors1, tensors2, tensors3)
self.assertEqual(expected, tensors1)
# note: BFloat16 has the same number of exponent bits as FP32
# so if squared L2 norm overflows in BF16, then it also overflows in FP32.
@onlyCUDA
@ops(
[o for o in foreach_reduce_op_db if "norm" in o.name],
allowed_dtypes=(torch.half, torch.bfloat16),
)
def test_foreach_l2_large_value_input(self, device, dtype, op):
ord, N = 2, 10
max_value = torch.finfo(dtype).max
scaler = torch.tensor([max_value]).sqrt().to(device=device, dtype=dtype)
inputs = (
[
t * scaler
for t in next(
iter(
op.sample_inputs(
device,
dtype,
requries_grad=True,
num_input_tensors=[N],
low=1,
)
)
).input
][:-1],
)
# make sure that the min. of squared L2 norm value per tensor is greater than the max value of `dtype`.
self.assertTrue(scaler * scaler * N > max_value)
fn, ref_fn, *_ = self._get_funcs(op)
actual = fn(
inputs, is_cuda=True, expect_fastpath=True, ord=ord, zero_size=False
)
expect = ref_fn(inputs, ord=ord)