forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_namedtensor.py
2062 lines (1702 loc) · 80.6 KB
/
test_namedtensor.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: named tensor"]
import unittest
from torch.testing._internal.common_utils import TestCase, run_tests, TEST_NUMPY
from torch.testing._internal.common_cuda import TEST_CUDA
from torch.testing._internal.common_device_type import get_all_device_types
from collections import namedtuple, OrderedDict
import itertools
import functools
import torch
from torch import Tensor
import torch.nn.functional as F
from multiprocessing.reduction import ForkingPickler
import pickle
import io
import sys
import warnings
def pass_name_to_python_arg_parser(name):
x = torch.empty(2, names=(name,))
def flatten(lst):
return [item for sublist in lst for item in sublist]
Function = namedtuple('TestCase', ['name', 'lambd'])
def parse_compressed_namedshape(string):
# This is a metalanguage for describing a shape of a tensor compactly.
# 'N:3,C:2' -> size = [3, 2], names: ['N', 'C']
# 'None:3,None:2' -> size = [3, 2], names: ['None', 'None']
# '3,2' -> size = [3, 2], names=None passed to ctor.
def parse_name(maybe_name):
maybe_name = maybe_name.strip()
if maybe_name == 'None':
return None
return maybe_name
string = string.strip()
# '' -> size: [], names:None
if len(string) == 0:
return None, []
# '3, 2' -> size = [3, 2], None names.
if ':' not in string:
return None, [int(size) for size in string.split(',')]
dims = string.split(',')
tuples = [dim.split(':') for dim in dims]
return zip(*[(parse_name(name), int(size)) for name, size in tuples])
def create(namedshape, factory=torch.randn):
# namedshape: str
names, shape = parse_compressed_namedshape(namedshape)
return factory(shape, names=names)
def out_fn(operator):
@functools.wraps(operator)
def fn(*inputs):
return operator(*inputs[1:], out=inputs[0])
return fn
class TestNamedTensor(TestCase):
def test_aaa_must_run_first_check_experimental_warning(self):
# TODO(rzou): It would be nice for this to be a "real" python warning.
# Right now this error message only prints once and doesn't respect
# warnings.simplefilter behavior (where python users can control whether
# or not to display warnings once, all the time, or never).
with warnings.catch_warnings(record=True) as warns:
x = torch.randn(3, 3, names=('N', 'C'))
self.assertEqual(len(warns), 1)
self.assertTrue(str(warns[0].message).startswith(
'Named tensors and all their associated APIs are an experimental feature'))
def test_trivial(self):
pass
def _test_name_inference(self, op, args=(), expected_names=(), device='cpu',
maybe_raises_regex=None):
casted_args = [arg.to(device) if isinstance(arg, torch.Tensor) else arg
for arg in args]
if maybe_raises_regex is not None:
with self.assertRaisesRegex(RuntimeError, maybe_raises_regex):
result = op(*args)
return
result = op(*args)
self.assertEqual(result.names, expected_names,
msg='Name inference for {} on device {} failed'.format(
op.__name__, device))
# TODO(rzou): Some form of this check should be added to self.assertEqual.
# Right now I don't know what it should look like.
def assertTensorDataAndNamesEqual(self, x, y):
self.assertEqual(x.names, y.names)
unnamed_x = x.rename(None)
unnamed_y = y.rename(None)
self.assertEqual(unnamed_x, unnamed_y)
def _test_factory(self, factory, device):
x = factory([], device=device)
self.assertEqual(x.names, ())
x = factory(1, 2, 3, device=device)
self.assertEqual(x.names, (None, None, None))
x = factory(1, 2, 3, names=None, device=device)
self.assertEqual(x.names, (None, None, None))
x = factory(1, 2, 3, names=('N', 'T', 'D'), device=device)
self.assertEqual(x.names, ('N', 'T', 'D'))
x = factory(1, 2, 3, names=('N', None, 'D'), device=device)
self.assertEqual(x.names, ('N', None, 'D'))
x = factory(1, 2, 3, names=('_1', 'batch9', 'BATCH_5'), device=device)
self.assertEqual(x.names, ('_1', 'batch9', 'BATCH_5'))
with self.assertRaisesRegex(RuntimeError,
'a valid identifier contains only'):
x = factory(2, names=('1',), device=device)
with self.assertRaisesRegex(RuntimeError,
'a valid identifier contains only'):
x = factory(2, names=('?',), device=device)
with self.assertRaisesRegex(RuntimeError, 'Number of names'):
x = factory(2, 1, names=('N',), device=device)
with self.assertRaisesRegex(TypeError, 'invalid combination of arguments'):
x = factory(2, 1, names='N', device=device)
with self.assertRaisesRegex(RuntimeError, 'construct a tensor with duplicate names'):
x = factory(2, 1, 1, names=('N', 'C', 'N'), device=device)
names64 = ['A' * i for i in range(1, 65)]
x = factory([1] * 64, names=names64, device=device)
self.assertEqual(x.names, names64)
with self.assertRaisesRegex(
RuntimeError,
'only support up to 64 dims'):
names65 = ['A' * i for i in range(1, 66)]
x = factory([1] * 65, names=names64, device=device)
def test_none_names_refcount(self, N=10):
def scope():
unnamed = torch.empty(2, 3)
unnamed.names # materialize [None, None]
prev_none_refcnt = sys.getrefcount(None)
# Ran it N times to reduce flakiness
[scope() for i in range(N)]
after_none_refcnt = sys.getrefcount(None)
self.assertTrue(after_none_refcnt - prev_none_refcnt < N / 2,
msg='Using tensor.names should not change '
'the refcount of Py_None')
def test_has_names(self):
unnamed = torch.empty(2, 3)
none_named = torch.empty(2, 3, names=(None, None))
partially_named = torch.empty(2, 3, names=('N', None))
fully_named = torch.empty(2, 3, names=('N', 'C'))
self.assertFalse(unnamed.has_names())
self.assertFalse(none_named.has_names())
self.assertTrue(partially_named.has_names())
self.assertTrue(fully_named.has_names())
def test_py3_ellipsis(self):
tensor = torch.randn(2, 3, 5, 7)
output = tensor.refine_names('N', ..., 'C')
self.assertEqual(output.names, ['N', None, None, 'C'])
def test_refine_names(self):
# Unnamed tensor -> Unnamed tensor
self._test_name_inference(Tensor.refine_names,
[create('None:1,None:2,None:3'), 'N', 'C', 'H'],
['N', 'C', 'H'])
# Named tensor -> Named tensor
self._test_name_inference(Tensor.refine_names,
[create('N:1,C:2,H:3'), 'N', 'C', 'H'],
['N', 'C', 'H'])
# Partially named tensor -> named tensor
self._test_name_inference(Tensor.refine_names,
[create('None:1,C:2,None:3'), None, 'C', 'H'],
[None, 'C', 'H'])
# Too few names
self._test_name_inference(Tensor.refine_names,
[create('None:2,None:3'), 'N', 'C', 'H'],
maybe_raises_regex="different number of dims")
# Cannot change Tensor[D] to Tensor[N]
self._test_name_inference(Tensor.refine_names,
[create('D:3'), 'N'],
maybe_raises_regex="is different from")
# Cannot change Tensor[D] to Tensor[None]
self._test_name_inference(Tensor.refine_names,
[create('D:3'), None],
maybe_raises_regex="'D' is more specific than None")
# globbing behavior exists
self._test_name_inference(Tensor.refine_names,
[create('None:1,None:1,None:2,None:3'), '...', 'C', 'H'],
[None, None, 'C', 'H'])
def test_detach(self):
names = ['N']
self._test_name_inference(
Tensor.detach_,
[torch.randn(3, requires_grad=True, names=names)],
names)
self._test_name_inference(
Tensor.detach,
[torch.randn(3, requires_grad=True, names=names)],
names)
def test_index_fill(self):
for device in get_all_device_types():
expected_names = ('N', 'C')
x = torch.randn(3, 5, device=device, names=expected_names)
output = x.index_fill_('C', torch.tensor([0, 1], device=device), 5)
self.assertEqual(output.names, expected_names)
output = x.index_fill_('C', torch.tensor([0, 1], device=device), torch.tensor(4.))
self.assertEqual(output.names, expected_names)
output = x.index_fill('C', torch.tensor([0, 1], device=device), 5)
self.assertEqual(output.names, expected_names)
output = x.index_fill('C', torch.tensor([0, 1], device=device), torch.tensor(4.))
self.assertEqual(output.names, expected_names)
def test_equal(self):
for device in get_all_device_types():
tensor = torch.randn(2, 3, device=device)
other = tensor.clone()
self.assertTrue(torch.equal(tensor.rename('N', 'C'), other.rename('N', 'C')))
self.assertFalse(torch.equal(tensor.rename('M', 'C'), other.rename('N', 'C')))
self.assertFalse(torch.equal(tensor.rename(None, 'C'), other.rename('N', 'C')))
def test_squeeze(self):
x = create('N:3,C:1,H:1,W:1')
output = x.squeeze('C')
self.assertEqual(output.names, ['N', 'H', 'W'])
output = x.squeeze()
self.assertEqual(output.names, ['N'])
def test_repr(self):
named_tensor = torch.zeros(2, 3).rename_('N', 'C')
expected = "tensor([[0., 0., 0.],\n [0., 0., 0.]], names=('N', 'C'))"
self.assertEqual(repr(named_tensor), expected)
unnamed_tensor = torch.zeros(2, 3)
expected = "tensor([[0., 0., 0.],\n [0., 0., 0.]])"
self.assertEqual(repr(unnamed_tensor), expected)
none_named_tensor = torch.zeros(2, 3).rename_(None, None)
self.assertEqual(repr(none_named_tensor), expected)
def test_diagonal(self):
named_tensor = torch.zeros(2, 3, 5, 7, names=list('ABCD'))
self.assertEqual(named_tensor.diagonal().names, ['C', 'D', None])
self.assertEqual(named_tensor.diagonal(1, 3).names, ['A', 'C', None])
self.assertEqual(named_tensor.diagonal(outdim='E', dim1='B', dim2='D').names,
['A', 'C', 'E'])
def test_max_pooling(self):
def check_tuple_return(op, inputs, expected_names):
values, indices = op(*inputs)
self.assertEqual(values.names, expected_names)
self.assertEqual(indices.names, expected_names)
for device in get_all_device_types():
named_tensor_1d = torch.zeros(2, 3, 5, device=device, names=list('ABC'))
named_tensor_2d = torch.zeros(2, 3, 5, 7, device=device, names=list('ABCD'))
named_tensor_3d = torch.zeros(2, 3, 5, 7, 9, device=device, names=list('ABCDE'))
self.assertEqual(F.max_pool1d(named_tensor_1d, 2).names, named_tensor_1d.names)
self.assertEqual(F.max_pool2d(named_tensor_2d, [2, 2]).names, named_tensor_2d.names)
self.assertEqual(F.max_pool3d(named_tensor_3d, [2, 2, 2]).names, named_tensor_3d.names)
check_tuple_return(F.max_pool1d_with_indices, [named_tensor_1d, 2], named_tensor_1d.names)
check_tuple_return(F.max_pool2d_with_indices, [named_tensor_2d, [2, 2]], named_tensor_2d.names)
check_tuple_return(F.max_pool3d_with_indices, [named_tensor_3d, [2, 2, 2]], named_tensor_3d.names)
def test_max_pooling_without_names_does_not_warn(self):
for device in get_all_device_types():
tensor_2d = torch.zeros(2, 3, 5, 7, device=device, requires_grad=True)
with warnings.catch_warnings(record=True) as warns:
warnings.simplefilter("always")
result = F.max_pool2d(tensor_2d, [2, 2])
result.sum().backward()
self.assertEqual(len(warns), 0)
def test_no_save_support(self):
named_tensor = torch.zeros(2, 3, names=('N', 'C'))
buf = io.BytesIO()
with self.assertRaisesRegex(RuntimeError, "NYI"):
torch.save(named_tensor, buf)
def test_no_pickle_support(self):
named_tensor = torch.zeros(2, 3, names=('N', 'C'))
with self.assertRaisesRegex(RuntimeError, "NYI"):
serialized = pickle.dumps(named_tensor)
def test_no_multiprocessing_support(self):
named_tensor = torch.zeros(2, 3, names=('N', 'C'))
buf = io.BytesIO()
with self.assertRaisesRegex(RuntimeError, "NYI"):
ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(named_tensor)
def test_big_tensor_repr_has_names(self):
def check_repr(named_tensor):
unnamed_tensor = named_tensor.rename(None)
names_tag = 'names={}'.format(named_tensor.names)
self.assertIn(names_tag, repr(named_tensor))
check_repr(torch.randn(128, 3, 64, 64, names=('N', 'C', 'H', 'W')))
def test_noncontig_contiguous(self):
# This type of contiguous is special-cased and therefore needs its own test
for device in get_all_device_types():
x = torch.randn(2, 3, device=device).t().rename_('N', 'C')
self.assertEqual(x.contiguous().names, ('N', 'C'))
def test_copy_transpose(self):
# This type of copy is special-cased and therefore needs its own test
def _test(self_names, other_names, expected_names):
x = torch.empty(2, 5, names=self_names)
y = torch.empty(5, 2).t().rename_(*other_names)
x.copy_(y)
self.assertEqual(x.names, expected_names)
_test(('N', 'C'), ('N', 'C'), ('N', 'C'))
_test(None, ('N', 'C'), ('N', 'C'))
def test_rename_(self):
tensor = torch.empty(1, 1, names=('N', 'C'))
self.assertEqual(tensor.rename_(None).names, (None, None))
self.assertEqual(tensor.rename_('H', 'W').names, ('H', 'W'))
with self.assertRaisesRegex(RuntimeError, 'Number of names'):
tensor.rename_('N', 'C', 'W')
with self.assertRaisesRegex(RuntimeError, 'duplicate names'):
tensor.rename_('N', 'N')
def test_rename(self):
tensor = torch.empty(1, 1, names=('N', 'C'))
self.assertEqual(tensor.rename(None).names, (None, None))
self.assertEqual(tensor.rename('H', 'W').names, ('H', 'W'))
# Check that we didn't modify tensor.names
self.assertEqual(tensor.names, ('N', 'C'))
with self.assertRaisesRegex(RuntimeError, 'Number of names'):
tensor.rename('N', 'C', 'W')
with self.assertRaisesRegex(RuntimeError, 'duplicate names'):
tensor.rename('N', 'N')
with self.assertRaisesRegex(RuntimeError, 'either positional args or keyword args'):
tensor.rename(None, N='batch')
# rename returns a view on the tensor
self.assertEqual(tensor.rename('H', 'W').data_ptr(), tensor.data_ptr())
self.assertEqual(tensor.rename(None).data_ptr(), tensor.data_ptr())
def test_rename_globber(self):
scalar = torch.randn([])
unnamed_tensor = torch.empty(1, 1, 1, 1)
named_tensor = torch.empty(1, 1, 1, 1, names=('N', 'C', 'H', 'W'))
self.assertEqual(scalar.rename(None).names, [])
self.assertEqual(scalar.rename('...').names, [])
# Check that it works with unnamed tensors
self.assertEqual(unnamed_tensor.rename('...').names, unnamed_tensor.names)
self.assertEqual(unnamed_tensor.rename('...', 'H', 'W').names,
[None, None, 'H', 'W'])
self.assertEqual(unnamed_tensor.rename('N', '...', 'W').names,
['N', None, None, 'W'])
self.assertEqual(unnamed_tensor.rename('N', 'C', '...').names,
['N', 'C', None, None])
# Check that it works with named tensors
self.assertEqual(named_tensor.rename('...').names, named_tensor.names)
self.assertEqual(named_tensor.rename('...', 'width').names,
['N', 'C', 'H', 'width'])
self.assertEqual(named_tensor.rename('batch', 'channels', '...', 'width').names,
['batch', 'channels', 'H', 'width'])
self.assertEqual(named_tensor.rename('batch', '...').names,
['batch', 'C', 'H', 'W'])
# Test empty glob
self.assertEqual(unnamed_tensor.rename('...', None, None, None, None).names,
[None, None, None, None])
self.assertEqual(named_tensor.rename('N', 'C', 'H', '...', 'W').names,
['N', 'C', 'H', 'W'])
# Multiple globs throw
with self.assertRaisesRegex(RuntimeError, 'More than one '):
named_tensor.rename('...', 'channels', '...')
def test_rename_rename_map(self):
scalar = torch.randn([])
unnamed_tensor = torch.empty(1, 1, 1, 1)
named_tensor = torch.empty(1, 1, 1, 1, names=('N', 'C', 'H', 'W'))
with self.assertRaisesRegex(RuntimeError, "dim 'N' does not exist"):
scalar.rename(N='batch')
with self.assertRaisesRegex(RuntimeError, "dim 'N' does not exist"):
unnamed_tensor.rename(N='batch')
with self.assertRaisesRegex(RuntimeError, "dim 'B' does not exist"):
named_tensor.rename(B='batch')
with self.assertRaisesRegex(RuntimeError, "dim 'B' does not exist"):
named_tensor.rename(H='height', B='batch')
self.assertEqual(named_tensor.rename(N='batch').data_ptr(),
named_tensor.data_ptr())
self.assertEqual(named_tensor.rename(N='batch').names,
['batch', 'C', 'H', 'W'])
self.assertEqual(named_tensor.rename(N='batch', H='height').names,
['batch', 'C', 'height', 'W'])
def test_set_names_property(self):
tensor = torch.empty(1, 1, names=('N', 'C'))
tensor.names = None
self.assertEqual(tensor.names, (None, None))
tensor.names = ('N', 'W')
self.assertEqual(tensor.names, ('N', 'W'))
with self.assertRaisesRegex(RuntimeError, 'Number of names'):
tensor.names = ['N', 'C', 'W']
with self.assertRaisesRegex(RuntimeError, 'duplicate names'):
tensor.names = ['N', 'N']
def test_factory_edge_cases(self):
for device in get_all_device_types():
self._test_factory(torch.empty, device)
def test_factory_coverage(self):
def _test(factory, device):
names = ('N', 'T', 'D')
torch.manual_seed(0)
result = factory(1, 2, 3, names=names, device=device)
torch.manual_seed(0)
expected = factory(1, 2, 3, device=device).rename_(*names)
self.assertTensorDataAndNamesEqual(result, expected)
supported = [
torch.ones,
torch.rand,
torch.randn,
torch.zeros,
]
for op, device in itertools.product(supported, get_all_device_types()):
_test(op, device)
# Test torch.full
for device in get_all_device_types():
names = ('N', 'T', 'D')
result = torch.full([1, 2, 3], 2., names=names, device=device)
expected = torch.full([1, 2, 3], 2., device=device).rename_(*names)
self.assertTensorDataAndNamesEqual(result, expected)
def test_tensor_from_lists(self):
names = ('N', 'C')
tensor = torch.tensor([[1]], names=names)
self.assertEqual(tensor.names, names)
names = ('N',)
tensor = torch.tensor([1], names=names)
self.assertEqual(tensor.names, names)
with self.assertRaisesRegex(RuntimeError, 'Number of names'):
names = ('N', 'C')
tensor = torch.tensor([1], names=names)
@unittest.skipIf(not TEST_NUMPY, "no numpy")
def test_tensor_from_numpy(self):
import numpy as np
arr = np.array([[1]])
names = ('N', 'C')
tensor = torch.tensor([[1]], names=names)
self.assertEqual(tensor.names, names)
def test_tensor_from_tensor(self):
x = torch.randn(1, 1)
names = ('N', 'C')
tensor = torch.tensor(x, names=names)
self.assertEqual(tensor.names, names)
def test_tensor_from_named_tensor(self):
x = torch.randn(1, 1, names=('N', 'D'))
tensor = torch.tensor(x)
self.assertEqual(tensor.names, ('N', 'D'))
# there's no way to distinguish between names=None and not passing in names.
# If the user passes in names=None they are asking for trouble.
x = torch.randn(1, 1, names=('N', 'D'))
tensor = torch.tensor(x, names=None)
self.assertEqual(tensor.names, ('N', 'D'))
x = torch.randn(1, 1, names=('N', 'D'))
with self.assertRaisesRegex(RuntimeError, "Name mismatch"):
tensor = torch.tensor(x, names=('N', 'C'))
def test_size(self):
t = torch.empty(2, 3, 5, names=('N', None, 'C'))
self.assertEqual(t.size('N'), 2)
self.assertEqual(t.size('C'), 5)
with self.assertRaisesRegex(RuntimeError, 'Please look up dimensions by name*'):
t.size(None)
with self.assertRaisesRegex(RuntimeError, 'Name \'channels\' not found in '):
t.size('channels')
with self.assertRaisesRegex(RuntimeError, 'Name \'N\' not found in '):
torch.empty(2, 3, 4).size('N')
def test_stride(self):
t = torch.empty(2, 3, 5, names=('N', None, 'C'))
self.assertEqual(t.stride('N'), 3 * 5)
self.assertEqual(t.stride('C'), 1)
with self.assertRaisesRegex(RuntimeError, 'Please look up dimensions by name'):
t.stride(None)
with self.assertRaisesRegex(RuntimeError, 'Name \'channels\' not found in '):
t.stride('channels')
with self.assertRaisesRegex(RuntimeError, 'Name \'N\' not found in '):
torch.empty(2, 3, 4).stride('N')
def test_transpose_variants(self):
t = torch.randn(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
self.assertEqual(t.transpose('N', 'C').names, ['C', 'N', 'H', 'W'])
self.assertEqual(t.transpose(1, 3).names, ['N', 'W', 'H', 'C'])
t = torch.randn(2, 3, names=('N', 'C'))
self.assertEqual(t.t().names, ['C', 'N'])
def test_resize(self):
for device in get_all_device_types():
named = torch.randn(2, names=('N',), device=device)
named.resize_([2])
self.assertEqual(named.names, ['N'])
with self.assertRaisesRegex(RuntimeError, "Cannot resize named tensor"):
named.resize_([3])
other_named = torch.randn(2, names=('N',), device=device)
named.resize_as_(other_named)
self.assertEqual(other_named.names, ['N'])
unnamed = torch.randn(2, device=device)
with self.assertRaisesRegex(
RuntimeError, r'names .* are not the same as the computed output names'):
named.resize_as_(unnamed)
unnamed = torch.randn(1, device=device)
unnamed.resize_as_(named)
self.assertEqual(unnamed.names, ['N'])
def test_cdist(self):
for device in get_all_device_types():
tensor = torch.randn(3, 1, 2, 7, names=('M', 'N', 'first_group', 'features'),
device=device)
other = torch.randn(5, 11, 7, names=('N', 'second_group', 'features'),
device=device)
result = torch.cdist(tensor, other)
self.assertEqual(result.names, ['M', 'N', 'first_group', 'second_group'])
def test_info_smoke(self):
# Smoke test for info functions / methods / attributes on named tensors.
tensor = torch.empty(1, 1, names=('N', 'D'))
tensor.device
tensor.dtype
tensor.get_device()
tensor.is_complex()
tensor.is_floating_point()
tensor.is_nonzero()
torch.is_same_size(tensor, tensor)
torch.is_signed(tensor)
tensor.layout
tensor.numel()
tensor.dim()
tensor.element_size()
tensor.is_contiguous()
tensor.is_cuda
tensor.is_leaf
tensor.is_pinned()
tensor.is_shared()
tensor.is_sparse
tensor.ndimension()
tensor.nelement()
tensor.shape
tensor.size()
tensor.size(1)
tensor.storage()
tensor.storage_offset()
tensor.storage_type()
tensor.stride()
tensor.stride(1)
tensor.data
tensor.data_ptr()
tensor.ndim
tensor.item()
tensor.type()
tensor.is_shared()
tensor.is_signed()
def test_autograd_smoke(self):
x = torch.randn(3, 3, names=('N', 'D'), requires_grad=True)
y = x.clone()
y.retain_grad()
y.register_hook(lambda x: x)
y.sum().backward()
# autograd related attributes
tensor = torch.empty(1, 1, names=('N', 'D'), requires_grad=True)
tensor = tensor.relu()
tensor.output_nr
tensor.grad_fn
tensor.requires_grad
def test_split_fns_propagates_names(self):
fns = [
lambda x: x.split(1, 0),
lambda x: x.split([1, 1], 1),
lambda x: x.chunk(2, 0),
]
for device in get_all_device_types():
orig_tensor = torch.empty(2, 2, names=('N', 'D'), device=device)
for fn in fns:
splits = fn(orig_tensor)
for split in splits:
self.assertEqual(split.names, orig_tensor.names)
def test_any_all(self):
for device in get_all_device_types():
x = torch.zeros(3, dtype=torch.bool, device=device, names=('C',))
self.assertEqual(x.any().names, [])
self.assertEqual(x.all().names, [])
def test_addcmul_addcdiv(self):
for device in get_all_device_types():
names = ['N']
a = torch.rand(3, device=device, names=names)
b = torch.rand(3, device=device, names=names)
# avoid division by 0
c = torch.rand(3, device=device, names=names).clamp_min_(0.1)
out = torch.randn(3, device=device, names=names)
self.assertEqual(torch.addcmul(a, b, c).names, names)
self.assertEqual(torch.addcmul(a, b, c, out=out).names, names)
self.assertEqual(a.addcmul_(b, c).names, names)
self.assertEqual(torch.addcdiv(a, b, c).names, names)
self.assertEqual(torch.addcdiv(a, b, c, out=out).names, names)
self.assertEqual(a.addcdiv_(b, c).names, names)
def test_binary_ops(self):
def test_basic(op):
a = torch.empty(2, 3, names=('N', 'C'))
b = torch.empty(3, 2, names=('C', 'N'))
c = torch.empty(3, names=('C',))
d = torch.empty(5, names=('W',))
self.assertEqual(op(a, a).names, ('N', 'C'))
self.assertEqual(op(a, c).names, ('N', 'C'))
with self.assertRaisesRegex(RuntimeError, "do not match"):
op(a, d)
with self.assertRaisesRegex(RuntimeError, "do not match"):
op(a, b)
def test_wildcard(op):
a = torch.empty(2, 3, names=('N', 'C'))
c = torch.empty(2, 3, names=(None, 'C'))
self.assertEqual(op(a, c).names, ('N', 'C'))
b = torch.empty(2, 3)
self.assertEqual(op(a, b).names, ('N', 'C'))
d = torch.empty(2, 3, names=('C', None))
with self.assertRaisesRegex(RuntimeError, "Misaligned"):
op(d, c)
def test_mixed_unnamed_named(op, is_inplace):
named2 = torch.randn(1, 1, names=('N', 'C'))
unnamed1 = torch.randn(1)
unnamed2 = torch.randn(1, 1)
unnamed3 = torch.randn(1, 1, 1)
def compute_expected_names(tensor, other):
assert tensor.has_names() ^ other.has_names()
named = tensor if tensor.has_names() else other
unnamed = other if tensor.has_names() else tensor
unnamed_dim = unnamed.dim()
if unnamed_dim > named.dim():
return [None] * (unnamed_dim - named.dim()) + list(named.names)
else:
return named.names
inputs = itertools.chain(
itertools.product([named2], [unnamed1, unnamed2, unnamed3]),
itertools.product([unnamed1, unnamed2, unnamed3], [named2]),
)
if is_inplace:
# In-place ops have the constraint that they must not change shape.
inputs = [(a, b) for (a, b) in inputs if a.dim() >= b.dim()]
for tensor, other in inputs:
expected_names = compute_expected_names(tensor, other)
self.assertEqual(op(tensor, other).names, expected_names)
def method(name, *args, **kwargs):
return [Function(name, lambda a, b: getattr(a, name)(b, *args, **kwargs))]
def function(name, *args, **kwargs):
return [Function(name, lambda a, b: getattr(torch, name)(a, b, *args, **kwargs))]
def out_function(name, *args, **kwargs):
out_fn = getattr(torch, name)
def fn(a, b):
result = torch.empty([0], dtype=a.dtype, device=a.device)
out_fn(a, b, *args, out=result, **kwargs)
return result
return [Function(name, fn)]
def fn_method_and_inplace(name, *args, **kwargs):
return (
method(name, *args, **kwargs) +
method(name + '_', *args, **kwargs) +
out_function(name, *args, **kwargs)
)
tests = [
fn_method_and_inplace('add'),
fn_method_and_inplace('div'),
fn_method_and_inplace('mul'),
fn_method_and_inplace('sub'),
fn_method_and_inplace('pow'),
fn_method_and_inplace('atan2'),
method('copy_'),
function('floor_divide'),
function('true_divide'),
]
tests = flatten(tests)
for name, op in tests:
test_basic(op)
test_wildcard(op)
test_mixed_unnamed_named(op, is_inplace=name.endswith('_'))
def test_logical_ops(self):
# Implemented via TensorIterator, so just check that each version
# (out-of-place, inplace, out=) propagates names.
def zeros(*args, **kwargs):
return torch.zeros(*args, dtype=torch.bool, **kwargs)
for op in ('logical_xor', 'logical_and', 'logical_or'):
self._test_name_inference(
getattr(torch, op),
(create('N:2,C:3', zeros), create('N:2,C:3', zeros)),
expected_names=['N', 'C'])
self._test_name_inference(
getattr(Tensor, op + '_'),
(create('N:2,C:3', zeros), create('N:2,C:3', zeros)),
expected_names=['N', 'C'])
self._test_name_inference(
lambda out, x, y: getattr(torch, op)(x, y, out=out),
(create('0', zeros), create('N:2,C:3', zeros), create('N:2,C:3', zeros)),
expected_names=['N', 'C'])
def test_pow_special(self):
# There are a few pow cases that don't go through TensorIterator.
# Test them here.
for device in get_all_device_types():
named = torch.randn(2, 3, names=('N', 'C'), device=device)
unnamed = torch.randn([0], device=device)
result = torch.pow(named, 0, out=unnamed.clone())
self.assertEqual(result.names, named.names)
result = torch.pow(named, 1, out=unnamed.clone())
self.assertEqual(result.names, named.names)
result = torch.pow(1, named, out=unnamed.clone())
self.assertEqual(result.names, named.names)
def test_out_fn_semantics(self):
out_fn = torch.abs
unnamed_tensor = torch.randn(3, 2)
none_named_tensor = torch.randn(3, 2, names=(None, None))
named_tensor = torch.randn(3, 2, names=('N', 'C'))
partially_named_tensor = torch.randn(3, 2, names=('N', None))
with self.assertRaisesRegex(RuntimeError, "Name mismatch"):
out_fn(partially_named_tensor, out=named_tensor)
with self.assertRaisesRegex(RuntimeError, "Name mismatch"):
out_fn(named_tensor, out=partially_named_tensor)
with self.assertRaisesRegex(RuntimeError, "Name mismatch"):
out_fn(none_named_tensor, out=named_tensor)
with self.assertRaisesRegex(RuntimeError, "Name mismatch"):
out_fn(unnamed_tensor, out=named_tensor)
output = torch.randn(3, 2)
out_fn(unnamed_tensor, out=output)
self.assertFalse(output.has_names())
output = torch.randn(3, 2, names=(None, None))
out_fn(named_tensor, out=output)
self.assertEqual(output.names, named_tensor.names)
output = torch.randn(3, 2)
out_fn(named_tensor, out=output)
self.assertEqual(output.names, named_tensor.names)
output = torch.randn(3, 2, names=(None, None))
out_fn(unnamed_tensor, out=output)
self.assertFalse(output.has_names())
def test_unary_propagate_names_fns(self):
def _test(testcase, names=('N', 'D'), device='cpu'):
sizes = [2] * len(names)
tensor = torch.empty(sizes, names=names, device=device)
try:
out = testcase.lambd(tensor)
except RuntimeError as err:
# Get a better error message by catching the error and asserting.
raise RuntimeError('{}: {}'.format(testcase.name, err)) from err
self.assertEqual(out.names, tensor.names,
msg=testcase.name)
def fn(name, *args, **kwargs):
return [Function(name, lambda t: getattr(torch, name)(t, *args, **kwargs))]
def method(name, *args, **kwargs):
return [Function(name, lambda t: getattr(t, name)(*args, **kwargs))]
def out_function(name, *args, **kwargs):
out_fn = getattr(torch, name)
def fn(tensor):
result = torch.empty([0], dtype=tensor.dtype, device=tensor.device)
out_fn(tensor, *args, out=result, **kwargs)
return result
return [Function(name + '_out', fn)]
def fn_method_and_inplace(name, *args, **kwargs):
return (
method(name, *args, **kwargs) +
method(name + '_', *args, **kwargs) +
out_function(name, *args, **kwargs)
)
# All of these operate on 2x2 tensors.
tests = [
# unary pointwise
fn_method_and_inplace('abs'),
fn_method_and_inplace('acos'),
fn_method_and_inplace('asin'),
fn_method_and_inplace('atan'),
fn_method_and_inplace('ceil'),
fn_method_and_inplace('clamp', -1, 1),
fn_method_and_inplace('clamp_min', -2),
fn_method_and_inplace('clamp_max', 2),
method('cauchy_'),
method('clone'),
method('contiguous'),
fn_method_and_inplace('cos'),
fn_method_and_inplace('cosh'),
fn_method_and_inplace('digamma'),
fn_method_and_inplace('erf'),
fn_method_and_inplace('erfc'),
fn_method_and_inplace('erfinv'),
fn_method_and_inplace('exp'),
fn_method_and_inplace('expm1'),
method('exponential_'),
fn_method_and_inplace('floor'),
fn_method_and_inplace('frac'),
method('geometric_', p=0.5),
fn_method_and_inplace('lgamma'),
fn_method_and_inplace('log'),
fn_method_and_inplace('log10'),
fn_method_and_inplace('log1p'),
fn_method_and_inplace('log2'),
method('log_normal_'),
fn_method_and_inplace('neg'),
method('normal_'),
[Function('polygamma', lambda t: torch.polygamma(1, t))],
method('polygamma_', 1),
fn_method_and_inplace('reciprocal'),
method('random_', 0, 1),
method('random_', 1),
method('random_'),
method('relu_'),
method('requires_grad_'),
method('relu'),
fn_method_and_inplace('round'),
fn_method_and_inplace('rsqrt'),
fn_method_and_inplace('sigmoid'),
fn_method_and_inplace('sign'),
fn_method_and_inplace('sin'),
fn_method_and_inplace('sinh'),
fn_method_and_inplace('sqrt'),
fn_method_and_inplace('tan'),
fn_method_and_inplace('tanh'),
fn('threshold', 0, 1),
fn('threshold_', 0, 1),
out_function('threshold', 0, 1),
fn_method_and_inplace('trunc'),
method('uniform_'),
method('zero_'),
method('fill_', 1),
method('fill_', torch.tensor(3.14)),
# conversions
method('to', dtype=torch.long),
method('to', device='cpu'),
method('to', torch.empty([])),
method('bool'),
method('byte'),
method('char'),
method('cpu'),
method('double'),
method('float'),
method('long'),
method('half'),
method('int'),
method('short'),
method('type', dtype=torch.long),
# cumsum and cumprod
fn('cumsum', 0),
fn('cumsum', 'D'),
out_function('cumsum', 'D'),
fn('cumprod', 0),
fn('cumprod', 'D'),
out_function('cumprod', 'D'),
# views
method('narrow', 0, 0, 1),
# creation functions
fn('empty_like'),
fn('zeros_like'),
fn('ones_like'),
fn('full_like', 3.14),
fn('rand_like'),
fn('randn_like'),
# bernoulli variants
method('bernoulli_', 0.5),
method('bernoulli_', torch.tensor(0.5)),
method('softmax', dim=1),
method('softmax', dim='D'),
method('log_softmax', dim=1),
method('log_softmax', dim='D'),
[Function('F.dropout(inplace)', lambda t: F.dropout(t, p=0.5, inplace=True))],
[Function('F.dropout(outplace)', lambda t: F.dropout(t, p=0.5, inplace=False))],
]
tests = flatten(tests)
for testcase, device in itertools.product(tests, get_all_device_types()):
_test(testcase, device=device)
def test_cummax_cummin(self):
def test_ops(op):
for device in get_all_device_types():
names = ('N', 'D')