forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_binary_ufuncs.py
4473 lines (3940 loc) · 175 KB
/
test_binary_ufuncs.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: tests"]
import torch
import numpy as np
import sys
import itertools
from itertools import chain
from itertools import product
import math
import random
from numbers import Number
import warnings
import operator
from functools import partial
import torch.autograd.forward_ad as fwAD
from torch import inf, nan
from torch.testing._internal.common_utils import (
TestCase,
slowTest,
iter_indices,
run_tests,
gradcheck,
torch_to_numpy_dtype_dict,
numpy_to_torch_dtype_dict,
TEST_SCIPY,
set_default_dtype,
skipIfTorchDynamo,
)
from torch.testing._internal.common_device_type import (
expectedFailureMeta,
instantiate_device_type_tests,
onlyCUDA,
onlyCPU,
dtypes,
dtypesIfCUDA,
dtypesIfCPU,
deviceCountAtLeast,
precisionOverride,
onlyNativeDeviceTypes,
skipIf,
ops,
OpDTypes,
skipMeta,
)
from torch.testing import make_tensor
from torch.testing._internal.common_dtype import (
all_types_and_complex_and,
all_types_and,
integral_types,
complex_types,
integral_types_and,
floating_types_and,
floating_and_complex_types,
get_all_math_dtypes,
get_all_int_dtypes,
)
from torch.testing._internal.common_methods_invocations import (
binary_ufuncs,
binary_ufuncs_and_refs,
generate_elementwise_binary_tensors,
generate_elementwise_binary_small_value_tensors,
generate_elementwise_binary_large_value_tensors,
generate_elementwise_binary_extremal_value_tensors,
generate_elementwise_binary_broadcasting_tensors,
generate_elementwise_binary_with_scalar_samples,
generate_elementwise_binary_with_scalar_and_type_promotion_samples,
)
if TEST_SCIPY:
import scipy.special
import scipy.integrate
# TODO: update to use opinfos consistently
class TestBinaryUfuncs(TestCase):
# Generic tests for elementwise binary (AKA binary universal (u) functions (funcs))
# TODO: below contiguous tensor results are compared with a variety of noncontiguous results.
# It would be interesting to have the lhs and rhs have different discontiguities.
# Helper for comparing torch tensors and NumPy arrays
# TODO: should this or assertEqual also validate that strides are equal?
def assertEqualHelper(
self, actual, expected, msg, *, dtype, exact_dtype=True, **kwargs
):
assert isinstance(actual, torch.Tensor)
# Some NumPy functions return scalars, not arrays
if isinstance(expected, Number):
self.assertEqual(actual.item(), expected, msg=msg, **kwargs)
elif isinstance(expected, np.ndarray):
# Handles exact dtype comparisons between arrays and tensors
if exact_dtype:
# Allows array dtype to be float32 when comparing with bfloat16 tensors
# since NumPy doesn't support the bfloat16 dtype
# Also ops like scipy.special.erf, scipy.special.erfc, etc, promote float16
# to float32
if expected.dtype == np.float32:
assert actual.dtype in (
torch.float16,
torch.bfloat16,
torch.float32,
)
else:
assert expected.dtype == torch_to_numpy_dtype_dict[actual.dtype]
self.assertEqual(
actual,
torch.from_numpy(expected).to(actual.dtype),
msg,
exact_device=False,
**kwargs,
)
else:
self.assertEqual(actual, expected, msg, exact_device=False, **kwargs)
# Tests that the function and its (array-accepting) reference produce the same
# values on given tensors
def _test_reference_numerics(self, dtype, op, gen, equal_nan=True):
def _helper_reference_numerics(
expected, actual, msg, exact_dtype, equal_nan=True
):
if not torch.can_cast(
numpy_to_torch_dtype_dict[expected.dtype.type], dtype
):
exact_dtype = False
if dtype is torch.bfloat16 and expected.dtype == np.float32:
# Ref: https://github.com/pytorch/pytorch/blob/master/torch/testing/_internal/common_utils.py#L1149
self.assertEqualHelper(
actual,
expected,
msg,
dtype=dtype,
exact_dtype=exact_dtype,
rtol=16e-3,
atol=1e-5,
)
else:
self.assertEqualHelper(
actual,
expected,
msg,
dtype=dtype,
equal_nan=equal_nan,
exact_dtype=exact_dtype,
)
for sample in gen:
# Each sample input acquired from the generator is just one lhs tensor
# and one rhs tensor
l = sample.input
r = sample.args[0]
numpy_sample = sample.numpy()
l_numpy = numpy_sample.input
r_numpy = numpy_sample.args[0]
actual = op(l, r)
expected = op.ref(l_numpy, r_numpy)
# Crafts a custom error message for smaller, printable tensors
def _numel(x):
if isinstance(x, torch.Tensor):
return x.numel()
# Assumes x is a scalar
return 1
if _numel(l) <= 100 and _numel(r) <= 100:
msg = (
"Failed to produce expected results! Input lhs tensor was"
f" {l}, rhs tensor was {r}, torch result is {actual}, and reference result is"
f" {expected}."
)
else:
msg = None
exact_dtype = True
if isinstance(actual, torch.Tensor):
_helper_reference_numerics(
expected, actual, msg, exact_dtype, equal_nan
)
else:
for x, y in zip(expected, actual):
# testing multi-outputs results
_helper_reference_numerics(x, y, msg, exact_dtype, equal_nan)
# The following tests only apply to elementwise binary operators with references
binary_ufuncs_with_references = list(
filter(lambda op: op.ref is not None and op.ref is not None, binary_ufuncs)
)
@ops(binary_ufuncs_with_references)
def test_reference_numerics(self, device, dtype, op):
gen = generate_elementwise_binary_tensors(op, device=device, dtype=dtype)
self._test_reference_numerics(dtype, op, gen, equal_nan=True)
@ops(binary_ufuncs_with_references)
def test_reference_numerics_small_values(self, device, dtype, op):
if dtype is torch.bool:
self.skipTest("Doesn't support bool!")
gen = generate_elementwise_binary_small_value_tensors(
op, device=device, dtype=dtype
)
self._test_reference_numerics(dtype, op, gen, equal_nan=True)
@ops(
binary_ufuncs_with_references,
allowed_dtypes=(
torch.int16,
torch.int32,
torch.int64,
torch.float16,
torch.bfloat16,
torch.float32,
torch.float64,
torch.complex64,
torch.complex128,
),
)
def test_reference_numerics_large_values(self, device, dtype, op):
gen = generate_elementwise_binary_large_value_tensors(
op, device=device, dtype=dtype
)
self._test_reference_numerics(dtype, op, gen, equal_nan=True)
@ops(
binary_ufuncs_with_references,
allowed_dtypes=(
torch.float16,
torch.bfloat16,
torch.float32,
torch.float64,
torch.complex64,
torch.complex128,
),
)
def test_reference_numerics_extremal_values(self, device, dtype, op):
gen = generate_elementwise_binary_extremal_value_tensors(
op, device=device, dtype=dtype
)
self._test_reference_numerics(dtype, op, gen, equal_nan=True)
# tests broadcasting and noncontiguous broadcasting behavior
@ops(
binary_ufuncs_with_references,
allowed_dtypes=(
torch.long,
torch.float32,
),
)
def test_broadcasting(self, device, dtype, op):
gen = generate_elementwise_binary_broadcasting_tensors(
op, device=device, dtype=dtype
)
self._test_reference_numerics(dtype, op, gen, equal_nan=True)
@ops(
binary_ufuncs_with_references,
allowed_dtypes=(torch.long, torch.float32, torch.complex64),
)
def test_scalar_support(self, device, dtype, op):
gen = generate_elementwise_binary_with_scalar_samples(
op, device=device, dtype=dtype
)
self._test_reference_numerics(dtype, op, gen, equal_nan=True)
gen = generate_elementwise_binary_with_scalar_and_type_promotion_samples(
op, device=device, dtype=dtype
)
self._test_reference_numerics(dtype, op, gen, equal_nan=True)
@ops(binary_ufuncs)
def test_contig_vs_every_other(self, device, dtype, op):
lhs = make_tensor(
(1026,), device=device, dtype=dtype, **op.lhs_make_tensor_kwargs
)
rhs = make_tensor(
(1026,), device=device, dtype=dtype, **op.rhs_make_tensor_kwargs
)
lhs_non_contig = lhs[::2]
rhs_non_contig = rhs[::2]
self.assertTrue(lhs.is_contiguous())
self.assertTrue(rhs.is_contiguous())
self.assertFalse(lhs_non_contig.is_contiguous())
self.assertFalse(rhs_non_contig.is_contiguous())
expected = op(lhs, rhs)[::2]
actual = op(lhs_non_contig, rhs_non_contig)
self.assertEqual(expected, actual)
@ops(binary_ufuncs)
def test_contig_vs_transposed(self, device, dtype, op):
lhs = make_tensor(
(789, 357), device=device, dtype=dtype, **op.lhs_make_tensor_kwargs
)
rhs = make_tensor(
(789, 357), device=device, dtype=dtype, **op.rhs_make_tensor_kwargs
)
lhs_non_contig = lhs.T
rhs_non_contig = rhs.T
self.assertTrue(lhs.is_contiguous())
self.assertTrue(rhs.is_contiguous())
self.assertFalse(lhs_non_contig.is_contiguous())
self.assertFalse(rhs_non_contig.is_contiguous())
expected = op(lhs, rhs).T
actual = op(lhs_non_contig, rhs_non_contig)
self.assertEqual(expected, actual)
@ops(binary_ufuncs)
def test_non_contig(self, device, dtype, op):
shapes = ((5, 7), (1024,))
for shape in shapes:
lhs = make_tensor(
shape, dtype=dtype, device=device, **op.lhs_make_tensor_kwargs
)
rhs = make_tensor(
shape, dtype=dtype, device=device, **op.rhs_make_tensor_kwargs
)
lhs_non_contig = torch.empty(shape + (2,), device=device, dtype=dtype)[
..., 0
]
lhs_non_contig.copy_(lhs)
rhs_non_contig = torch.empty(shape + (2,), device=device, dtype=dtype)[
..., 0
]
rhs_non_contig.copy_(rhs)
self.assertTrue(lhs.is_contiguous())
self.assertTrue(rhs.is_contiguous())
self.assertFalse(lhs_non_contig.is_contiguous())
self.assertFalse(rhs_non_contig.is_contiguous())
expected = op(lhs, rhs)
actual = op(lhs_non_contig, rhs_non_contig)
self.assertEqual(expected, actual)
@ops(binary_ufuncs)
def test_non_contig_index(self, device, dtype, op):
shape = (2, 2, 1, 2)
lhs = make_tensor(
shape, dtype=dtype, device=device, **op.lhs_make_tensor_kwargs
)
rhs = make_tensor(
shape, dtype=dtype, device=device, **op.rhs_make_tensor_kwargs
)
lhs_non_contig = lhs[:, 1, ...]
lhs = lhs_non_contig.contiguous()
rhs_non_contig = rhs[:, 1, ...]
rhs = rhs_non_contig.contiguous()
self.assertTrue(lhs.is_contiguous())
self.assertTrue(rhs.is_contiguous())
self.assertFalse(lhs_non_contig.is_contiguous())
self.assertFalse(rhs_non_contig.is_contiguous())
expected = op(lhs, rhs)
actual = op(lhs_non_contig, rhs_non_contig)
self.assertEqual(expected, actual)
@ops(binary_ufuncs)
def test_non_contig_expand(self, device, dtype, op):
shapes = [(1, 3), (1, 7), (5, 7)]
for shape in shapes:
lhs = make_tensor(
shape, dtype=dtype, device=device, **op.lhs_make_tensor_kwargs
)
rhs = make_tensor(
shape, dtype=dtype, device=device, **op.rhs_make_tensor_kwargs
)
lhs_non_contig = lhs.clone().expand(3, -1, -1)
rhs_non_contig = rhs.clone().expand(3, -1, -1)
self.assertTrue(lhs.is_contiguous())
self.assertTrue(rhs.is_contiguous())
self.assertFalse(lhs_non_contig.is_contiguous())
self.assertFalse(rhs_non_contig.is_contiguous())
expected = op(lhs, rhs)
actual = op(lhs_non_contig, rhs_non_contig)
for i in range(3):
self.assertEqual(expected, actual[i])
@ops(binary_ufuncs)
def test_contig_size1(self, device, dtype, op):
shape = (5, 100)
lhs = make_tensor(
shape, dtype=dtype, device=device, **op.lhs_make_tensor_kwargs
)
rhs = make_tensor(
shape, dtype=dtype, device=device, **op.rhs_make_tensor_kwargs
)
lhs = lhs[:1, :50]
lhs_alt = torch.empty(lhs.size(), device=device, dtype=dtype)
lhs_alt.copy_(lhs)
rhs = rhs[:1, :50]
rhs_alt = torch.empty(rhs.size(), device=device, dtype=dtype)
rhs_alt.copy_(rhs)
self.assertTrue(lhs.is_contiguous())
self.assertTrue(rhs.is_contiguous())
self.assertTrue(lhs_alt.is_contiguous())
self.assertTrue(rhs_alt.is_contiguous())
expected = op(lhs, rhs)
actual = op(lhs_alt, rhs_alt)
self.assertEqual(expected, actual)
@ops(binary_ufuncs)
def test_contig_size1_large_dim(self, device, dtype, op):
shape = (5, 2, 3, 1, 4, 5, 3, 2, 1, 2, 3, 4)
lhs = make_tensor(
shape, dtype=dtype, device=device, **op.lhs_make_tensor_kwargs
)
rhs = make_tensor(
shape, dtype=dtype, device=device, **op.rhs_make_tensor_kwargs
)
lhs = lhs[:1, :, :, :, :, :, :, :, :, :, :, :]
lhs_alt = torch.empty(lhs.size(), device=device, dtype=dtype)
lhs_alt.copy_(lhs)
rhs = rhs[:1, :, :, :, :, :, :, :, :, :, :, :]
rhs_alt = torch.empty(rhs.size(), device=device, dtype=dtype)
rhs_alt.copy_(rhs)
self.assertTrue(lhs.is_contiguous())
self.assertTrue(rhs.is_contiguous())
self.assertTrue(lhs_alt.is_contiguous())
self.assertTrue(rhs_alt.is_contiguous())
expected = op(lhs, rhs)
actual = op(lhs_alt, rhs_alt)
self.assertEqual(expected, actual)
@ops(binary_ufuncs)
def test_batch_vs_slicing(self, device, dtype, op):
shape = (32, 512)
lhs = make_tensor(
shape, dtype=dtype, device=device, **op.lhs_make_tensor_kwargs
)
rhs = make_tensor(
shape, dtype=dtype, device=device, **op.rhs_make_tensor_kwargs
)
expected = op(lhs, rhs)
actual = []
for idx in range(32):
actual.append(op(lhs[idx], rhs[idx]))
actual = torch.stack(actual)
self.assertEqual(expected, actual)
# Tests that elementwise binary operators participate in type promotion properly
# NOTE: because the cross-product of all possible type promotion tests is huge, this
# just spot checks some handwritten cases.
# NOTE: It may be possible to refactor this test into something simpler
@ops(binary_ufuncs_and_refs, dtypes=OpDTypes.none)
def test_type_promotion(self, device, op):
supported_dtypes = op.supported_dtypes(torch.device(device).type)
make_lhs = partial(
make_tensor, (5,), device=device, **op.lhs_make_tensor_kwargs
)
make_rhs = partial(
make_tensor, (5,), device=device, **op.rhs_make_tensor_kwargs
)
make_rhs_scalar_tensor = partial(
make_tensor, (), device='cpu', **op.rhs_make_tensor_kwargs
)
def _supported(dtypes):
return all(x in supported_dtypes for x in dtypes)
# int x int type promotion
if _supported((torch.int16, torch.int32, torch.int64)):
lhs_i16 = make_lhs(dtype=torch.int16)
lhs_i32 = make_lhs(dtype=torch.int32)
lhs_i64 = make_lhs(dtype=torch.int64)
rhs_i16 = make_rhs(dtype=torch.int16)
rhs_i32 = make_rhs(dtype=torch.int32)
rhs_i64 = make_rhs(dtype=torch.int64)
if op.promotes_int_to_float:
default_dtype = torch.get_default_dtype()
self.assertEqual(op(lhs_i16, rhs_i32).dtype, default_dtype)
self.assertEqual(
op(lhs_i16, rhs_i32),
op(lhs_i16.to(default_dtype), rhs_i32.to(default_dtype)),
)
self.assertEqual(op(lhs_i32, rhs_i64).dtype, default_dtype)
self.assertEqual(
op(lhs_i32, rhs_i64),
op(lhs_i32.to(default_dtype), rhs_i64.to(default_dtype)),
)
elif op.always_returns_bool:
self.assertEqual(op(lhs_i16, rhs_i32).dtype, torch.bool)
self.assertEqual(op(lhs_i32, rhs_i64).dtype, torch.bool)
else: # standard type promotion
self.assertEqual(op(lhs_i16, rhs_i32).dtype, torch.int32)
self.assertEqual(
op(lhs_i16, rhs_i32), op(lhs_i16.to(torch.int32), rhs_i32)
)
self.assertEqual(op(lhs_i32, rhs_i64).dtype, torch.int64)
self.assertEqual(
op(lhs_i32, rhs_i64), op(lhs_i32.to(torch.int64), rhs_i64)
)
if op.supports_out:
if not op.promotes_int_to_float:
# Integers can be safely cast to other integer types
out = torch.empty_like(lhs_i64)
self.assertEqual(op(lhs_i16, rhs_i32, out=out).dtype, torch.int64)
self.assertEqual(op(lhs_i16, rhs_i32), out, exact_dtype=False)
out = torch.empty_like(lhs_i16)
self.assertEqual(op(lhs_i32, rhs_i64, out=out).dtype, torch.int16)
else:
# Float outs cannot be safely cast to integer types
with self.assertRaisesRegex(RuntimeError, "can't be cast"):
op(lhs_i16, rhs_i32, out=torch.empty_like(lhs_i64))
if not op.always_returns_bool:
# Neither integer nor float outs can be cast to bool
with self.assertRaisesRegex(RuntimeError, "can't be cast"):
op(
lhs_i16,
rhs_i32,
out=torch.empty_like(lhs_i64, dtype=torch.bool),
)
# All these output types can be cast to any float or complex type
out = torch.empty_like(lhs_i64, dtype=torch.float16)
self.assertEqual(op(lhs_i16, rhs_i32, out=out).dtype, torch.float16)
out = torch.empty_like(lhs_i64, dtype=torch.bfloat16)
self.assertEqual(op(lhs_i16, rhs_i32, out=out).dtype, torch.bfloat16)
out = torch.empty_like(lhs_i64, dtype=torch.float32)
self.assertEqual(op(lhs_i16, rhs_i32, out=out).dtype, torch.float32)
self.assertEqual(op(lhs_i16, rhs_i32), out, exact_dtype=False)
out = torch.empty_like(lhs_i64, dtype=torch.complex64)
self.assertEqual(op(lhs_i16, rhs_i32, out=out).dtype, torch.complex64)
self.assertEqual(op(lhs_i16, rhs_i32), out, exact_dtype=False)
# float x float type promotion
if _supported((torch.float32, torch.float64)):
lhs_f32 = make_lhs(dtype=torch.float32)
lhs_f64 = make_lhs(dtype=torch.float64)
rhs_f32 = make_rhs(dtype=torch.float32)
rhs_f64 = make_rhs(dtype=torch.float64)
if op.always_returns_bool:
self.assertEqual(op(lhs_f32, rhs_f64).dtype, torch.bool)
else: # normal float type promotion
self.assertEqual(op(lhs_f32, rhs_f64).dtype, torch.float64)
self.assertEqual(
op(lhs_f32, rhs_f64), op(lhs_f32.to(torch.float64), rhs_f64)
)
if op.supports_out:
# All these output types can be cast to any float or complex type
out = torch.empty_like(lhs_f64, dtype=torch.float16)
self.assertEqual(op(lhs_f32, rhs_f64, out=out).dtype, torch.float16)
out = torch.empty_like(lhs_f64, dtype=torch.bfloat16)
self.assertEqual(op(lhs_f32, rhs_f64, out=out).dtype, torch.bfloat16)
self.assertEqual(op(lhs_f32, rhs_f64), out, exact_dtype=False)
out = torch.empty_like(lhs_f64, dtype=torch.float32)
self.assertEqual(op(lhs_f32, rhs_f64, out=out).dtype, torch.float32)
self.assertEqual(op(lhs_f32, rhs_f64), out, exact_dtype=False)
out = torch.empty_like(lhs_f64, dtype=torch.complex64)
self.assertEqual(op(lhs_f32, rhs_f64, out=out).dtype, torch.complex64)
self.assertEqual(op(lhs_f32, rhs_f64), out, exact_dtype=False)
if not op.always_returns_bool:
# float outs can't be cast to an integer dtype
with self.assertRaisesRegex(RuntimeError, "can't be cast"):
op(
lhs_f32,
rhs_f64,
out=torch.empty_like(lhs_f64, dtype=torch.int64),
)
else:
# bool outs can be cast to an integer dtype
out = torch.empty_like(lhs_f64, dtype=torch.int64)
self.assertEqual(op(lhs_f32, rhs_f64, out=out).dtype, torch.int64)
self.assertEqual(op(lhs_f32, rhs_f64), out, exact_dtype=False)
# complex x complex type promotion
if _supported((torch.complex64, torch.complex128)):
lhs_c64 = make_lhs(dtype=torch.complex64)
lhs_c128 = make_lhs(dtype=torch.complex128)
rhs_c64 = make_rhs(dtype=torch.complex64)
rhs_c128 = make_rhs(dtype=torch.complex128)
if op.always_returns_bool:
self.assertEqual(op(lhs_c64, lhs_c128).dtype, torch.bool)
else: # normal complex type promotion
self.assertEqual(op(lhs_c64, rhs_c128).dtype, torch.complex128)
self.assertEqual(
op(lhs_c64, rhs_c128), op(lhs_c64.to(torch.complex128), rhs_c128)
)
if op.supports_out:
# All these output types can be cast to any or complex type
out = torch.empty_like(lhs_c64, dtype=torch.complex64)
self.assertEqual(op(lhs_c64, rhs_c128, out=out).dtype, torch.complex64)
result = op(lhs_c64, rhs_c128)
self.assertEqual(result, out.to(result.dtype))
if not op.always_returns_bool:
# complex outs can't be cast to float types
with self.assertRaisesRegex(RuntimeError, "can't be cast"):
op(
lhs_c64,
rhs_c128,
out=torch.empty_like(lhs_c64, dtype=torch.float64),
)
# complex outs can't be cast to an integer dtype
with self.assertRaisesRegex(RuntimeError, "can't be cast"):
op(
lhs_c64,
rhs_c128,
out=torch.empty_like(lhs_c64, dtype=torch.int64),
)
else:
# bool outs can be cast to a float type
out = torch.empty_like(lhs_c64, dtype=torch.float64)
self.assertEqual(
op(lhs_c64, rhs_c128, out=out).dtype, torch.float64
)
self.assertEqual(op(lhs_c64, rhs_c128), out, exact_dtype=False)
# bool outs can be cast to an integer dtype
out = torch.empty_like(lhs_f64, dtype=torch.int64)
self.assertEqual(op(lhs_f32, rhs_f64, out=out).dtype, torch.int64)
self.assertEqual(op(lhs_f32, rhs_f64), out, exact_dtype=False)
# int x float type promotion
# Note: float type is the result dtype
if _supported((torch.long, torch.float32)):
lhs_i64 = make_lhs(dtype=torch.int64)
rhs_f32 = make_rhs(dtype=torch.float32)
result = op(lhs_i64, rhs_f32)
expected_dtype = torch.float32 if not op.always_returns_bool else torch.bool
self.assertEqual(result.dtype, expected_dtype)
# float x complex type promotion
# Note: complex type with highest "value type" is the result dtype
if _supported((torch.float64, torch.complex64)):
lhs_f64 = make_lhs(dtype=torch.float64)
rhs_c64 = make_rhs(dtype=torch.complex64)
result = op(lhs_f64, rhs_c64)
expected_dtype = (
torch.complex128 if not op.always_returns_bool else torch.bool
)
self.assertEqual(result.dtype, expected_dtype)
# int x float scalar type promotion
# Note: default float dtype is the result dtype
if _supported((torch.int64, torch.float32)) and op.supports_rhs_python_scalar:
lhs_i64 = make_lhs(dtype=torch.int64)
rhs_f_scalar = 1.0
result = op(lhs_i64, rhs_f_scalar)
expected_dtype = (
torch.get_default_dtype() if not op.always_returns_bool else torch.bool
)
self.assertEqual(result.dtype, expected_dtype)
# repeats with a scalar float tensor, which should set the dtype
rhs_f32_scalar_tensor = make_rhs_scalar_tensor(dtype=torch.float32)
result = op(lhs_i64, rhs_f32_scalar_tensor)
expected_dtype = torch.float32 if not op.always_returns_bool else torch.bool
self.assertEqual(result.dtype, expected_dtype)
# Additional test with double
if _supported((torch.float64,)):
rhs_f64_scalar_tensor = make_rhs_scalar_tensor(dtype=torch.float64)
result = op(lhs_i64, rhs_f64_scalar_tensor)
expected_dtype = (
torch.float64 if not op.always_returns_bool else torch.bool
)
self.assertEqual(result.dtype, expected_dtype)
# float x complex scalar type promotion
# Note: result dtype is complex with highest "value type" among all tensors
if (
_supported((torch.float32, torch.complex64))
and op.supports_rhs_python_scalar
):
lhs_f32 = make_lhs(dtype=torch.float32)
rhs_c_scalar = complex(1, 1)
result = op(lhs_f32, rhs_c_scalar)
expected_dtype = (
torch.complex64 if not op.always_returns_bool else torch.bool
)
self.assertEqual(result.dtype, expected_dtype)
# repeats with a scalar complex tensor
rhs_c64_scalar_tensor = make_rhs_scalar_tensor(dtype=torch.complex64)
result = op(lhs_f32, rhs_c64_scalar_tensor)
expected_dtype = (
torch.complex64 if not op.always_returns_bool else torch.bool
)
self.assertEqual(result.dtype, expected_dtype)
# Additional test with complexdouble
if _supported((torch.complex128,)):
rhs_c128_scalar_tensor = make_rhs_scalar_tensor(dtype=torch.complex128)
result = op(lhs_f32, rhs_c128_scalar_tensor)
# Value type of 1D+ Tensor (lhs_f32) takes priority over scalar tensor (rhs_c128).
expected_dtype = (
torch.complex64 if not op.always_returns_bool else torch.bool
)
self.assertEqual(result.dtype, expected_dtype)
# float x float scalar tensor
# Note: result dtype is the type of the float tensor
if _supported((torch.float32, torch.float64)) and op.supports_rhs_python_scalar:
lhs_f32 = make_lhs(dtype=torch.float32)
rhs_f64_scalar_tensor = make_rhs_scalar_tensor(dtype=torch.float64)
result = op(lhs_f32, rhs_f64_scalar_tensor)
expected_dtype = torch.float32 if not op.always_returns_bool else torch.bool
self.assertEqual(result.dtype, expected_dtype)
# complex x complex scalar tensor
# Note: result dtype is the type of the complex tensor
if (
_supported((torch.complex64, torch.complex128))
and op.supports_rhs_python_scalar
):
lhs_c64 = make_lhs(dtype=torch.complex64)
rhs_c128_scalar_tensor = make_rhs_scalar_tensor(dtype=torch.complex128)
result = op(lhs_c64, rhs_c128_scalar_tensor)
expected_dtype = (
torch.complex64 if not op.always_returns_bool else torch.bool
)
self.assertEqual(result.dtype, expected_dtype)
# scalar x scalar
# Note: result dtype is default float type
if op.supports_two_python_scalars and _supported((torch.long, torch.float32)):
rhs_f_scalar = 2.
for lhs in (1, 1.):
result = op(lhs, rhs_f_scalar)
expected_dtype = torch.get_default_dtype() if not op.always_returns_bool else torch.bool
self.assertEqual(result.dtype, expected_dtype)
# TODO: move to error input test
@ops(binary_ufuncs, allowed_dtypes=(torch.float32,))
def test_not_broadcastable(self, device, dtype, op):
for shape_lhs, shape_rhs in (
((2,), (3,)),
((3, 1), (2, 1)),
((1, 3, 2), (3,)),
((3, 1, 2), (2, 1, 2)),
):
lhs = make_tensor(
shape_lhs, device=device, dtype=dtype, **op.lhs_make_tensor_kwargs
)
rhs = make_tensor(
shape_rhs, device=device, dtype=dtype, **op.rhs_make_tensor_kwargs
)
try:
broadcasted_shape = op(lhs, rhs).shape
except RuntimeError:
continue
msg = (
f"On {device}, torch.{op.name} broadcasts inputs shapes {shape_lhs} and {shape_rhs} into "
f"{broadcasted_shape}, although they are not broadcastable."
)
raise AssertionError(msg)
def test_add_broadcast_empty(self, device):
# empty + empty
self.assertRaises(
RuntimeError,
lambda: torch.randn(5, 0, device=device) + torch.randn(0, 5, device=device),
)
self.assertEqual(
torch.randn(5, 0, device=device),
torch.randn(0, device=device) + torch.randn(5, 0, device=device),
)
self.assertEqual(
torch.randn(5, 0, 0, device=device),
torch.randn(0, device=device) + torch.randn(5, 0, 1, device=device),
)
# scalar + empty
self.assertEqual(
torch.randn(5, 0, 6, device=device),
torch.randn((), device=device) + torch.randn(5, 0, 6, device=device),
)
# non-empty, empty
self.assertEqual(
torch.randn(0, device=device),
torch.randn(0, device=device) + torch.randn(1, device=device),
)
self.assertEqual(
torch.randn(0, 7, 0, 6, 5, 0, 7, device=device),
torch.randn(0, 7, 0, 6, 5, 0, 1, device=device)
+ torch.randn(1, 1, 5, 1, 7, device=device),
)
self.assertRaises(
RuntimeError,
lambda: torch.randn(7, 0, device=device) + torch.randn(2, 1, device=device),
)
def test_addcmul_scalars_as_floats(self, device):
# zero-dim variables that don't require grad should bind to scalar arguments
x = torch.tensor(2.0)
y = torch.tensor(3.0, device=device)
# 3 + (3 * 3) * 2
self.assertEqual(y.addcmul(y, y, value=x), 21)
x = torch.tensor(2.0, requires_grad=True)
self.assertRaises(Exception, lambda: y.addcmul(y, y, value=x))
# Tests that the binary operators and, or, and xor (as well as their reflected and inplace versions)
# work properly (AKA &, ||, ^ and &=, |=, ^=)
@dtypes(*integral_types_and(torch.bool))
def test_bitwise_ops(self, device, dtype):
# Tensor x Tensor and Tensor x Scalar ops
ops = (
operator.and_,
operator.iand,
operator.or_,
operator.ior,
operator.xor,
operator.ixor,
)
inplace_ops = (operator.iand, operator.ior, operator.ixor)
shapes = ((5,), (15, 15), (500, 500))
for op, shape in itertools.product(ops, shapes):
# Tests tensor x tensor case
a = make_tensor(shape, device=device, dtype=dtype)
b = make_tensor(shape, device=device, dtype=dtype)
a_np = a.cpu().clone().numpy()
b_np = b.cpu().clone().numpy()
self.assertEqual(op(a, b), op(a_np, b_np))
# Tests tensor x scalar case
a = make_tensor(shape, device=device, dtype=dtype)
b_scalar = make_tensor((), device="cpu", dtype=dtype).item()
a_np = a.cpu().clone().numpy()
self.assertEqual(op(a, b_scalar), op(a_np, b_scalar))
# Tests scalar x tensor case
a_scalar = make_tensor((), device="cpu", dtype=dtype).item()
b = make_tensor(shape, device=device, dtype=dtype)
b_np = b.cpu().clone().numpy()
self.assertEqual(op(a_scalar, b), op(a_scalar, b_np))
# Tests scalar x tensor case (for ops which aren't inplace)
if op in inplace_ops:
# Tests tensor x tensor case
a = make_tensor(shape, device=device, dtype=dtype)
b = make_tensor(shape, device=device, dtype=dtype)
a_np = a.cpu().clone().numpy()
b_np = b.cpu().clone().numpy()
op(a, b)
op(a_np, b_np)
self.assertEqual(a, a_np)
# Tests tensor x scalar case
a = make_tensor(shape, device=device, dtype=dtype)
b_scalar = make_tensor((), device="cpu", dtype=dtype).item()
a_np = a.cpu().clone().numpy()
op(a, b_scalar)
op(a_np, b_scalar)
self.assertEqual(a, a_np)
def test_inplace_division(self, device):
t = torch.rand(5, 5, device=device)
id_before = id(t)
t /= 2
id_after = id(t)
self.assertEqual(id_before, id_after)
@dtypes(*all_types_and(torch.half, torch.bfloat16))
def test_div_rounding_modes(self, device, dtype):
if dtype.is_floating_point:
low, high = -10.0, 10.0
else:
info = torch.iinfo(dtype)
low, high = info.min, info.max
a = make_tensor((100,), dtype=dtype, device=device, low=low, high=high)
b = make_tensor((100,), dtype=dtype, device=device, low=low, high=high)
# Avoid division by zero so we can test (a / b) * b == a
if dtype.is_floating_point:
eps = 0.1
b[(-eps < b) & (b < eps)] = eps
else:
b[b == 0] = 1
if not dtype.is_floating_point:
# floor(a / b) * b can be < a, so fixup slightly to avoid underflow
a = torch.where(a < 0, a + b, a)
d_true = torch.divide(a, b, rounding_mode=None)
self.assertTrue(d_true.is_floating_point())
self.assertEqual(d_true * b, a.to(d_true.dtype))
d_floor = torch.divide(a, b, rounding_mode="floor")
if dtype not in (torch.bfloat16, torch.half):
self.assertEqual(d_floor * b + torch.remainder(a, b), a)
else:
self.assertEqual(
d_floor * b + torch.remainder(a.float(), b.float()),
a,
exact_dtype=False,
)
d_trunc = torch.divide(a, b, rounding_mode="trunc")
rounding_unsupported = (
dtype == torch.half
and device != "cuda"
or dtype == torch.bfloat16
and device != "cpu"
)
d_ref = d_true.float() if rounding_unsupported else d_true
self.assertEqual(d_trunc, d_ref.trunc().to(dtype))
@dtypes(torch.bfloat16, torch.half, torch.float32, torch.float64)
def test_div_rounding_nonfinite(self, device, dtype):
# Compare division of special floating point values against NumPy
num = torch.tensor(
[1.0, -1.0, 0, 0.1, -0.1, np.pi, -np.pi, np.inf, -np.inf, np.nan],
dtype=dtype,
)
# Divide by zero is tested separately
denom = num[num != 0]
a, b = num[None, :].clone(), denom[:, None].clone()
# Compare bfloat16 against NumPy float
exact_dtype = dtype != torch.bfloat16
if exact_dtype:
an, bn = a.cpu().numpy(), b.cpu().numpy()
else:
an, bn = a.float().cpu().numpy(), b.float().cpu().numpy()
for mode, np_ref in ((None, np.true_divide), ("floor", np.floor_divide)):
expect = np_ref(an, bn)
kwargs = dict(rounding_mode=mode) if mode is not None else {}
with set_default_dtype(torch.double):
actual = torch.divide(a, b, **kwargs)
self.assertEqual(
actual,
torch.from_numpy(expect),
exact_device=False,
exact_dtype=exact_dtype,
)
# Compare contiguous (likely vectorized) against non-contiguous (not vectorized)