-
Notifications
You must be signed in to change notification settings - Fork 21.4k
/
jit_type.h
2546 lines (2227 loc) · 74 KB
/
jit_type.h
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
#pragma once
#include <ATen/core/TensorBody.h>
#include <ATen/core/functional.h>
#include <ATen/core/interned_strings.h>
#include <ATen/core/ivalue.h>
#include <ATen/core/qualified_name.h>
#include <c10/util/TypeList.h>
#include <c10/util/Optional.h>
#include <iostream>
#include <memory>
#include <type_traits>
#include <array>
struct ClassType;
namespace torch {
namespace jit {
struct CompilationUnit;
} // namespace jit
} // namespace torch
namespace c10 {
struct FunctionSchema;
struct NamedType;
using OptNameList = c10::optional<std::vector<std::string>>;
#define C10_FORALL_TYPES(_) \
_(AnyType) \
_(EnumType) \
_(AnyEnumType) \
_(TensorType) \
_(TupleType) \
_(ListType) \
_(DictType) \
_(NumberType) \
_(FloatType) \
_(FutureType) \
_(RRefType) \
_(IntType) \
_(NoneType) \
_(StringType) \
_(GeneratorType) \
_(QuantizerType) \
_(BoolType) \
_(OptionalType) \
_(VarType) \
_(DeviceObjType) \
_(StreamObjType) \
_(FunctionType) \
_(ClassType) \
_(PyObjectType) \
_(CapsuleType) \
_(InterfaceType) \
_(QSchemeType) \
_(LayoutType) \
_(ScalarTypeType) \
_(AnyListType) \
_(AnyTupleType) \
_(AnyClassType)
enum class TypeKind {
#define DEFINE_TYPE(T) T,
C10_FORALL_TYPES(DEFINE_TYPE)
#undef DEFINE_TYPE
};
CAFFE2_API const char* typeKindToString(TypeKind kind);
struct Type;
using TypePtr = std::shared_ptr<Type>;
using ConstTypePtr = std::shared_ptr<const Type>;
// Use this to customize how a Type is printed using `annotation_str()`. If
// c10::nullopt is returned, `annotation_str()` falls through to its default
// implementation.
using TypePrinter =
std::function<c10::optional<std::string>(const ConstTypePtr&)>;
struct CAFFE2_API Type : std::enable_shared_from_this<Type> {
private:
TypeKind kind_;
protected:
Type(TypeKind kind) : kind_(kind) {}
virtual std::string annotation_str_impl(TypePrinter printer) const {
return str();
}
public:
virtual bool operator==(const Type& rhs) const = 0;
// subtyping relation. By default, we return true for the case
// when the type is exactly equal or if this <: T where rhs = Optional[T]
// if this returns false and the why_not stream is non-null, it contains
// additional details that describe why this is not a subtype of 'rhs'.
// This additional information should only contain details that are not obvious
// from the annotation_str() that describes the type. For instance it is clear that `int <: str` is false
// but not clear why `Foo <: InterfaceBar` might be false.
virtual bool isSubtypeOfExt(const TypePtr& rhs, std::ostream* why_not) const;
virtual bool is_module() const;
bool isSubtypeOf(const TypePtr& rhs) const {
return isSubtypeOfExt(rhs, nullptr);
}
// How this type will appear in FunctionSchema declarations
virtual std::string str() const = 0;
// How this type will appear as if it were a type annotation in Python
// which is sometimes different than how it appears in declarations (e.g.
// int[] vs List[int])
//
// Takes a custom printer that users can pass in to customize the output of
// this method.
std::string annotation_str(TypePrinter printer) const {
if (printer) {
// the printer can return nullopt to fall through to the default impl
if (auto renamed = printer(shared_from_this())) {
return *renamed;
}
}
return annotation_str_impl(printer);
}
std::string annotation_str() const {
// Overload instead of define a default value for `printer` to help
// debuggers out.
return annotation_str(nullptr);
}
// Returns a human readable string that includes additional information like
// "type is inferred rather than explictly defined" to help construct more
// user-friendly messages.
virtual std::string repr_str() const {
return annotation_str();
}
TypeKind kind() const {
return kind_;
}
virtual bool requires_grad() const {
for (const auto& ct : containedTypes()) {
if (ct->requires_grad()) {
return true;
}
}
return false;
}
// Dynamically cast this object to the subclass indicated by the
// template variable, returning nullptr if the cast is invalid.
template <typename T>
std::shared_ptr<T> cast() {
if (T::Kind == kind()) {
return std::static_pointer_cast<T>(shared_from_this());
}
return nullptr;
}
template <typename T>
std::shared_ptr<const T> cast() const {
if (T::Kind == kind()) {
return std::static_pointer_cast<const T>(shared_from_this());
}
return nullptr;
}
template <typename T>
std::shared_ptr<T> expect() {
auto r = cast<T>();
AT_ASSERT(r);
return r;
}
template <typename T>
std::shared_ptr<const T> expect() const {
auto r = cast<const T>();
AT_ASSERT(r);
return r;
}
virtual ~Type() = default;
virtual bool hasFreeVariables() const {
return false;
}
// list of types this type contains, e.g. for a List then element type of a
// list for a tuple, the types of the tuple elements
virtual at::ArrayRef<TypePtr> containedTypes() const {
return {};
}
// create a new version of this type, replacing its contained types with
// contained_types
TypePtr withContained(std::vector<TypePtr> contained_types) {
auto current_contained = containedTypes();
AT_ASSERT(current_contained.size() == contained_types.size());
if (current_contained.equals(contained_types)) {
return shared_from_this();
}
return createWithContained(std::move(contained_types));
}
// per-type constructor, you only need to override this if the
// containedTypes() is not empty
virtual TypePtr createWithContained(
std::vector<TypePtr> contained_types) const {
AT_ERROR(
"type with contained types did not overload createWithContained: ",
str());
}
};
struct AnyType;
using AnyTypePtr = std::shared_ptr<AnyType>;
// Any is the top of the type hierarchy, all other types are subtypes
// T <: Any, forall T
struct CAFFE2_API AnyType : public Type {
static AnyTypePtr create() {
return AnyTypePtr(
new AnyType()); // NOLINT(modernize-make-shared)
}
bool operator==(const Type& rhs) const override {
return rhs.kind() == kind();
}
std::string str() const override {
return "Any";
}
static const TypeKind Kind = TypeKind::AnyType;
// global singleton
static AnyTypePtr get();
private:
AnyType() : Type(TypeKind::AnyType) {}
};
inline std::string toString(TypePtr typePtr) {
return typePtr->str();
}
inline bool operator!=(const Type& lhs, const Type& rhs) {
return !(lhs == rhs);
}
// common base for all types that have a single sub element
// e.g. Future[T], Optional[T], List[T]
template <TypeKind K, typename T>
struct SingleElementType : public Type {
static const TypeKind Kind = K;
TypePtr getElementType() const {
return elem;
}
bool hasFreeVariables() const override {
return getElementType()->hasFreeVariables();
}
at::ArrayRef<TypePtr> containedTypes() const override {
return elem;
}
bool operator==(const Type& rhs) const override {
if (auto rhs_ = rhs.cast<T>()) {
return *getElementType() == *rhs_->getElementType();
}
return false;
}
protected:
SingleElementType(TypePtr elem) : Type(Kind), elem(std::move(elem)) {
if (!this->elem) {
throw std::runtime_error(c10::str(
"Can not create ", typeKindToString(Kind), " with None type"));
}
}
private:
TypePtr elem;
};
struct OptionalType;
using OptionalTypePtr = std::shared_ptr<OptionalType>;
// This type represents an optional type, for each element type.
// Optional[T] can accept both T and None(nullopt in C++)
// Subtype hierarchy for Optional:
// 1. Optional[T] <: Optional[R] iff T <: R
// 2. T <: Optional[R] if T <: R
// 3. None <: Optional[T] for all T
struct CAFFE2_API OptionalType
: public SingleElementType<TypeKind::OptionalType, OptionalType> {
static OptionalTypePtr create(TypePtr element) {
TORCH_INTERNAL_ASSERT(element, "OptionalType requires valid TypePtr");
// Optional is a union of [None, T], so Optional[[Optional[T]]] ->
// Optional[T]
if (auto opt_ptr = element->cast<OptionalType>()) {
return opt_ptr;
}
return OptionalTypePtr(
new OptionalType(std::move(element))); // NOLINT(modernize-make-shared)
}
std::string str() const override {
std::stringstream ss;
ss << getElementType()->str() << "?";
return ss.str();
}
TypePtr createWithContained(
std::vector<TypePtr> contained_types) const override {
AT_ASSERT(contained_types.size() == 1);
return create(contained_types[0]);
}
bool isSubtypeOfExt(const TypePtr& rhs, std::ostream* why_not) const override {
if (Type::isSubtypeOfExt(rhs, why_not)) {
return true;
}
if (auto rhs_ = rhs->cast<OptionalType>()) {
return getElementType()->isSubtypeOfExt(rhs_->getElementType(), why_not);
}
return false;
}
// common cast Optional[Tensor] for undefined tensor type
static OptionalTypePtr ofTensor();
private:
OptionalType(TypePtr elem) : SingleElementType(elem) {}
std::string annotation_str_impl(TypePrinter printer = nullptr) const override {
std::stringstream ss;
ss << "Optional[" << getElementType()->annotation_str(printer) << "]";
return ss.str();
}
};
template <typename T>
inline c10::optional<T> merge_primitive(
const c10::optional<T>& a,
const c10::optional<T>& b) {
if (a.has_value() && b.has_value() && a.value() == b.value()) {
return a;
}
return c10::optional<T>{};
}
// If we see `a + b + c` and know that a, b, and c are the same size and have
// two dimensions (WxH), then we can generate a fused kernel for them. That
// fused kernel would likely have indexing math to handling both the W and H
// dimensions. However, if we knew the WxH dimensions were contiguous, we can
// pretend like we only have a single dimension, simplifying the indexing logic.
// This can be performed even if the dimensions are transposed,
// as long as a, b, and c are transposed in the same way.
// We'd like to have the compiler be able to do this dimensionality reduction,
// but simply knowing sizes is not enough.
// We can extend profiling to also record stride information.
// Rather than recording specific strides,
// we can simply order the strides from smallest to largest with
// `stride_indices` A contiguity marker on the smallest stride (c0) indicates
// the stride is precisely 1, otherwise a contiguity marker means that $stride_n
// = size_{n-1}*stride_{n-1}$
struct CAFFE2_API Stride {
Stride() {}
Stride(
const c10::optional<size_t>& stride_index,
const c10::optional<bool>& contiguous,
const c10::optional<size_t>& stride)
: stride_index_(stride_index), contiguous_(contiguous), stride_(stride) {}
bool operator==(const Stride& b) const {
return stride_index_ == b.stride_index_ && contiguous_ == b.contiguous_ &&
stride_ == b.stride_;
}
c10::optional<size_t> stride_index_;
c10::optional<bool> contiguous_;
c10::optional<size_t> stride_;
};
template <>
inline c10::optional<Stride> merge_primitive(
const c10::optional<Stride>& a,
const c10::optional<Stride>& b) {
c10::optional<Stride> left = a;
c10::optional<Stride> right = b;
if (!left.has_value()) {
left = {Stride()};
}
if (!right.has_value()) {
right = {Stride()};
}
auto merged_index =
merge_primitive(left->stride_index_, right->stride_index_);
auto merged_cont = merge_primitive(left->contiguous_, right->contiguous_);
auto merged_stride = merge_primitive(left->stride_, right->stride_);
auto r = Stride(merged_index, merged_cont, merged_stride);
// normalize
if (!r.stride_index_.has_value() && !r.contiguous_.has_value() &&
!r.stride_.has_value()) {
return c10::optional<Stride>{};
}
return r;
}
struct CAFFE2_API ShapeSymbol {
// needed for use in `std::map`
ShapeSymbol() : value_(-1) {}
// is this symbol a fixed/static dimension
bool is_static() const {
return value_ >= 0;
};
bool operator==(const ShapeSymbol& b) const {
return value_ == b.value_;
}
bool operator<(const ShapeSymbol& b) const {
return value_ < b.value_;
}
static ShapeSymbol fromStaticSize(int64_t val) {
return ShapeSymbol(val);
}
int64_t static_size() const {
TORCH_CHECK(is_static());
return value_;
};
static ShapeSymbol newSymbol() {
return fromStaticSize(-static_cast<int64_t>(++num_symbols));
};
friend CAFFE2_API std::ostream& operator<<(
std::ostream& os,
const ShapeSymbol& s);
private:
ShapeSymbol(int64_t val) : value_(val) {}
int64_t value_;
static std::atomic<size_t> num_symbols;
};
inline ShapeSymbol merge_primitive(
const ShapeSymbol& a,
const ShapeSymbol& b) {
if (a.is_static() && b.is_static() && a == b) {
return a;
}
return ShapeSymbol::newSymbol();
}
// Shape of a Tensor represented with ShapeSymbol's. Unranked, ranked unknown
// dims, partially known and fully known shapes are all supported.
struct CAFFE2_API SymbolicShape {
// Unranked shape constructor.
SymbolicShape() : dims_(c10::nullopt) {}
// Known rank but unknown dimentions.
SymbolicShape(c10::optional<size_t> rank) : dims_(c10::nullopt) {
if(!rank) {
return;
}
std::vector<ShapeSymbol> shape_symbols;
shape_symbols.reserve(*rank);
for(size_t i = 0; i < *rank; ++i) {
shape_symbols.push_back(ShapeSymbol::newSymbol());
}
dims_ = shape_symbols;
}
// Mix of known and unknown ranks
SymbolicShape(const std::vector<c10::optional<int64_t>>& dims) {
std::vector<ShapeSymbol> shape_symbols;
shape_symbols.reserve(dims.size());
for(c10::optional<int64_t> dim: dims) {
if(!dim) {
shape_symbols.push_back(ShapeSymbol::newSymbol());
} else {
shape_symbols.push_back(ShapeSymbol::fromStaticSize(*dim));
}
}
dims_ = shape_symbols;
}
SymbolicShape(std::vector<ShapeSymbol> dims) : dims_(std::move(dims)) {}
SymbolicShape(c10::IntArrayRef dims) {
std::vector<ShapeSymbol> shape_symbols;
shape_symbols.reserve(dims.size());
for(int64_t dim : dims) {
shape_symbols.push_back(ShapeSymbol::fromStaticSize(dim));
}
dims_ = shape_symbols;
}
ShapeSymbol operator[](size_t i) const {
if (!dims_) {
throw std::runtime_error("Rank isn't fixed");
}
return (*dims_).at(i);
}
// Returns rank or nullopt in case of unranked shape.
c10::optional<size_t> rank() const {
if(!dims_) {
return c10::nullopt;
}
return dims_->size();
}
c10::optional<std::vector<ShapeSymbol>> sizes() const {
return dims_;
}
// Checks whether the shape is fully defined/complete, ie. rank and sizes
// of every dimension are known.
bool isComplete() const {
if(!dims_) {
return false;
}
for(auto d : *dims_) {
if(!d.is_static()) {
return false;
}
}
return true;
}
// Create new SymbolicShape that is result of merging self and another
// SymbolicShape. Only dimensions that are static and equal will be
// preserved.
// If either of two shapes are of unknown rank or they have unmatching rank,
// result will be unranked.
SymbolicShape merge(const SymbolicShape& other) const;
private:
c10::optional<std::vector<ShapeSymbol>> dims_;
};
template <typename T>
struct VaryingShape {
using ListOfOptionalElements = std::vector<c10::optional<T>>;
VaryingShape(const std::vector<T>& vec)
: VaryingShape(ListOfOptionalElements(vec.begin(), vec.end())) {}
VaryingShape(c10::ArrayRef<T> vec)
: VaryingShape(ListOfOptionalElements(vec.begin(), vec.end())) {}
VaryingShape(c10::optional<size_t> size = c10::nullopt) : dims_(c10::nullopt) {
if (size) {
dims_ = ListOfOptionalElements(*size);
}
}
VaryingShape(ListOfOptionalElements dims) : dims_(std::move(dims)) {}
VaryingShape(size_t size) : VaryingShape(c10::optional<size_t>(size)) {}
bool operator==(const VaryingShape& other) const {
return dims_ == other.dims_;
}
const c10::optional<T> &operator[](size_t i) const {
if (!dims_) {
throw std::runtime_error("Rank isn't fixed");
}
return (*dims_).at(i);
}
c10::optional<size_t> size() const {
if (!dims_) {
return c10::nullopt;
}
const auto& dims = dims_.value();
return dims.size();
}
const c10::optional<ListOfOptionalElements>& sizes() const {
return dims_;
}
CAFFE2_API VaryingShape merge(const VaryingShape& other) const;
c10::optional<std::vector<T>> concrete_sizes() const {
if (!dims_) {
return c10::nullopt;
}
std::vector<T> sizes;
for (auto d : *dims_) {
if (!d) {
return c10::nullopt;
}
sizes.push_back(d.value());
}
return sizes;
}
bool isComplete() const {
if (!dims_) {
return false;
}
for (auto d : *dims_) {
if(!d) {
return false;
}
}
return true;
}
private:
c10::optional<ListOfOptionalElements> dims_;
};
struct TensorType;
using TensorTypePtr = std::shared_ptr<TensorType>;
// This type represents a single Tensor with a specific size
struct CAFFE2_API TensorType : public Type {
static TensorTypePtr create(const at::Tensor& t);
// used by TensorType::create(size_t dim) which in turn used by
// shape_analysis.cpp
static TensorTypePtr 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 = false,
bool tensor_contiguity = false);
static TensorTypePtr create(
c10::optional<at::ScalarType> scalar_type,
c10::optional<Device> device,
const SymbolicShape& sizes,
const VaryingShape<Stride>& stride_,
c10::optional<bool> requires_grad,
c10::optional<bool> undefined = false,
bool is_inferred = false);
static TensorTypePtr create(
c10::optional<at::ScalarType> scalar_type,
c10::optional<Device> device,
c10::optional<size_t> dim,
c10::optional<bool> requires_grad);
// overloaded create variadic template argument as it could not distinguish
// initializer list
static TensorTypePtr createContiguous(
at::ScalarType scalar_type,
at::Device device,
at::IntArrayRef sizes);
static TypePtr fromNumberType(TypePtr typ);
static TypePtr fromBoolType();
c10::optional<size_t> dim() const {
return sizes().size();
}
VaryingShape<int64_t> sizes() const;
VaryingShape<int64_t> strides() const;
const VaryingShape<Stride>& stride_properties() const {
return strides_;
}
c10::optional<at::Device> device() const {
return device_;
}
c10::optional<at::ScalarType> scalarType() const {
return scalar_type_;
}
c10::optional<bool> requiresGrad() const {
return requires_grad_;
}
bool requires_grad() const override {
return requires_grad_ ? *requires_grad_ : true;
}
bool operator==(const Type& rhs) const override;
bool isSubtypeOfExt(const TypePtr& rhs, std::ostream* why_not) const override;
std::string str() const override;
std::string repr_str() const override {
return str() + (isInferredType() ? " (inferred)" : "");
}
c10::optional<size_t> numel() const {
size_t prod = 1;
const auto& shape = sizes();
for (size_t i = 0; i < shape.size(); i++) {
if (!shape[i]) {
return c10::optional<size_t>{};
}
prod *= shape[i].value();
}
return prod;
}
TensorTypePtr withRequiresGrad(c10::optional<bool> s) {
auto copy = clone();
copy->requires_grad_ = s;
return copy;
}
TensorTypePtr withScalarType(c10::optional<ScalarType> st) {
auto copy = clone();
copy->scalar_type_ = st;
return copy;
}
TensorTypePtr withDim(c10::optional<size_t> d) {
auto copy = clone();
// withDim is only used by the legacy executor
// that only cares about the rank, so create dummy symbols)) :
copy->sizes_ = SymbolicShape(d);
copy->strides_ = VaryingShape<Stride>(d);
return copy;
}
TensorTypePtr withSizesStrides(
at::IntArrayRef sizes,
at::IntArrayRef strides) const {
auto cloned = clone();
auto ssizes = SymbolicShape(sizes);
cloned->sizes_ = ssizes;
cloned->strides_ = computeStrideProps(sizes, strides);
return cloned;
}
TensorTypePtr withSymbolicShapes(SymbolicShape ssizes) const {
auto cloned = clone();
cloned->sizes_ = std::move(ssizes);
return cloned;
}
TensorTypePtr withSizes(at::IntArrayRef sizes) const {
return withSizesStrides(
sizes, contiguousStridesOf(sizes));
}
TensorTypePtr dimensionedOnly() const {
auto copy = clone();
copy->sizes_ = SymbolicShape(sizes().size());
copy->strides_ = VaryingShape<Stride>(sizes().size());
return copy;
}
TensorTypePtr contiguous() const {
auto cloned = clone();
TORCH_INTERNAL_ASSERT(sizes().concrete_sizes().has_value());
auto strides = computeStrideProps(
*sizes().concrete_sizes(),
contiguousStridesOf(*sizes().concrete_sizes()));
cloned->strides_ = strides;
return cloned;
}
const SymbolicShape& symbolic_sizes() const;
TensorTypePtr merge(const TensorType& other, bool merge_sizes = true) const;
bool matchTensor(const at::Tensor& t);
// is all information about the type specified except for autograd?
// This replaces the notion of a 'CompleteTensorType' that used to exist
// in the type-hierarchy. Excluding require_grad and undefined allows
// this to match the old behavior.
bool isComplete() const {
return scalar_type_ && device_ && sizes_.isComplete() && strides_.isComplete();
}
bool isInferredType() const {
return is_inferred_;
}
static TensorTypePtr getInferred() {
static auto valueInferred = TensorType::create(
/*scalar_type=*/{}, /*device=*/{},
/*sizes=*/SymbolicShape(),
/*stride=*/VaryingShape<Stride>{}, /*requires_grad=*/{},
/*undefined=*/false, /*is_inferred=*/true);
return valueInferred;
}
// this property is used by GuardElimination
// please see `checkInputs` for more details
bool isSummarized() const {
return !(isComplete() && requiresGrad().has_value() &&
undefined().has_value());
}
TensorTypePtr withUndefined() {
auto r = clone();
r->undefined_ = true;
return r;
}
TensorTypePtr withPossiblyUndefined() {
auto r = clone();
r->undefined_ = c10::nullopt;
return r;
}
c10::optional<bool> undefined() const { return undefined_; }
static TensorTypePtr get();
static const TypeKind Kind = TypeKind::TensorType;
private:
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 = false);
TensorTypePtr clone() const {
return TensorTypePtr(new TensorType(
scalar_type_, device_, sizes_, strides_, requires_grad_, undefined_));
}
static std::vector<int64_t> contiguousStridesOf(at::IntArrayRef sizes) {
std::vector<int64_t> strides(sizes.size());
if (sizes.empty()) // zero-dim case
return strides;
strides.back() = 1;
for (size_t i = strides.size() - 1; i > 0; i--) {
strides[i - 1] = strides[i] * sizes[i];
}
return strides;
}
static VaryingShape<Stride> computeStrideProps(
at::IntArrayRef sizes,
at::IntArrayRef strides,
bool tensor_contiguity = false);
c10::optional<at::ScalarType> scalar_type_;
c10::optional<at::Device> device_;
SymbolicShape sizes_;
VaryingShape<Stride> strides_;
c10::optional<bool> requires_grad_;
// we exploit the fact certain tensors must be zero in the autograd to
// optimize gradient computation. Such zero tensors are currently implemented
// with `UndefinedTensorImpl.` They can be handled only by special operators
// (e.g. `AutogradAdd`) and their `Tensor::defined()` property returns false.
// Normally, `undefined_` is set to false, unless a type was created
// with `withUndefined`
// This will also mean that `undefined` tensors will fail
// `subtypeOf(TensorType::get())` check
// undefined_ may become `c10::nullopt` if the tensor was observed to be both
// defined and undefined. However, no tensor type starts out with
// `undefined_` set to `c10::nullopt`
c10::optional<bool> undefined_;
// Represents whether or not this type was inferred.
bool is_inferred_ = false;
};
struct ListType;
using ListTypePtr = std::shared_ptr<ListType>;
struct CAFFE2_API ListType
: public SingleElementType<TypeKind::ListType, ListType> {
// It's not exactly a singleton, but there should be exactly one instance of
// List[T] for every T
friend struct Type;
template <typename... T>
static ListTypePtr create(T&&... all) {
return ListTypePtr(
new ListType(std::forward<T>(all)...)); // NOLINT(modernize-make-shared)
}
std::string str() const override {
std::stringstream ss;
ss << getElementType()->str() << "[]";
return ss.str();
}
TypePtr createWithContained(
std::vector<TypePtr> contained_types) const override {
return create(contained_types.at(0));
}
bool isSubtypeOfExt(const TypePtr& rhs, std::ostream* why_not) const override;
// common cast List[Tensor]
static ListTypePtr ofTensors();
static ListTypePtr ofInts();
static ListTypePtr ofFloats();
static ListTypePtr ofBools();
static ListTypePtr ofStrings();
private:
ListType(TypePtr elem) : SingleElementType(elem) {}
std::string annotation_str_impl(TypePrinter printer = nullptr) const override {
std::stringstream ss;
ss << "List[" << getElementType()->annotation_str(printer) << "]";
return ss.str();
}
};
struct DictType;
using DictTypePtr = std::shared_ptr<DictType>;
struct CAFFE2_API DictType : public Type {
friend struct Type;
static const TypeKind Kind = TypeKind::DictType;
static DictTypePtr create(TypePtr key, TypePtr value) {
switch (key->kind()) {
case TypeKind::AnyType:
case TypeKind::IntType:
case TypeKind::BoolType:
case TypeKind::FloatType:
case TypeKind::StringType:
case TypeKind::TensorType:
return DictTypePtr(new DictType(key, value));
default:
AT_ERROR(
"Cannot create dict for key type '",
key->str(),
"', only int, float, Tensor and string keys are supported");
}
}
// aligned with the format in FunctionSchema
std::string str() const override {
std::stringstream ss;
ss << "Dict(" << getKeyType()->str() << ", " << getValueType()->str()
<< ")";
return ss.str();
}
TypePtr createWithContained(
std::vector<TypePtr> contained_types) const override {
if (contained_types.size() != 2) {
throw std::runtime_error("Expected 2 contained types");
}
return create(contained_types.at(0), contained_types.at(1));
}
TypePtr getKeyType() const {
return types.at(0);
}
TypePtr getValueType() const {
return types.at(1);
}
bool hasFreeVariables() const override {
return has_free_variables;
}
at::ArrayRef<TypePtr> containedTypes() const override {
return types;
}
bool operator==(const Type& rhs) const override {
if (auto dict_rhs = rhs.cast<DictType>()) {
return *getKeyType() == *(dict_rhs->getKeyType()) &&
*getValueType() == *(dict_rhs->getValueType());
}
return false;
}
private:
DictType(TypePtr key, TypePtr value)
: Type(TypeKind::DictType),
types({key, value}),
has_free_variables(
key->hasFreeVariables() || value->hasFreeVariables()) {}
std::string annotation_str_impl(TypePrinter printer = nullptr) const override {
std::stringstream ss;
ss << "Dict[" << getKeyType()->annotation_str(printer) << ", "
<< getValueType()->annotation_str(printer) << "]";
return ss.str();
}
std::vector<TypePtr> types;
bool has_free_variables;
};
struct FutureType;
using FutureTypePtr = std::shared_ptr<FutureType>;
struct CAFFE2_API FutureType
: public SingleElementType<TypeKind::FutureType, FutureType> {
friend struct Type;
template <typename... T>
static FutureTypePtr create(TypePtr elem) {
return FutureTypePtr(
new FutureType(std::move(elem))); // NOLINT(modernize-make-shared)
}
std::string str() const override {
std::stringstream ss;
ss << "Future(" << getElementType()->str() << ")";
return ss.str();