-
Notifications
You must be signed in to change notification settings - Fork 21.4k
/
type.cpp
1434 lines (1309 loc) · 42.8 KB
/
type.cpp
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
#include <ATen/core/Dict.h>
#include <ATen/core/Tensor.h>
#include <ATen/core/function_schema.h>
#include <ATen/core/jit_type.h>
#include <c10/macros/Macros.h>
#include <ATen/core/grad_mode.h>
#include <ATen/core/function.h>
#include <iostream>
namespace c10 {
TypeVerbosity type_verbosity() {
static const char* c_verbosity = std::getenv("PYTORCH_JIT_TYPE_VERBOSITY");
static TypeVerbosity verbosity = c_verbosity ?
static_cast<TypeVerbosity>(c10::stoi(c_verbosity)) : TypeVerbosity::Default;
return verbosity;
}
std::ostream& operator<<(std::ostream & out, const Type & t) {
if (auto value = t.cast<TensorType>()) {
if (value->scalarType().has_value()) {
out << toString(*value->scalarType());
if (!value->sizes().size().has_value()) {
out << "Tensor";
}
} else {
out << "Tensor";
}
if (auto ndim = value->sizes().size()) {
bool has_valid_strides_info = *ndim > 0 &&
value->strides().isComplete() && value->strides().size() == ndim;
out << "(";
size_t i = 0;
for (i = 0; i < *ndim; ++i) {
if (i > 0) {
out << ", ";
}
if (auto s = value->sizes()[i]) {
out << *s;
} else {
out << "*";
}
}
if (has_valid_strides_info &&
type_verbosity() >= TypeVerbosity::TypeAndStride) {
out << ", strides=[";
for (size_t i = 0; i < *ndim; ++i) {
if (i > 0) {
out << ", ";
}
out << *value->strides()[i];
}
out << "]";
}
if (type_verbosity() >= TypeVerbosity::Full) {
if (value->requiresGrad()) {
if (i++ > 0) {
out << ", ";
}
out << "requires_grad=" << *value->requiresGrad();
}
if (value->device()) {
if (i++ > 0) {
out << ", ";
}
out << "device=" << *value->device();
}
}
out << ")";
}
if (value->undefined() && *value->undefined()) {
out << "[Undefined]";
}
} else if(t.kind() == TypeKind::ListType) {
auto prim = t.cast<ListType>()->getElementType();
out << *prim << "[]";
} else if (t.kind() == TypeKind::OptionalType) {
auto prim = t.cast<OptionalType>()->getElementType();
out << *prim << "?";
} else if(t.kind() == TypeKind::FutureType) {
auto elem = t.cast<FutureType>()->getElementType();
out << "Future[" << *elem << "]";
} else if(t.kind() == TypeKind::RRefType) {
auto elem = t.cast<RRefType>()->getElementType();
out << "RRef[" << *elem << "]";
} else if(auto tup = t.cast<TupleType>()) {
if (tup->schema()) {
out << "NamedTuple";
}
out << "(";
for(size_t i = 0; i < tup->elements().size(); ++i) {
if(i > 0)
out << ", ";
if (tup->schema()) {
out << tup->schema()->arguments()[i].name() << " : ";
}
out << *(tup->elements()[i]);
}
out << ")";
} else if (t.kind() == TypeKind::FunctionType) {
out << "Function";
} else {
out << t.str();
}
return out;
}
AnyTypePtr AnyType::get() {
static auto value = AnyType::create();
return value;
}
TensorTypePtr TensorType::get() {
static auto value = TensorType::create(
{}, {}, SymbolicShape(), VaryingShape<Stride>{}, {});
return value;
}
NumberTypePtr NumberType::get() {
static auto value = NumberType::create();
return value;
}
IntTypePtr IntType::get() {
static auto value = IntType::create();
return value;
}
FloatTypePtr FloatType::get() {
static auto value = FloatType::create();
return value;
}
BoolTypePtr BoolType::get() {
static auto value = BoolType::create();
return value;
}
NoneTypePtr NoneType::get() {
static auto value = NoneType::create();
return value;
}
GeneratorTypePtr GeneratorType::get() {
static auto value = GeneratorType::create();
return value;
}
QuantizerTypePtr QuantizerType::get() {
static auto value = QuantizerType::create();
return value;
}
QSchemeTypePtr QSchemeType::get() {
static auto value = QSchemeType::create();
return value;
}
StringTypePtr StringType::get() {
static auto value = StringType::create();
return value;
}
DeviceObjTypePtr DeviceObjType::get() {
static auto value = DeviceObjType::create();
return value;
}
ScalarTypeTypePtr ScalarTypeType::get() {
static auto value = ScalarTypeType::create();
return value;
}
LayoutTypePtr LayoutType::get() {
static auto value = LayoutType::create();
return value;
}
OptionalTypePtr OptionalType::ofTensor() {
static auto value = OptionalType::create(TensorType::get());
return value;
}
PyObjectTypePtr PyObjectType::get() {
static auto value = PyObjectType::create();
return value;
}
CapsuleTypePtr CapsuleType::get() {
static auto value = CapsuleType::create();
return value;
}
ListTypePtr ListType::ofTensors() {
static auto value = ListType::create(TensorType::get());
return value;
}
ListTypePtr ListType::ofInts() {
static auto value = ListType::create(IntType::get());
return value;
}
ListTypePtr ListType::ofFloats() {
static auto value = ListType::create(FloatType::get());
return value;
}
ListTypePtr ListType::ofBools() {
static auto value = ListType::create(BoolType::get());
return value;
}
ListTypePtr ListType::ofStrings() {
static auto value = ListType::create(StringType::get());
return value;
}
AnyListTypePtr AnyListType::get() {
static auto value = AnyListType::create();
return value;
}
AnyTupleTypePtr AnyTupleType::get() {
static auto value = AnyTupleType::create();
return value;
}
AnyClassTypePtr AnyClassType::get() {
static auto value = AnyClassType::create();
return value;
}
AnyEnumTypePtr AnyEnumType::get() {
static auto value = AnyEnumType::create();
return value;
}
c10::optional<TypePtr> unifyTypesImpl(const TypePtr& t1, const TypePtr& t2) {
// check direct subtyping relation
if (t1->isSubtypeOf(t2)) {
return t2;
} else if (t2->isSubtypeOf(t1)) {
return t1;
}
// Handle non-container types which do not subtype each other and unify
if (t1->kind() == TensorType::Kind && t2->kind() == TensorType::Kind) {
return t1->expect<TensorType>()->merge(t2->expect<TensorType>());
}
if (t1->isSubtypeOf(NoneType::get()) && !t2->isSubtypeOf(NoneType::get())) {
return OptionalType::create(t2);
} else if (t2->isSubtypeOf(NoneType::get()) && !t1->isSubtypeOf(NoneType::get())) {
return OptionalType::create(t1);
}
// NB: we do not return NumberType because there is not currently enough
// operator support for it
// Attempt to unify Complete Tensor Types for immutable type containers
// unify(Optional[t1], t2) => Optional[unify(t1, t2)]
if (auto opt_t1 = t1->cast<OptionalType>()) {
if (auto elem = unifyTypes(opt_t1->getElementType(), t2)) {
return OptionalType::create(*elem);
}
} else if (auto opt_t2 = t2->cast<OptionalType>()) {
if (auto elem = unifyTypes(opt_t2->getElementType(), t1)) {
return OptionalType::create(*elem);
}
}
if (t1->cast<TupleType>() && t2->cast<TupleType>()) {
auto tuple1 = t1->cast<TupleType>();
auto tuple2 = t2->cast<TupleType>();
if (tuple1->elements().size() != tuple2->elements().size()) {
return c10::nullopt;
}
std::vector<TypePtr> elements;
for (size_t i = 0; i < tuple1->elements().size(); i++) {
if (auto elem = unifyTypes(tuple1->elements().at(i), tuple2->elements().at(i))) {
elements.push_back(*elem);
} else {
return c10::nullopt;
}
}
return static_cast<TypePtr>(TupleType::create(elements));
}
if (t1->cast<FutureType>() && t2->cast<FutureType>()) {
if (auto elem = unifyTypes(
t1->cast<FutureType>()->getElementType(),
t2->cast<FutureType>()->getElementType())) {
return FutureType::create(*elem);
}
}
// Check direct subtyping relations again with Unshaped Types,
// to handle unification of mutable container types which might contain two different
// specialized tensors (ListType / DictType)
auto t1_unshaped = unshapedType(t1);
auto t2_unshaped = unshapedType(t2);
if (t1_unshaped->isSubtypeOf(t2_unshaped)) {
return t2_unshaped;
} else if (t2_unshaped->isSubtypeOf(t1_unshaped)) {
return t1_unshaped;
}
return c10::nullopt;
}
c10::optional<TypePtr> unifyTypes(const TypePtr& t1, const TypePtr& t2, bool default_to_any) {
auto unified = unifyTypesImpl(t1, t2);
if (default_to_any && !unified) {
return AnyType::get();
}
return unified;
}
c10::optional<TypePtr> unifyTypeList(
at::ArrayRef<TypePtr> elements,
std::ostream& why_not) {
if (elements.size() == 0) {
why_not << "Cannot get unified type from empty list";
return c10::nullopt;
}
TypePtr ret_type = elements.at(0);
for (size_t i = 1; i < elements.size() && ret_type; ++i) {
auto maybe_unified = unifyTypes(ret_type, elements.at(i));
if (!maybe_unified) {
why_not << "Could not unify type list since element " << i << " of type "
<< elements.at(i)->repr_str()
<< " did not match the types before it ("
<< ret_type->repr_str() << ")";
return c10::nullopt;
}
ret_type = maybe_unified.value();
}
return ret_type;
}
MatchTypeReturn matchTypeVariables(
TypePtr formal,
TypePtr actual,
TypeEnv& type_env) {
if (!formal->hasFreeVariables()) {
return MatchTypeReturn::Success();
}
if (auto vt = formal->cast<VarType>()) {
auto it = type_env.find(vt->name());
if (it == type_env.end()) {
type_env[vt->name()] = actual;
return MatchTypeReturn::Success();
} else if (auto unified = unifyTypes(it->second, actual)) {
// note: unifyTypes allows subtyping in either direction, so actual
// may be a supertype of the current binding. we're not responsible
// for reporting the error, only for keeping type_env stable
return MatchTypeReturn::Success();
}
std::stringstream ss;
ss << "Type variable '" << vt->name() << "' previously matched to type "
<< it->second->repr_str() << " is matched to type "
<< actual->repr_str();
return ss.str();
} else if (auto lt_formal = formal->cast<ListType>()) {
if (auto lt_actual = actual->cast<ListType>()) {
const auto innerMatch = matchTypeVariables(
lt_formal->getElementType(), lt_actual->getElementType(), type_env);
if (!innerMatch.success()) {
// propagate the errMsg onward
return innerMatch;
}
return MatchTypeReturn::Success();
} else if (auto tup_type = actual->cast<TupleType>()) {
std::stringstream ss;
auto maybe_tuple_unified = unifyTypeList(tup_type->elements(), ss);
if (maybe_tuple_unified) {
return matchTypeVariables(
lt_formal->getElementType(), *maybe_tuple_unified, type_env);
}
}
std::stringstream ss;
ss << "Cannot match " << lt_formal->repr_str() << " to "
<< actual->repr_str();
return ss.str();
} else if (auto tp_formal = formal->cast<TupleType>()) {
if (auto tp_actual = actual->cast<TupleType>()) {
if (tp_formal->elements().size() != tp_actual->elements().size()) {
return MatchTypeReturn("Cannot match tuples of mismatched size");
}
for (size_t i = 0; i < tp_formal->elements().size(); ++i) {
const auto result = matchTypeVariables(
tp_formal->elements()[i], tp_actual->elements()[i], type_env);
if (!result.success()) {
return result;
}
}
return MatchTypeReturn::Success();
} else {
std::stringstream ss;
ss << "Cannot match a tuple to " << actual->repr_str();
return MatchTypeReturn(ss.str());
}
} else if (auto lt_formal = formal->cast<FutureType>()) {
if (auto lt_actual = actual->cast<FutureType>()) {
const auto innerMatch = matchTypeVariables(
lt_formal->getElementType(), lt_actual->getElementType(), type_env);
if (!innerMatch.success()) {
return innerMatch;
}
return MatchTypeReturn::Success();
} else {
std::stringstream ss;
ss << "Cannot match a future to " << actual->repr_str();
return ss.str();
}
} else if (auto lt_formal = formal->cast<RRefType>()) {
if (auto lt_actual = actual->cast<RRefType>()) {
const auto innerMatch = matchTypeVariables(
lt_formal->getElementType(), lt_actual->getElementType(), type_env);
if (!innerMatch.success()) {
return innerMatch;
}
return MatchTypeReturn::Success();
} else {
std::stringstream ss;
ss << "Cannot match a rref to " << actual->repr_str();
return ss.str();
}
} else if (auto opt_formal = formal->cast<OptionalType>()) {
if (auto opt_actual = actual->cast<OptionalType>()) {
const auto optionedMatch = matchTypeVariables(
opt_formal->getElementType(), opt_actual->getElementType(), type_env);
if (!optionedMatch.success()) {
return optionedMatch;
}
} else if (!actual->isSubtypeOf(NoneType::get())) {
// If the actual type is a non-optional, allow matching to the formal if
// its element type matches the actual.
// Don't match None because it is already an optional (but one of
// unknown type).
return matchTypeVariables(opt_formal->getElementType(), actual, type_env);
}
// note: if actual was non here we potentially did not fill in the type
// variables contained in the formal. It is still a valid match because None
// matches Optional[T] later error checking on tryEvalTypeVariables will
// report the problem if we never match variables in type T
return MatchTypeReturn::Success();
} else if (auto dict_formal = formal->cast<DictType>()) {
if (auto dict_actual = actual->cast<DictType>()) {
auto key_match = matchTypeVariables(
dict_formal->getKeyType(), dict_actual->getKeyType(), type_env);
if (!key_match.success()) {
return key_match;
}
auto value_match = matchTypeVariables(
dict_formal->getValueType(), dict_actual->getValueType(), type_env);
if (!value_match.success()) {
return value_match;
}
return MatchTypeReturn::Success();
} else {
std::stringstream ss;
ss << "Cannot match a dict to " << actual->repr_str();
return ss.str();
}
}
AT_ERROR("Unhandled free variable container: ", formal->repr_str());
}
// change return types like List[List[t]] into List[List[int]]
CAFFE2_API TypePtr tryEvalTypeVariables(TypePtr type, std::unordered_map<std::string, TypePtr>& type_env) {
if (!type->hasFreeVariables()) {
return type;
}
if (auto vt = type->cast<VarType>()) {
auto it = type_env.find(vt->name());
if (it == type_env.end()) {
return nullptr;
}
return it->second;
} else {
std::vector<TypePtr> new_contained;
new_contained.reserve(type->containedTypes().size());
for (const TypePtr& t : type->containedTypes()) {
TypePtr r = tryEvalTypeVariables(t, type_env);
if (!r) {
return nullptr;
}
new_contained.push_back(r);
}
return type->withContained(std::move(new_contained));
}
}
CAFFE2_API bool elementTypeCanBeInferredFromMembers(const TypePtr& elem_type) {
if (elem_type->kind() == OptionalType::Kind ||
elem_type->kind() == NumberType::Kind) {
// Builtin Union types
return false;
}
if (elem_type->kind() == InterfaceType::Kind) {
// since classes can be members of multiple interfaces, we cannot
// construct which interface the list holds from the members alone
return false;
}
if (elem_type->kind() == AnyType::Kind) {
// List of Any can contains heterogenous types
return false;
}
return true;
}
const char * typeKindToString(TypeKind kind) {
#define CASE_TYPE(T) case TypeKind::T: return #T;
switch(kind) {
C10_FORALL_TYPES(CASE_TYPE)
}
#undef CASE_TYPE
return "";
}
bool Type::isSubtypeOfExt(const TypePtr rhs, std::ostream* why_not) const {
if (rhs->kind() == TypeKind::AnyType || *this == *rhs) {
return true;
}
if(auto rhs_ = rhs->cast<OptionalType>()) {
return this->isSubtypeOfExt(rhs_->getElementType(), why_not);
}
return false;
}
bool Type::is_module() const {
return false;
}
std::string TensorType::str() const {
return "Tensor";
}
template <typename T>
VaryingShape<T> VaryingShape<T>::merge(const VaryingShape<T>& other) const {
if (!dims_ || !other.dims_ || dims_->size() != other.dims_->size()) {
return VaryingShape<T>();
}
ListOfOptionalElements dims;
for (size_t i = 0, n = dims_->size(); i < n; i++) {
dims.push_back(merge_primitive((*dims_)[i], (*other.dims_)[i]));
}
return VaryingShape<T>(std::move(dims));
}
VaryingShape<int64_t> TensorType::sizes() const {
if (!sizes_.rank()) {
return VaryingShape<int64_t>();
}
return VaryingShape<int64_t>(
fmap(*sizes_.sizes(), [](ShapeSymbol ss) {
// we turn symbolic shapes into unknowns
return ss.is_static()
? c10::optional<int64_t>(ss.static_size())
: c10::nullopt;
}));
}
TensorTypePtr TensorType::merge(TensorTypePtr other, bool merge_sizes) const {
auto scalar_type = merge_primitive(scalarType(), other->scalarType());
auto dev = merge_primitive(device(), other->device());
auto sprops = stride_properties().merge(other->stride_properties());
auto gr = merge_primitive(requiresGrad(), other->requiresGrad());
auto undef = merge_primitive(undefined(), other->undefined());
return TensorType::create(
scalar_type,
dev,
merge_sizes ? symbolic_sizes().merge(other->symbolic_sizes())
: symbolic_sizes(),
sprops,
gr,
undef);
}
template <typename T>
bool is_null_or_equal(c10::optional<T> a, c10::IntArrayRef b) {
return !a.has_value() || a.value() == b;
}
bool TensorType::matchTensor(const at::Tensor& t) {
bool undef = undefined().value_or(!t.defined());
if (undef != !t.defined()) {
// When the followings are true, we consider it's not a match:
// - undefined().has_value() == true
// - undefined().value() != !t.defined()
return false;
} else if (!t.defined()) {
// When the followings are true, we consider it's a match:
// - t is not defined
// - undefined() == null or undefined().value() == true
return true;
}
// Here we know t.defined() == true and compare all other properties.
bool rg = at::GradMode::is_enabled() && t.requires_grad();
bool matched_strides = (!t.has_storage() && !stride_properties().isComplete())
|| stride_properties() == computeStrideProps(t.sizes(), t.strides(), t.is_contiguous());
return scalarType().value_or(t.scalar_type()) == t.scalar_type()
&& device().value_or(t.device()) == t.device()
&& requiresGrad().value_or(rg) == rg
&& matched_strides
&& is_null_or_equal(sizes().concrete_sizes(), t.sizes());
}
bool TensorType::operator==(const c10::Type& rhs) const {
if (rhs.kind() != kind()) {
return false;
}
auto rt = rhs.expect<TensorType>();
return scalar_type_ == rt->scalarType() && sizes() == rt->sizes() &&
stride_properties() == rt->stride_properties() &&
device() == rt->device() && requiresGrad() == rt->requiresGrad() &&
undefined() == rt->undefined();
}
template <typename T>
std::ostream& operator<<(std::ostream& out, const VaryingShape<T>& vs) {
out << "(";
if (!vs.size()) {
out << "*)";
return out;
}
for (size_t i = 0; i < vs.size(); i++) {
if (i > 0) {
out << ", ";
}
if (vs[i].has_value()) {
out << vs[i].value();
} else {
out << "*";
}
}
out << ")";
return out;
}
template std::ostream& operator<<(
std::ostream& out,
const VaryingShape<int64_t>& vs);
template std::ostream& operator<<(
std::ostream& out,
const VaryingShape<Stride>& vs);
std::ostream& operator<<(
std::ostream& os,
const SymbolicShape& ss) {
// TODO: Unranked SymbolicShape printing is ambiguous with that of
// dynamic-shaped vector.
if(!ss.rank()) {
os << "(*)";
return os;
}
auto sizes = ss.sizes().value();
os << "(";
for (size_t i = 0; i < ss.rank().value(); i++) {
if (i > 0) {
os << ", ";
}
if(sizes[i].is_static()) {
os << sizes[i];
} else {
os << "*";
}
}
os << ")";
return os;
}
std::ostream& operator<<(std::ostream& os, const ShapeSymbol& s) {
os << "SS(" << s.value_ << ')';
return os;
}
std::ostream& operator<<(std::ostream& os, const Stride& s) {
os << "{";
if (s.stride_index_.has_value()) {
os << *s.stride_index_;
} else {
os << "*";
}
os << ":";
if (s.stride_.has_value()) {
os << *s.stride_;
} else {
os << "*";
}
os << '}';
return os;
}
TupleTypePtr TupleType::createNamed(
const c10::optional<c10::QualifiedName>& qualName,
const std::vector<std::string>& field_names,
const std::vector<TypePtr>& field_types) {
TORCH_INTERNAL_ASSERT(field_names.size() == field_types.size());
std::vector<Argument> arguments;
for (size_t i = 0; i < field_names.size(); ++i) {
arguments.emplace_back(
/*name=*/field_names[i],
/*type=*/field_types[i],
/*N=*/i);
}
auto schema = std::make_shared<FunctionSchema>(
/*name=*/qualName.value_or(c10::QualifiedName()).name(),
/*overload_name=*/std::string(""),
/*arguments=*/arguments,
/*returns=*/std::vector<Argument>{});
return std::shared_ptr<TupleType>(new TupleType(
field_types, qualName, schema)); // NOLINT(modernize-make-shared)
}
TupleType::TupleType(
std::vector<TypePtr> elements,
c10::optional<c10::QualifiedName> name,
std::shared_ptr<FunctionSchema> schema)
: NamedType(TypeKind::TupleType, std::move(name)),
elements_(std::move(elements)),
schema_(std::move(schema)) {
has_free_variables_ =
std::any_of(elements_.begin(), elements_.end(), [](TypePtr v) {
if (!v) {
throw std::runtime_error("Can not create tuple with None type");
}
return v->hasFreeVariables();
});
if (schema_) {
for (const Argument& arg : schema_->arguments()) {
checkNoAny(*this, "attribute", arg.name(), arg.type());
}
}
}
bool TupleType::isSubtypeOfExt(const TypePtr rhs_, std::ostream* why_not) const {
if (Type::isSubtypeOfExt(rhs_, why_not)) {
return true;
}
if (rhs_->kind() == AnyTupleType::Kind) {
return true;
}
auto rhs = rhs_->cast<TupleType>();
if (!rhs)
return false;
// unnamed tuple is not a subtype of nametuple
if (!schema() && rhs->schema())
return false;
// namedtuple may be a subtype of unnamed tuple
auto test_names_match = [&](const std::shared_ptr<FunctionSchema>& lhs, const std::shared_ptr<FunctionSchema>& rhs) {
const auto& args_lhs = lhs->arguments();
const auto& args_rhs = rhs->arguments();
if (args_lhs.size() != args_rhs.size()) {
return false;
}
for (size_t i = 0; i < args_lhs.size(); ++i) {
if (args_lhs[i].name() != args_rhs[i].name()) {
return false;
}
}
return true;
};
bool names_match = !rhs->schema() || test_names_match(schema(), rhs->schema());
// co-variant rules for tuples
return names_match && compare(*rhs, [&](const TypePtr a, const TypePtr b) {
return a->isSubtypeOfExt(b, why_not);
});
}
bool ListType::isSubtypeOfExt(const TypePtr rhs_, std::ostream* why_not) const {
if (Type::isSubtypeOfExt(rhs_, why_not)) {
return true;
}
if (rhs_->kind() == AnyListType::Kind) {
return true;
}
return false;
}
bool TupleType::operator==(const Type& rhs) const {
bool typesSame =
compare(rhs, [](const TypePtr a, const TypePtr b) { return *a == *b; });
if (!typesSame) {
return false;
}
// `compare` guarantees that rhs is always a TupleType.
auto rhsTuple = rhs.expect<TupleType>();
if (schema_ == nullptr && rhsTuple->schema_ == nullptr) {
return typesSame;
}
if (schema_ == nullptr || rhsTuple->schema_ == nullptr) {
return false;
}
return *schema_ == *rhsTuple->schema_;
}
std::string TupleType::str() const {
std::stringstream ss;
if (schema_ && name()) {
ss << name()->qualifiedName();
} else {
ss << "(";
for(size_t i = 0; i < elements().size(); ++i) {
if(i > 0)
ss << ", ";
ss << elements()[i]->str();
}
ss << ")";
}
return ss.str();
}
std::string TupleType::annotation_str_impl(TypePrinter printer) const {
std::stringstream ss;
if (schema_ && name()) {
ss << name()->qualifiedName();
} else {
ss << "Tuple[";
for(size_t i = 0; i < elements().size(); ++i) {
if(i > 0)
ss << ", ";
ss << elements()[i]->annotation_str(printer);
}
ss << "]";
}
return ss.str();
}
static std::vector<bool> findContiguous(
const at::IntArrayRef& sizes,
const at::IntArrayRef& strides) {
AT_ASSERT(sizes.size() == strides.size());
std::vector<bool> cont(sizes.size());
for (size_t i = 0; i < sizes.size(); ++i) {
const auto expected_stride =
(i + 1 < sizes.size()) ? sizes[i + 1] * strides[i + 1] : 1;
cont[i] = (strides[i] == expected_stride);
}
return cont;
}
VaryingShape<int64_t> TensorType::strides() const {
if (!strides_.size().has_value()) {
return VaryingShape<int64_t>();
}
std::vector<c10::optional<int64_t>> ss(*strides_.size());
for (size_t i = 0; i < *strides_.size(); i++) {
if (!strides_[i].has_value()) {
continue;
}
auto s = *strides_[i];
if (s.stride_index_.has_value() && s.stride_.has_value()) {
ss[*s.stride_index_] = *s.stride_;
}
}
return VaryingShape<int64_t>(ss);
}
VaryingShape<Stride> TensorType::computeStrideProps(
at::IntArrayRef sizes,
at::IntArrayRef strides,
bool tensor_contiguity) {
std::vector<size_t> stride_indices(sizes.size());
std::iota(stride_indices.begin(), stride_indices.end(), 0);
std::sort(
stride_indices.begin(),
stride_indices.end(),
[&strides](const int& a, const int& b) {
// break ties in case of unsqueezed dims
// i.e. (1, 1, 5)
if (strides[a] == strides[b]) {
return a > b;
}
return strides[a] < strides[b];
});
std::vector<Stride> stride_properties;
for (size_t i = 0; i < stride_indices.size(); i++) {
bool contiguous_ = tensor_contiguity;
if (!contiguous_) {
// innermost stride expected to be 1
// TODO: turn contiguous_ into an enum CONTIGUOUS, NONCONTIGUOUS,
// BROADCASTED
if (i == 0) {
contiguous_ = strides[stride_indices[i]] == 1;
} else {
contiguous_ = strides[stride_indices[i]] == 1 ||
(strides[stride_indices[i]] != 0 &&
strides[stride_indices[i]] ==
strides[stride_indices[i - 1]] * sizes[stride_indices[i - 1]]);
}
}
stride_properties.emplace_back(stride_indices[i], contiguous_, strides[stride_indices[i]]);
}
return VaryingShape<Stride>{stride_properties};
}
std::atomic<size_t> ShapeSymbol::num_symbols{1};
template struct VaryingShape<c10::ShapeSymbol>;
template struct VaryingShape<bool>;
template struct VaryingShape<size_t>;
template struct VaryingShape<int64_t>;
TensorType::TensorType(
c10::optional<at::ScalarType> scalar_type,
c10::optional<Device> device,
const SymbolicShape& sizes,
const VaryingShape<Stride>& strides,
c10::optional<bool> requires_grad,
c10::optional<bool> undefined)
: Type(TypeKind::TensorType),
scalar_type_(scalar_type),
device_(device),
sizes_(sizes),
strides_(strides),
requires_grad_(requires_grad),
undefined_(undefined) {}
TensorTypePtr TensorType::create(const at::Tensor& t) {
VaryingShape<bool> contiguity;
VaryingShape<size_t> stride_indices;
VaryingShape<int64_t> strides;
VaryingShape<int64_t> sizes;
if (!t.is_mkldnn() && !t.is_sparse()) {
sizes = VaryingShape<int64_t>{t.sizes().vec()};
strides = VaryingShape<int64_t>{t.strides().vec()};
return TensorType::create(
t.scalar_type(), t.device(), sizes, strides, t.requires_grad(), false, t.is_contiguous());
}
return TensorType::create(
t.scalar_type(),
t.device(),
SymbolicShape(),
VaryingShape<Stride>{},
t.requires_grad(),
false);
}
TensorTypePtr TensorType::create(
c10::optional<at::ScalarType> scalar_type,
c10::optional<Device> device,
const VaryingShape<int64_t>& sizes,
const VaryingShape<int64_t>& strides,
c10::optional<bool> requires_grad,
c10::optional<bool> undefined, bool tensor_contiguity) {
if(strides.concrete_sizes() && strides.concrete_sizes().has_value()){
// handles case where strides are set
TORCH_INTERNAL_ASSERT(sizes.concrete_sizes()->size() == strides.concrete_sizes()->size());
auto sprops = strides.concrete_sizes().has_value()
? computeStrideProps(*sizes.concrete_sizes(), *strides.concrete_sizes(), tensor_contiguity)
: VaryingShape<Stride>();
auto symbol_sizes = SymbolicShape(*sizes.concrete_sizes());
return TensorType::create(
scalar_type, device, symbol_sizes, sprops, requires_grad, undefined);
} else {
// strides are all null, but still have number of strides equal to number of ranks
TORCH_INTERNAL_ASSERT(sizes.sizes() && sizes.size());
auto symbol_sizes = SymbolicShape(*sizes.sizes());
return TensorType::create(
scalar_type, device, symbol_sizes, VaryingShape<Stride>(*sizes.size()), requires_grad, undefined);
}
}
TensorTypePtr TensorType::create(
c10::optional<at::ScalarType> scalar_type,
c10::optional<Device> device,
const SymbolicShape& sizes,
const VaryingShape<Stride>& strides,
c10::optional<bool> requires_grad,
c10::optional<bool> undefined,
bool is_inferred) {
auto pt = TensorTypePtr(new TensorType(
scalar_type, device, sizes, strides, requires_grad, undefined));
pt->is_inferred_ = is_inferred;
return pt;
}
TensorTypePtr TensorType::create(
c10::optional<at::ScalarType> scalar_type,
c10::optional<Device> device,
c10::optional<size_t> dim,
c10::optional<bool> requires_grad) {
return TensorType::create(
scalar_type,
device,
SymbolicShape(dim),
VaryingShape<Stride>(dim),
requires_grad);
}
TensorTypePtr TensorType::createContiguous(
at::ScalarType scalar_type,
at::Device device,