forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ivalue.h
1587 lines (1412 loc) · 50.2 KB
/
ivalue.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/DimVector.h>
#include <ATen/core/TensorBody.h>
#include <ATen/core/blob.h>
#include <ATen/core/custom_class.h>
#include <ATen/core/ivalue_to.h>
#include <ATen/core/jit_type_base.h>
#include <ATen/core/type_factory.h>
#include <c10/core/SymBool.h>
#include <c10/core/SymFloat.h>
#include <c10/macros/Export.h>
#include <c10/util/MaybeOwned.h>
#include <c10/util/intrusive_ptr.h>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
namespace torch {
class TORCH_API CustomClassHolder : public c10::intrusive_ptr_target {};
namespace jit {
using ::torch::CustomClassHolder;
struct Function;
struct CompilationUnit;
struct Module;
} // namespace jit
} // namespace torch
namespace c10 {
template <class Key, class Value>
class Dict;
template <class T>
class List;
template <class T>
class IListRef;
struct IValue;
struct ClassType;
struct Type;
class RRefInterface;
struct ClassType;
using ClassTypePtr = std::shared_ptr<ClassType>;
TORCH_API bool _fastEqualsForContainer(const IValue& lhs, const IValue& rhs);
TORCH_API torch::jit::Function* checkObjectSortSchema(
const c10::ClassTypePtr& t,
std::stringstream& why_not);
// A comparator that checks ordering of two IValues of same type.
typedef std::function<bool(const IValue& a, const IValue& b)> IValueComparator;
TORCH_API IValueComparator getLessThanComparator(const IValue& v);
TORCH_API IValueComparator getGreaterThanComparator(const IValue& v);
namespace ivalue {
struct Tuple;
struct Future;
struct Await;
struct ConstantString;
struct GenericDict;
struct Object;
struct PyObjectHolder;
struct EnumHolder;
// We need a ComplexHolder because currently the payloads in the Union
// only take 64 bits. Since ComplexDouble takes up 128 bits, and is too big
// to fit in the IValue directly, we indirect complex numbers through an
// intrusive pointer to ComplexHolder (which contains a c10::complex).
struct ComplexHolder : c10::intrusive_ptr_target {
public:
template <typename T>
ComplexHolder(c10::complex<T> c) {
val = convert<decltype(val), c10::complex<T>>(c);
}
ComplexHolder() = default;
c10::complex<double> val;
};
// Similar to ComplexHolder, for StreamData3
struct StreamData3Holder : c10::intrusive_ptr_target {
public:
StreamData3Holder(struct c10::StreamData3 d) : val(d) {}
StreamData3Holder() = delete;
struct c10::StreamData3 val;
};
} // namespace ivalue
// This is an owning wrapper for a std::optional<std::vector<T>>
// that can be implicitly converted to a (non-owning) std::optional<ArrayRef<T>>.
// Its purpose is to be used in generated code to keep the vector alive
// either until the end of a statement (as a temporary), or as a saved arg
// in autograd.
template <typename T>
struct OptionalArray {
std::optional<std::vector<T>> list;
OptionalArray() = default;
OptionalArray(std::vector<T> val) : list(std::move(val)) {}
// Used when saving an argument for the backwards pass.
OptionalArray& operator=(std::optional<ArrayRef<T>> ref) {
if (ref) {
list = std::vector<T>(ref->begin(), ref->end());
} else {
list = std::nullopt;
}
return *this;
}
// Used when saving an argument for the backwards pass.
OptionalArray& operator=(c10::OptionalArrayRef<T> ref) {
if (ref) {
list = std::vector<T>(ref->begin(), ref->end());
} else {
list = std::nullopt;
}
return *this;
}
operator std::optional<c10::ArrayRef<T>>() {
if (!list) {
return std::nullopt;
}
return *list;
}
operator c10::OptionalArrayRef<T>() {
if (!list) {
return std::nullopt;
}
return *list;
}
};
// Capsule is an internal implementation detail of custom C++ classes. We
// define it as an owning wrapper for
// c10::intrusive_ptr<torch::CustomClassHolder> This wrapper is here to serve as
// an abstraction of the type erased custom class object pointer. It also allow
// pybind11 to treat this as a standalone class to register as a separate type
// caster, instead of a custom pointer holder which the pointer holder type
// caster try to "unwrap" it automatically.
struct Capsule {
c10::intrusive_ptr<torch::CustomClassHolder> obj_ptr;
explicit Capsule(c10::intrusive_ptr<torch::CustomClassHolder> ptr)
: obj_ptr(std::move(ptr)) {}
};
// IValue is the generic tagged union used by the interpreter to hold
// all value types.
// It is a 16-byte object with an 8-byte payload and an 8-byte tag.
// The tag is currently 4 bytes to determine the type, and 1 byte
// to mark whether that type is a subtype of c10::intrusive_ptr_target and needs
// retain/release calls.
#define TORCH_FORALL_TAGS(_) \
_(None) \
_(Tensor) \
_(Storage) \
_(Double) \
_(ComplexDouble) \
_(Int) \
_(SymInt) \
_(SymFloat) \
_(SymBool) \
_(Bool) \
_(Tuple) \
_(String) \
_(Blob) \
_(GenericList) \
_(GenericDict) \
_(Future) \
_(Await) \
_(Device) \
_(Stream) \
_(Object) \
_(PyObject) \
_(Uninitialized) \
_(Capsule) \
_(RRef) \
_(Quantizer) \
_(Generator) \
_(Enum)
// [doxygen private]
// These methods are not actually private but we don't want to document them, so
// they are marked `@private`, which hides them on the doxygen documentation for
// this page.
/// IValue (Interpreter Value) is a tagged union over the types
/// supported by the TorchScript interpreter. IValues contain their
/// values as an `IValue::Payload`, which holds primitive types
/// (`int64_t`, `bool`, `double`, `Device`) and `Tensor` as values,
/// and all other types as a `c10::intrusive_ptr`. In order to
/// optimize performance of the destructor and related operations by
/// making the `Tensor` and `c10::intrusive_ptr` paths generate the
/// same code, we represent a null `c10::intrusive_ptr` as
/// `UndefinedTensorImpl::singleton()`, *not* `nullptr`.
///
/// IValues are used as inputs to and outputs from the TorchScript interpreter.
/// To retrieve the value contained within an IValue, use the `.toX()` methods,
/// where `X` is the type you are trying to get. Note that neither the `.toX()`
/// methods nor the templated `.to<T>` functions do any kind of casting, they
/// only unwrap the contained value. For example:
///
/// \rst
/// .. code-block:: cpp
///
/// // Make the IValue
/// torch::IValue my_ivalue(26);
/// std::cout << my_ivalue << "\n";
///
/// // Unwrap the IValue
/// int64_t my_int = my_ivalue.toInt();
/// std::cout << my_int << "\n";
///
/// // This will throw an error!
/// // `my_ivalue` is tagged as an int and cannot be used as another type
/// torch::Tensor my_tensor = my_ivalue.toTensor();
/// \endrst
struct TORCH_API IValue final {
IValue(const IValue& rhs) : IValue(rhs.payload, rhs.tag) {
if (isIntrusivePtr() &&
payload.u.as_intrusive_ptr != c10::UndefinedTensorImpl::singleton()) {
c10::raw::intrusive_ptr::incref(payload.u.as_intrusive_ptr);
}
}
IValue(IValue&& rhs) noexcept : tag(rhs.tag) {
moveFrom(std::move(rhs));
}
/// @private [doxygen private]
~IValue() {
destroy();
}
C10_ALWAYS_INLINE IValue& operator=(IValue&& rhs) & noexcept {
if (&rhs == this) {
return *this;
}
destroy();
moveFrom(std::move(rhs));
return *this;
}
IValue& operator=(IValue const& rhs) & {
*this = IValue(rhs);
return *this;
}
void dump() const;
/**
* Equality comparison. The semantics are the same as Python's `==`:
* 1. Numerical types are compared by value.
* 2. Tensors compute element-wise equality, returning a BoolTensor (see:
* `torch.eq()`)
* 3. Strings are compared by value.
* 4. Sequence types (list, tuple) are compared lexicographically by
* comparing their elements. Different sequence types never compare equal.
* 5. Mappings (dict) must have equal (key, value) pairs.
* 6. If not listed above, the default behavior for is to test identity
* equality (e.g. pointer equality).
*
* Why does this return an IValue instead of a bool? Because in PyTorch,
* `tensor1 == tensor2` returns a `BoolTensor`, not a bool.
*
* NOTE: we (like Python) assume that identity equality implies value equality
* for efficiency.
* TODO: need to support customizing equality
*/
IValue equals(const IValue& rhs) const;
/**
* This implements the same semantics as `bool(lhs == rhs)` in Python. which
* is the same as `equals()` except for Tensor types.
*/
TORCH_API friend bool operator==(const IValue& lhs, const IValue& rhs);
TORCH_API friend bool operator!=(const IValue& lhs, const IValue& rhs);
/**
* Identity comparison. Checks if `this` is the same object as `rhs`. The
* semantics are the same as Python's `is` operator.
*
* NOTE: Like in Python, this operation is poorly defined for primitive types
* like numbers and strings. Prefer to use `==` unless you really want to
* check identity equality.
*/
bool is(const IValue& rhs) const;
/**
* Hashing for IValues. Returns an IValue-boxed int.
*
* Some notes:
* - Like eager, Tensors are hashed by looking at the pointer. This is not
* strictly correct because two value-equal tensors with different tensor
* pointers will hash differently, but we choose to reproduce the eager
* semantics.
* - Hashing is not defined on all built-in IValue types (e.g. list and
* dict), following Python. Calling `hash()` on these types will throw.
*/
IValue hash() const {
return (int64_t)IValue::hash(*this);
}
// This is defined because `c10::hash` dispatches to a function of this
// signature. See the member function `hash()`.
static size_t hash(const IValue& iv);
/**
* @private [doxygen private]
* [container equality]
* This is an equality implementation that assumes objects with the same
* identity equal themselves, for efficiency reasons. We primarily have this
* for consistency, because Python does the same thing. This actually
* provokes user-visible changes in behavior due to quirks in torch:
* [tensor1] == [tensor1] -> True (because container equality will first
* compare identity) [tensor1] == [tensor1_copy] -> RuntimeError:
* Boolean value of Tensor with more than one value is ambiguous
*/
TORCH_API friend bool _fastEqualsForContainer(
const IValue& lhs,
const IValue& rhs);
private:
static bool isAliasOf(const at::Tensor& a, const at::Tensor& b) {
if (a.is_sparse()) {
return isAliasOf(a._values(), b) || isAliasOf(a._indices(), b);
}
if (b.is_sparse()) {
return isAliasOf(a, b._values()) || isAliasOf(a, b._indices());
}
if (a.is_sparse_csr()) {
return isAliasOf(a.values(), b) || isAliasOf(a.crow_indices(), b) ||
isAliasOf(a.col_indices(), b);
}
if (b.is_sparse_csr()) {
return isAliasOf(a, b.values()) || isAliasOf(a, b.crow_indices()) ||
isAliasOf(a, b.col_indices());
}
// Opaque tensors such as the ones constructed by the MKL-DNN backend
// don't have storage so we just compare their TensorImpls.
// TODO: Find way to expose alias info for opaque tensors.
if (!a.has_storage() || !b.has_storage()) {
return a.unsafeGetTensorImpl() == b.unsafeGetTensorImpl();
}
return a.is_alias_of(b);
}
template <typename T>
bool isListOf() const;
public:
/// @private [doxygen private]
bool isAliasOf(const IValue& rhs) const {
if (this->tag != rhs.tag) {
// Trivially don't alias if the type is different
return false;
}
// Tensors should be compared based on internal storage
if (this->isTensor()) {
return isAliasOf(this->toTensor(), rhs.toTensor());
}
if (!isIntrusivePtr()) {
// Primitive types don't alias anything
return false;
}
AT_ASSERT(rhs.isIntrusivePtr());
// Other types can be compared by their ptr value
return this->payload.u.as_intrusive_ptr == rhs.payload.u.as_intrusive_ptr;
}
/// @private [doxygen private]
size_t use_count() const noexcept {
if (isTensor()) {
return payload.as_tensor.use_count();
}
if (!isIntrusivePtrLegacyBehavior()) {
return 1;
}
if (payload.u.as_intrusive_ptr == c10::UndefinedTensorImpl::singleton()) {
return 0;
}
return c10::raw::intrusive_ptr::use_count(payload.u.as_intrusive_ptr);
}
/// @private [doxygen private]
void swap(IValue& rhs) noexcept {
if (isTensor() && rhs.isTensor()) {
std::swap(payload.as_tensor, rhs.payload.as_tensor);
} else if (isTensor()) {
at::Tensor t = std::move(payload.as_tensor);
// As far as I can tell, omitting the usual explicit destructor call
// is not UB in and of itself, and it's a slight perf win. The
// destructor is a no-op, because the moved-from Tensor is
// effectively an intrusive_ptr in the null state, so we don't need
// the behavior for correctness reasons either. Leaving this
// explanatory comment, including commented-out destructor call, to
// make this abundantly clear.
//
// payload.as_tensor.~Tensor();
payload.u = rhs.payload.u;
new (&rhs.payload.as_tensor) at::Tensor(std::move(t));
} else if (rhs.isTensor()) {
rhs.swap(*this);
return;
} else {
std::swap(payload.u, rhs.payload.u);
}
std::swap(tag, rhs.tag);
}
// Accessors for subtypes are arranged together below
// While some of these accessors could be generated through templates,
// we prefer to write them manually for clarity
IValue(at::TensorBase t) : tag(Tag::Tensor) {
new (&payload.as_tensor) at::Tensor(std::move(t));
}
bool isTensor() const {
return Tag::Tensor == tag;
}
private:
// Outlined error path so that toTensor() can be inlined.
[[noreturn]] void reportToTensorTypeError() const;
public:
at::Tensor toTensor() &&;
at::Tensor& toTensor() &;
const at::Tensor& toTensor() const&;
at::TensorImpl* unsafeToTensorImpl() const {
TORCH_INTERNAL_ASSERT(isTensor());
return payload.as_tensor.unsafeGetTensorImpl();
}
IValue(at::Storage s) : tag(Tag::Storage) {
payload.u.as_intrusive_ptr =
null_to_undefined_tensor(s.unsafeReleaseStorageImpl());
}
bool isStorage() const {
return Tag::Storage == tag;
}
c10::Storage toStorage() &&;
c10::Storage toStorage() const&;
const IValue& toIValue() const {
return *this;
}
IValue& toIValue() {
return *this;
}
/// @private [doxygen private]
IValue(intrusive_ptr<caffe2::Blob> blob) : tag(Tag::Blob) {
// TODO (after Tensor merge) If we pass in a Blob holding a Tensor, extract
// and store it as a Tensor instead.
payload.u.as_intrusive_ptr = null_to_undefined_tensor(blob.release());
}
/// @private [doxygen private]
bool isBlob() const {
return Tag::Blob == tag;
}
/// @private [doxygen private]
c10::intrusive_ptr<caffe2::Blob> toBlob() &&;
/// @private [doxygen private]
c10::intrusive_ptr<caffe2::Blob> toBlob() const&;
// Capsule. No new callsites of these APIs should
// be introduced.
static inline IValue make_capsule(
intrusive_ptr<torch::CustomClassHolder> blob);
bool isCapsule() const {
return Tag::Capsule == tag;
}
c10::intrusive_ptr<torch::CustomClassHolder> toCapsule() &&;
c10::intrusive_ptr<torch::CustomClassHolder> toCapsule() const&;
// Custom C++ classes
template <
typename T,
std::enable_if_t<std::is_base_of_v<torch::CustomClassHolder, T>, int> = 0>
IValue(intrusive_ptr<T> custom_class);
bool isCustomClass() const;
template <typename T>
c10::intrusive_ptr<T> toCustomClass() &&;
template <typename T>
c10::intrusive_ptr<T> toCustomClass() const&;
// Tuple
IValue(c10::intrusive_ptr<ivalue::Tuple> v);
template <
typename... Args,
std::enable_if_t<
!std::disjunction_v<
std::is_lvalue_reference<Args>...,
std::negation<std::is_constructible<IValue, Args>>...>,
std::nullptr_t> = nullptr>
IValue(const std::tuple<Args...>& t);
template <
typename... Args,
std::enable_if_t<
!std::disjunction_v<
std::is_lvalue_reference<Args>...,
std::negation<std::is_constructible<IValue, Args>>...>,
std::nullptr_t> = nullptr>
IValue(std::tuple<Args...>&& t);
bool isTuple() const {
return Tag::Tuple == tag;
}
c10::intrusive_ptr<ivalue::Tuple> toTuple() &&;
c10::intrusive_ptr<ivalue::Tuple> toTuple() const&;
[[nodiscard]] ivalue::Tuple& toTupleRef() const;
// Double
IValue(double d) : tag(Tag::Double) {
payload.u.as_double = d;
}
bool isDouble() const {
return Tag::Double == tag;
}
double toDouble() const {
if (isDouble()) {
return payload.u.as_double;
} else if (isSymFloat()) {
return toSymFloat().guard_float(__FILE__, __LINE__);
} else {
TORCH_INTERNAL_ASSERT(0, "expected double");
}
}
// ComplexDouble
template <typename T>
IValue(c10::complex<T> c);
bool isComplexDouble() const {
return Tag::ComplexDouble == tag;
}
c10::complex<double> toComplexDouble() const;
// Future
IValue(c10::intrusive_ptr<ivalue::Future> v);
bool isFuture() const {
return Tag::Future == tag;
}
c10::intrusive_ptr<ivalue::Future> toFuture() &&;
c10::intrusive_ptr<ivalue::Future> toFuture() const&;
IValue(c10::intrusive_ptr<ivalue::Await> v);
bool isAwait() const {
return Tag::Await == tag;
}
c10::intrusive_ptr<ivalue::Await> toAwait() &&;
c10::intrusive_ptr<ivalue::Await> toAwait() const&;
// RRef
IValue(c10::intrusive_ptr<c10::RRefInterface> v);
bool isRRef() const {
return Tag::RRef == tag;
}
c10::intrusive_ptr<c10::RRefInterface> toRRef() &&;
c10::intrusive_ptr<c10::RRefInterface> toRRef() const&;
// Quantizer
IValue(c10::intrusive_ptr<at::Quantizer> v);
bool isQuantizer() const {
return Tag::Quantizer == tag;
}
c10::intrusive_ptr<at::Quantizer> toQuantizer() &&;
c10::intrusive_ptr<at::Quantizer> toQuantizer() const&;
// Int
IValue(int64_t i) : tag(Tag::Int) {
payload.u.as_int = i;
}
IValue(const c10::SymInt& i) {
if (auto mi = i.maybe_as_int()) {
tag = Tag::Int;
payload.u.as_int = *mi;
} else {
tag = Tag::SymInt;
payload.u.as_intrusive_ptr = i.toSymNode().release();
}
}
bool isSymInt() const {
return Tag::SymInt == tag;
}
c10::SymInt toSymInt() &&;
c10::SymInt toSymInt() const&;
IValue(const c10::SymFloat& i) {
if (i.is_symbolic()) {
tag = Tag::SymFloat;
payload.u.as_intrusive_ptr = i.toSymNodeImpl().release();
} else {
tag = Tag::Double;
payload.u.as_double = i.as_float_unchecked();
}
}
bool isSymFloat() const {
return Tag::SymFloat == tag;
}
c10::SymFloat toSymFloat() &&;
c10::SymFloat toSymFloat() const&;
IValue(const c10::SymBool& i) {
if (auto mi = i.maybe_as_bool()) {
tag = Tag::Bool;
payload.u.as_int = *mi;
} else {
tag = Tag::SymBool;
payload.u.as_intrusive_ptr = i.toSymNodeImpl().release();
}
}
bool isSymBool() const {
return Tag::SymBool == tag;
}
c10::SymBool toSymBool() &&;
c10::SymBool toSymBool() const&;
// allow you to pass literals (3, 4) without ambiguity
IValue(int32_t i) : IValue(static_cast<int64_t>(i)) {}
bool isInt() const {
return Tag::Int == tag;
}
int64_t toInt() const {
if (isInt()) {
return payload.u.as_int;
} else if (isSymInt()) {
return toSymInt().guard_int(__FILE__, __LINE__);
} else {
TORCH_INTERNAL_ASSERT(0, "expected int");
}
}
// Bool
IValue(bool b) : tag(Tag::Bool) {
#if defined(__clang__) && defined(__x86_64__)
// Initializing entire payload stops valgrind's from reporting
// "jump or move depends on uninitialised value" in IValue copy constructor
// See https://github.com/pytorch/pytorch/issues/37117
payload.u.as_int = b;
#else
payload.u.as_bool = b;
#endif
}
bool isBool() const {
return Tag::Bool == tag;
}
bool toBool() const {
if (isBool()) {
return payload.u.as_bool;
} else if (isSymBool()) {
return toSymBool().guard_bool(__FILE__, __LINE__);
} else {
TORCH_INTERNAL_ASSERT(0, "expected bool");
}
}
// IntList
bool isIntList() const;
bool isSymIntList() const;
c10::List<int64_t> toIntList() &&;
c10::List<int64_t> toIntList() const&;
std::vector<int64_t> toIntVector() const;
std::vector<c10::SymInt> toSymIntVector() const;
at::DimVector toDimVector() const;
// ConstantString
IValue(c10::intrusive_ptr<ivalue::ConstantString> v);
IValue(std::string v);
IValue(const char* v) : IValue(std::string(v)) {}
IValue(std::string_view v) : IValue(std::string(v)){}
bool isString() const {
return Tag::String == tag;
}
c10::intrusive_ptr<ivalue::ConstantString> toString() &&;
c10::intrusive_ptr<ivalue::ConstantString> toString() const&;
const std::string& toStringRef() const;
std::optional<std::reference_wrapper<const std::string>> toOptionalStringRef()
const;
c10::string_view toStringView() const;
// DoubleList
bool isDoubleList() const;
c10::List<double> toDoubleList() &&;
c10::List<double> toDoubleList() const&;
std::vector<double> toDoubleVector() const;
// ComplexDoubleList
bool isComplexDoubleList() const;
c10::List<c10::complex<double>> toComplexDoubleList() &&;
c10::List<c10::complex<double>> toComplexDoubleList() const&;
std::vector<c10::complex<double>> toComplexDoubleVector() const;
// BoolList
bool isBoolList() const;
c10::List<bool> toBoolList() &&;
c10::List<bool> toBoolList() const&;
// TensorList
bool isTensorList() const;
c10::List<at::Tensor> toTensorList() &&;
c10::List<at::Tensor> toTensorList() const&;
std::vector<at::Tensor> toTensorVector() const;
// OptionalTensorList
bool isOptionalTensorList() const;
c10::List<std::optional<at::Tensor>> toOptionalTensorList() &&;
c10::List<std::optional<at::Tensor>> toOptionalTensorList() const&;
std::vector<std::optional<at::Tensor>> toOptionalTensorVector() const;
// GenericList
IValue(c10::List<IValue> v);
bool isList() const {
return Tag::GenericList == tag;
}
c10::List<IValue> toList() &&;
c10::List<IValue> toList() const&;
c10::ArrayRef<IValue> toListRef() const;
// Some template constructors of IValue calls another constructor recursively.
// This SFINAEs the called constructor exists.
template <class T>
using enable_if_ivalue_constructible =
std::enable_if_t<std::is_constructible_v<IValue, T>, std::nullptr_t>;
// The rule for lists is more complicated; the generic constructor is only
// acceptable if your element isn't SymInt. If you do have a SymInt element,
// then you must also, at construction time, check if you can decay the list
// into an int list (this is MANDATORY, as at a use site we may expect
// toIntList to work even if at the call site you had a SymIntArrayRef
// argument). In practice, only SymIntArrayRef is used this way, so we
// didn't bother making it work for the other constructors, we just make sure
// they're not selectable.
template <class T>
using enable_if_list_is_ivalue_constructible = std::enable_if_t<
std::is_constructible_v<IValue, T> && !std::is_same_v<T, c10::SymInt>,
std::nullptr_t>;
template <class T, enable_if_list_is_ivalue_constructible<T> = nullptr>
IValue(c10::List<T>&& v);
template <class T, enable_if_list_is_ivalue_constructible<T> = nullptr>
IValue(const c10::List<T>& v);
template <class T, enable_if_list_is_ivalue_constructible<T> = nullptr>
IValue(at::ArrayRef<T> v);
template <class T, enable_if_list_is_ivalue_constructible<T> = nullptr>
IValue(const std::vector<T>& v);
template <class T, enable_if_list_is_ivalue_constructible<T> = nullptr>
IValue(std::vector<T>&& v);
template <class T, size_t N>
IValue(std::array<T, N> v);
// Manual constructors for lists of symints, which decay to int list if
// possible. To avoid ambiguous overload situations, we template them
// to prevent implicit conversions
template <class T>
using enable_if_symint =
std::enable_if_t<std::is_same_v<T, c10::SymInt>, std::nullptr_t>;
template <class T, enable_if_symint<T> = nullptr>
IValue(at::ArrayRef<T> v);
template <class T, enable_if_symint<T> = nullptr>
IValue(at::OptionalArrayRef<T> v);
template <class T, enable_if_symint<T> = nullptr>
IValue(const std::vector<T>& v);
template <class T, enable_if_symint<T> = nullptr>
IValue(std::vector<T>&& v);
template <class T>
using enable_if_ilist_is_ivalue_constructible = std::enable_if_t<
std::is_constructible_v<IValue, T> &&
std::is_constructible_v<IValue, typename IListRef<T>::boxed_type> &&
!std::is_same_v<T, c10::SymInt>,
std::nullptr_t>;
template <class T, enable_if_ilist_is_ivalue_constructible<T> = nullptr>
IValue(c10::IListRef<T> v);
// GenericDict
IValue(c10::Dict<IValue, IValue> v);
bool isGenericDict() const {
return Tag::GenericDict == tag;
}
c10::Dict<IValue, IValue> toGenericDict() &&;
c10::Dict<IValue, IValue> toGenericDict() const&;
template <class Key, class Value>
IValue(c10::Dict<Key, Value> v);
template <class Key, class Value>
/// \cond
/// DOXYGEN_CANNOT_HANDLE_CONSTRUCTORS_WITH_MACROS_SO_EXCLUDE_THIS_LINE_FROM_DOXYGEN
C10_DEPRECATED_MESSAGE(
"IValues based on std::unordered_map<K, V> are slow and deprecated. Please use c10::Dict<K, V> instead.")
/// \endcond
IValue(std::unordered_map<Key, Value> v);
template <class T, enable_if_ivalue_constructible<T> = nullptr>
IValue(std::optional<T> v);
template <class T, enable_if_list_is_ivalue_constructible<T> = nullptr>
IValue(c10::OptionalArrayRef<T> v);
IValue(std::nullopt_t);
// ClassType
IValue(c10::intrusive_ptr<ivalue::Object> v);
bool isObject() const {
return tag == Tag::Object;
}
c10::intrusive_ptr<ivalue::Object> toObject() &&;
c10::intrusive_ptr<ivalue::Object> toObject() const&;
ivalue::Object& toObjectRef() const;
torch::jit::Module toModule() const;
bool isModule() const;
// PyObject
IValue(c10::intrusive_ptr<ivalue::PyObjectHolder> v);
bool isPyObject() const {
return tag == Tag::PyObject;
}
c10::intrusive_ptr<ivalue::PyObjectHolder> toPyObjectHolder() &&;
c10::intrusive_ptr<ivalue::PyObjectHolder> toPyObjectHolder() const&;
PyObject* toPyObject() const;
// Enum
explicit IValue(c10::intrusive_ptr<ivalue::EnumHolder> v);
bool isEnum() const {
return tag == Tag::Enum;
}
c10::intrusive_ptr<ivalue::EnumHolder> toEnumHolder() &&;
c10::intrusive_ptr<ivalue::EnumHolder> toEnumHolder() const&;
// None
IValue() = default;
bool isNone() const {
return Tag::None == tag;
}
std::string toNone() const {
AT_ASSERT(isNone());
return "None";
}
static IValue uninitialized() {
auto i = IValue();
i.tag = Tag::Uninitialized;
return i;
}
// Scalar, which gets encoded as either an Int, a Double or a ComplexDouble
IValue(const at::Scalar& s) : IValue() {
// NB: do the symbolic versions first, as isFloatingPoint is true
// for both SymFloat and double
if (s.isSymInt()) {
tag = Tag::SymInt;
payload.u.as_intrusive_ptr = s.toSymInt().toSymNode().release();
} else if (s.isSymFloat()) {
tag = Tag::SymFloat;
payload.u.as_intrusive_ptr = s.toSymFloat().toSymNodeImpl().release();
} else if (s.isSymBool()) {
tag = Tag::SymBool;
payload.u.as_intrusive_ptr = s.toSymBool().toSymNodeImpl().release();
} else if (s.isFloatingPoint()) {
tag = Tag::Double;
payload.u.as_double = s.toDouble();
} else if (s.isComplex()) {
*this = s.toComplexDouble();
} else if (s.isBoolean()) {
tag = Tag::Bool;
payload.u.as_bool = s.toBool();
} else {
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
s.isIntegral(false), "Unknown type in Scalar");
tag = Tag::Int;
payload.u.as_int = s.toLong();
}
}
bool isScalar() const {
return isDouble() || isInt() || isComplexDouble() || isBool() ||
isSymInt() || isSymFloat() || isSymBool();
}
at::Scalar toScalar() const {
if (isDouble())
return toDouble();
else if (isInt())
return toInt();
else if (isComplexDouble())
return toComplexDouble();
else if (isBool())
return toBool();
else if (isSymInt())
return toSymInt();
else if (isSymFloat())
return toSymFloat();
else if (isSymBool())
return toSymBool();
throw std::runtime_error("IValue is not a Scalar");
}
// Device
IValue(c10::Device d) : tag(Tag::Device) {
payload.u.as_device.type = d.type();
payload.u.as_device.index = d.index();
}
bool isDevice() const {
return Tag::Device == tag;
}
c10::Device toDevice() const {
AT_ASSERT(isDevice());
return c10::Device(payload.u.as_device.type, payload.u.as_device.index);
}
// Stream
IValue(c10::Stream s) : tag(Tag::Stream) {
auto v = c10::make_intrusive<ivalue::StreamData3Holder>(s.pack3());
payload.u.as_intrusive_ptr = v.release();
}
c10::Stream toStream() &&;
c10::Stream toStream() const&;
bool isStream() const {
return Tag::Stream == tag;
}
// ScalarType
IValue(ScalarType t)
: IValue(static_cast<std::underlying_type_t<ScalarType>>(t)) {}
at::ScalarType toScalarType() const {
return static_cast<at::ScalarType>(toInt());
}
// Layout
IValue(Layout l) : IValue(static_cast<std::underlying_type_t<Layout>>(l)) {}
at::Layout toLayout() const {
return static_cast<at::Layout>(toInt());
}
// MemoryFormat
IValue(MemoryFormat m)
: IValue(static_cast<std::underlying_type_t<MemoryFormat>>(m)) {}
at::MemoryFormat toMemoryFormat() const {
return static_cast<at::MemoryFormat>(toInt());
}
// QScheme
IValue(at::QScheme qscheme) : tag(Tag::Int) {
payload.u.as_int = static_cast<int64_t>(qscheme);
}
at::QScheme toQScheme() const {
return static_cast<at::QScheme>(toInt());
}
// Dimname
IValue(at::Dimname dimname) : IValue(dimname.symbol().toQualString()) {}
at::Dimname toDimname() const {
return at::Dimname::fromSymbol(Symbol::fromQualString(toStringRef()));
}
// Generator
IValue(at::Generator g) : tag(Tag::Generator) {
payload.u.as_intrusive_ptr =
null_to_undefined_tensor(g.unsafeReleaseGeneratorImpl());
}
bool isGenerator() const {
return Tag::Generator == tag;
}
at::Generator toGenerator() &&;
at::Generator toGenerator() const&;
// for debugging
std::string tagKind() const {
switch (tag) {
#define DEFINE_CASE(x) \
case Tag::x: \
return #x;
TORCH_FORALL_TAGS(DEFINE_CASE)
#undef DEFINE_CASE