forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ivalue_inl.h
2509 lines (2228 loc) · 83.6 KB
/
ivalue_inl.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 <condition_variable>
#include <memory>
#include <type_traits>
#include <utility>
#include <ATen/core/Dict.h>
#include <ATen/core/List.h>
#include <ATen/core/IListRef.h>
#include <ATen/core/functional.h>
#include <ATen/core/jit_type.h>
#include <ATen/core/qualified_name.h>
#include <ATen/core/rref_interface.h>
#include <ATen/core/symbol.h>
#include <c10/core/DeviceGuard.h>
#include <c10/core/Event.h>
#include <c10/core/Scalar.h>
#include <c10/core/Stream.h>
#include <c10/core/StreamGuard.h>
#include <c10/core/TensorImpl.h>
#include <c10/core/UndefinedTensorImpl.h>
#include <c10/core/impl/DeviceGuardImplInterface.h>
#include <c10/util/FunctionRef.h>
#include <c10/util/Logging.h>
#include <c10/util/hash.h>
#include <c10/util/intrusive_ptr.h>
#include <c10/util/irange.h>
namespace torch {
namespace jit {
struct Function;
struct CompilationUnit;
} // namespace jit
TORCH_API bool isCustomClass(const c10::IValue& v);
} // namespace torch
namespace c10 {
struct IValue;
struct ClassType;
struct TupleType;
struct EnumType;
struct InferredType;
// For custom class __init__ registration, we need to pass in a function
// that looks like this: [](IValue x, args...)
// However, make_boxed_from_unboxed_functor.h automatically sets the input types
// of the function by introspecting the types of the functor (which is IValue in
// this case). However, we need the type it binds to be Foo.
// Instead, we pass in a lambda [](ivalue_holder<CurClass> x, args...) from
// which getTypePtr can recover the original class pointer.
template <typename TaggedCapsuleType>
struct tagged_capsule {
IValue ivalue;
};
template <class T, class NullType>
c10::intrusive_ptr<T, NullType> IValue::moveToIntrusivePtr() {
auto t = c10::intrusive_ptr<T, NullType>::reclaim(
payload.u.as_intrusive_ptr == c10::UndefinedTensorImpl::singleton()
? NullType::singleton()
: static_cast<T*>(payload.u.as_intrusive_ptr));
clearToNone();
return t;
}
template <typename T, class NullType>
c10::intrusive_ptr<T, NullType> IValue::toIntrusivePtr() const {
if (payload.u.as_intrusive_ptr == c10::UndefinedTensorImpl::singleton()) {
return c10::intrusive_ptr<T, NullType>();
}
c10::raw::intrusive_ptr::incref(payload.u.as_intrusive_ptr);
return c10::intrusive_ptr<T, NullType>::reclaim(
static_cast<T*>(payload.u.as_intrusive_ptr));
}
template <class T, class U>
intrusive_ptr<T> static_intrusive_pointer_cast(intrusive_ptr<U> r) {
return intrusive_ptr<T>::reclaim(static_cast<T*>(r.release()));
}
template <class T, class U>
intrusive_ptr<T> dynamic_intrusive_pointer_cast(intrusive_ptr<U> r) {
return intrusive_ptr<T>::reclaim(dynamic_cast<T*>(r.release()));
}
inline c10::intrusive_ptr<ivalue::Future> IValue::toFuture() && {
AT_ASSERT(isFuture(), "Expected Future but got ", tagKind());
return moveToIntrusivePtr<ivalue::Future>();
}
inline c10::intrusive_ptr<ivalue::Future> IValue::toFuture() const& {
AT_ASSERT(isFuture(), "Expected Future but got ", tagKind());
return toIntrusivePtr<ivalue::Future>();
}
inline c10::intrusive_ptr<ivalue::Await> IValue::toAwait() && {
AT_ASSERT(isAwait(), "Expected Await but got ", tagKind());
return moveToIntrusivePtr<ivalue::Await>();
}
inline c10::intrusive_ptr<ivalue::Await> IValue::toAwait() const& {
AT_ASSERT(isAwait(), "Expected Await but got ", tagKind());
return toIntrusivePtr<ivalue::Await>();
}
inline c10::intrusive_ptr<c10::RRefInterface> IValue::toRRef() && {
AT_ASSERT(isRRef(), "Expected RRef but got ", tagKind());
return moveToIntrusivePtr<c10::RRefInterface>();
}
inline c10::intrusive_ptr<c10::RRefInterface> IValue::toRRef() const& {
AT_ASSERT(isRRef(), "Expected RRef but got ", tagKind());
return toIntrusivePtr<c10::RRefInterface>();
}
inline c10::intrusive_ptr<at::Quantizer> IValue::toQuantizer() && {
AT_ASSERT(isQuantizer(), "Expected Quantizer but got ", tagKind());
return moveToIntrusivePtr<at::Quantizer>();
}
inline c10::intrusive_ptr<at::Quantizer> IValue::toQuantizer() const& {
AT_ASSERT(isQuantizer(), "Expected Quantizer but got ", tagKind());
return toIntrusivePtr<at::Quantizer>();
}
inline c10::intrusive_ptr<ivalue::ConstantString> IValue::toString() && {
AT_ASSERT(isString(), "Expected String but got ", tagKind());
return moveToIntrusivePtr<ivalue::ConstantString>();
}
inline c10::intrusive_ptr<ivalue::ConstantString> IValue::toString() const& {
AT_ASSERT(isString(), "Expected String but got ", tagKind());
return toIntrusivePtr<ivalue::ConstantString>();
}
inline c10::intrusive_ptr<ivalue::Object> IValue::toObject() && {
AT_ASSERT(isObject(), "Expected Object but got ", tagKind());
return moveToIntrusivePtr<ivalue::Object>();
}
inline c10::intrusive_ptr<ivalue::Object> IValue::toObject() const& {
AT_ASSERT(isObject(), "Expected Object but got ", tagKind());
return toIntrusivePtr<ivalue::Object>();
}
inline c10::intrusive_ptr<ivalue::PyObjectHolder> IValue::
toPyObjectHolder() && {
TORCH_INTERNAL_ASSERT(isPyObject(), "Expected PyObject but got ", tagKind());
return moveToIntrusivePtr<ivalue::PyObjectHolder>();
}
inline c10::intrusive_ptr<ivalue::PyObjectHolder> IValue::toPyObjectHolder()
const& {
TORCH_INTERNAL_ASSERT(isPyObject(), "Expected PyObject but got ", tagKind());
return toIntrusivePtr<ivalue::PyObjectHolder>();
}
inline c10::intrusive_ptr<ivalue::EnumHolder> IValue::toEnumHolder() && {
TORCH_INTERNAL_ASSERT(isEnum(), "Expected Enum but got ", tagKind());
return moveToIntrusivePtr<ivalue::EnumHolder>();
}
inline c10::intrusive_ptr<ivalue::EnumHolder> IValue::toEnumHolder() const& {
TORCH_INTERNAL_ASSERT(isEnum(), "Expected Enum but got ", tagKind());
return toIntrusivePtr<ivalue::EnumHolder>();
}
inline c10::complex<double> IValue::toComplexDouble() const {
TORCH_INTERNAL_ASSERT(isComplexDouble(), "Expected ComplexDouble but got ", tagKind());
auto ptr = toIntrusivePtr<ivalue::ComplexHolder>();
return (*ptr).val;
}
inline at::Tensor IValue::toTensor() && {
if (C10_UNLIKELY(!isTensor())) {
reportToTensorTypeError();
}
auto result = 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();
clearToNone();
return result;
}
inline at::Tensor& IValue::toTensor() & {
if (C10_UNLIKELY(!isTensor())) {
reportToTensorTypeError();
}
return payload.as_tensor;
}
inline const at::Tensor& IValue::toTensor() const& {
if (C10_UNLIKELY(!isTensor())) {
reportToTensorTypeError();
}
return payload.as_tensor;
}
inline c10::Storage IValue::toStorage() && {
AT_ASSERT(isStorage(), "Expected Storage but got ", tagKind());
return c10::Storage(
moveToIntrusivePtr<at::StorageImpl>());
}
inline c10::Storage IValue::toStorage() const& {
AT_ASSERT(isStorage(), "Expected Storage but got ", tagKind());
return c10::Storage(toIntrusivePtr<at::StorageImpl>());
}
inline c10::Stream IValue::toStream() && {
AT_ASSERT(isStream(), "Expected Stream but got ", tagKind());
auto ptr = toIntrusivePtr<ivalue::StreamData3Holder>();
return c10::Stream::unpack3((*ptr).val.stream_id,
(*ptr).val.device_index,
(*ptr).val.device_type);
}
inline c10::Stream IValue::toStream() const& {
AT_ASSERT(isStream(), "Expected Stream but got ", tagKind());
auto ptr = toIntrusivePtr<ivalue::StreamData3Holder>();
return c10::Stream::unpack3((*ptr).val.stream_id,
(*ptr).val.device_index,
(*ptr).val.device_type);
}
inline c10::intrusive_ptr<caffe2::Blob> IValue::toBlob() && {
AT_ASSERT(isBlob(), "Expected Blob but got ", tagKind());
return moveToIntrusivePtr<caffe2::Blob>();
}
inline c10::intrusive_ptr<caffe2::Blob> IValue::toBlob() const& {
AT_ASSERT(isBlob(), "Expected Blob but got ", tagKind());
return toIntrusivePtr<caffe2::Blob>();
;
}
inline c10::intrusive_ptr<torch::CustomClassHolder> IValue::toCapsule() && {
TORCH_INTERNAL_ASSERT(isCapsule());
return moveToIntrusivePtr<torch::CustomClassHolder>();
}
inline c10::intrusive_ptr<torch::CustomClassHolder> IValue::toCapsule() const& {
TORCH_INTERNAL_ASSERT(isCapsule());
return toIntrusivePtr<torch::CustomClassHolder>();
}
inline at::Generator IValue::toGenerator() && {
AT_ASSERT(isGenerator(), "Expected Generator but got ", tagKind());
return at::Generator(moveToIntrusivePtr<at::GeneratorImpl>());
}
inline at::Generator IValue::toGenerator() const& {
AT_ASSERT(isGenerator(), "Expected Generator but got ", tagKind());
return at::Generator(toIntrusivePtr<at::GeneratorImpl>());
}
inline c10::SymInt IValue::toSymInt() && {
AT_ASSERT(isSymInt() || isInt(), "Expected SymInt or int but got ", tagKind());
if (isSymInt()) {
return c10::SymInt(moveToIntrusivePtr<c10::SymNodeImpl>());
} else {
return c10::SymInt(payload.u.as_int);
}
}
inline c10::SymInt IValue::toSymInt() const& {
AT_ASSERT(isSymInt() || isInt(), "Expected SymInt or int but got ", tagKind());
if (isSymInt()) {
return c10::SymInt(toIntrusivePtr<c10::SymNodeImpl>());
} else {
return c10::SymInt(payload.u.as_int);
}
}
inline c10::SymFloat IValue::toSymFloat() && {
AT_ASSERT(isSymFloat() || isDouble(), "Expected SymFloat or double but got ", tagKind());
if (isSymFloat()) {
return c10::SymFloat(moveToIntrusivePtr<c10::SymNodeImpl>());
} else {
return c10::SymFloat(payload.u.as_double);
}
}
inline c10::SymFloat IValue::toSymFloat() const& {
AT_ASSERT(isSymFloat() || isDouble(), "Expected SymFloat or double but got ", tagKind());
if (isSymFloat()) {
return c10::SymFloat(toIntrusivePtr<c10::SymNodeImpl>());
} else {
return c10::SymFloat(payload.u.as_double);
}
}
inline c10::SymBool IValue::toSymBool() && {
AT_ASSERT(isSymBool() || isBool(), "Expected SymBool or boolean but got ", tagKind());
if (isSymBool()) {
return c10::SymBool(moveToIntrusivePtr<c10::SymNodeImpl>());
} else {
return c10::SymBool(payload.u.as_bool);
}
}
inline c10::SymBool IValue::toSymBool() const& {
AT_ASSERT(isSymBool() || isBool(), "Expected SymBool or boolean but got ", tagKind());
if (isSymBool()) {
return c10::SymBool(toIntrusivePtr<c10::SymNodeImpl>());
} else {
return c10::SymBool(payload.u.as_bool);
}
}
namespace ivalue {
void TORCH_API
checkCustomClassType(const ClassType* expected_type, const Type* actual_type);
template <typename T>
using Shared = c10::intrusive_ptr<T>;
// string
struct TORCH_API ConstantString final : c10::intrusive_ptr_target {
private:
const std::string str_;
public:
ConstantString(std::string str) : str_(std::move(str)) {}
ConstantString(c10::string_view str) : str_(std::string(str)) {}
static c10::intrusive_ptr<ConstantString> create(std::string str_);
static c10::intrusive_ptr<ConstantString> create(c10::string_view str_);
static c10::intrusive_ptr<ConstantString> create(const char* str_);
const std::string& string() const {
return str_;
}
c10::string_view string_view() const {
return str_;
}
operator const std::string&() const {
return string();
}
TORCH_API friend std::ostream& operator<<(
std::ostream& out,
const ConstantString& v);
};
struct Future;
struct TORCH_API TupleElements {
private:
size_t inlineSize_;
// We represent TupleElements this way to save doing a heap
// allocation in the common (at least for unpickling) case where we
// have only 3 elements. We have our own union instead of
// c10::SmallVector<IValue> because c10::SmallVector<IValue> always
// stores the begin/end/capacity pointers, which would be a waste of
// space in our use case.
union {
std::vector<IValue> elementsVector_;
// Don't want to declare a std::array because the convenient
// iteration and size members are a footgun in this case -- the
// actual size of the array may be smaller than 3!
// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays)
IValue elementsInline_[3];
};
void destroyInline() {
for (const auto ii : c10::irange(inlineSize_)) {
elementsInline_[ii].~IValue();
}
}
public:
using iterator = IValue*;
using const_iterator = const IValue*;
TupleElements() : inlineSize_(0) {
new (&elementsVector_) std::vector<IValue>();
}
explicit TupleElements(std::vector<IValue> elements)
: inlineSize_(0), elementsVector_(std::move(elements)) {}
explicit TupleElements(c10::ArrayRef<IValue> elements)
: inlineSize_(elements.size() <= 3 ? elements.size() : 0) {
switch (inlineSize_) {
case 3:
new (&elementsInline_[2]) IValue(elements[2]);
C10_FALLTHROUGH;
case 2:
new (&elementsInline_[1]) IValue(elements[1]);
C10_FALLTHROUGH;
case 1:
new (&elementsInline_[0]) IValue(elements[0]);
break;
case 0:
new (&elementsVector_) std::vector<IValue>(elements.begin(), elements.end());
break;
}
}
explicit TupleElements(IValue&& e1)
: inlineSize_(1) {
new (&elementsInline_[0]) IValue(std::move(e1));
}
explicit TupleElements(IValue&& e1, IValue&& e2)
: inlineSize_(2) {
new (&elementsInline_[0]) IValue(std::move(e1));
new (&elementsInline_[1]) IValue(std::move(e2));
}
explicit TupleElements(IValue&& e1, IValue&& e2, IValue&& e3)
: inlineSize_(3) {
new (&elementsInline_[0]) IValue(std::move(e1));
new (&elementsInline_[1]) IValue(std::move(e2));
new (&elementsInline_[2]) IValue(std::move(e3));
}
~TupleElements() {
if (inlineSize_) {
destroyInline();
} else {
elementsVector_.~vector();
}
}
// It would be nice to make this noncopyable to prevent people from
// writing code like `auto output =
// forward(...).toTupleRef().elements()` (which does refcount bumps on
// each element, unlike the more efficient but verbose
// ```
// auto outputIntrusivePtr = forward(...).toTuple();
// const auto& output = outputIntrusivePtr->elements();
// ```
// ), but there is simply an overwhelming amount of code that does
// it the inefficient way.
// See also operator std::vector below.
TupleElements(const TupleElements& rhs)
: inlineSize_(rhs.inlineSize_) {
if (rhs.inlineSize_) {
for (const auto ii : c10::irange(inlineSize_)) {
new (&elementsInline_[ii]) IValue(rhs.elementsInline_[ii]);
}
} else {
new (&elementsVector_) std::vector<IValue>(rhs.elementsVector_);
}
}
TupleElements& operator=(const TupleElements& rhs) {
if (inlineSize_) {
if (rhs.inlineSize_) {
for (const auto ii : c10::irange(std::min(inlineSize_, rhs.inlineSize_))) {
elementsInline_[ii] = rhs.elementsInline_[ii];
}
if (rhs.inlineSize_ > inlineSize_) {
for (const auto ii : c10::irange(inlineSize_, rhs.inlineSize_)) {
new (&elementsInline_[ii]) IValue(rhs.elementsInline_[ii]);
}
} else {
for (const auto ii : c10::irange(rhs.inlineSize_, inlineSize_)) {
elementsInline_[ii].~IValue();
}
}
} else {
destroyInline();
new (&elementsVector_) std::vector<IValue>(rhs.elementsVector_);
}
} else {
if (rhs.inlineSize_) {
elementsVector_.~vector();
for (const auto ii : c10::irange(rhs.inlineSize_)) {
new (&elementsInline_[ii]) IValue(rhs.elementsInline_[ii]);
}
} else {
elementsVector_ = rhs.elementsVector_;
}
}
inlineSize_ = rhs.inlineSize_;
return *this;
}
TupleElements(TupleElements&& rhs) noexcept
: inlineSize_(rhs.inlineSize_) {
if (inlineSize_) {
for (const auto ii : c10::irange(inlineSize_)) {
new (&elementsInline_[ii]) IValue(std::move(rhs.elementsInline_[ii]));
}
} else {
new (&elementsVector_) std::vector<IValue>(std::move(rhs.elementsVector_));
}
}
TupleElements& operator=(TupleElements&& rhs) noexcept {
if (inlineSize_) {
if (rhs.inlineSize_) {
for (const auto ii : c10::irange(std::min(inlineSize_, rhs.inlineSize_))) {
elementsInline_[ii] = std::move(rhs.elementsInline_[ii]);
}
if (rhs.inlineSize_ > inlineSize_) {
for (const auto ii : c10::irange(inlineSize_, rhs.inlineSize_)) {
new (&elementsInline_[ii]) IValue(std::move(rhs.elementsInline_[ii]));
}
} else {
for (const auto ii : c10::irange(rhs.inlineSize_, inlineSize_)) {
elementsInline_[ii].~IValue();
}
}
} else {
destroyInline();
new (&elementsVector_) std::vector<IValue>(std::move(rhs.elementsVector_));
}
} else {
if (rhs.inlineSize_) {
elementsVector_.~vector();
for (const auto ii : c10::irange(rhs.inlineSize_)) {
new (&elementsInline_[ii]) IValue(std::move(rhs.elementsInline_[ii]));
}
} else {
elementsVector_ = std::move(rhs.elementsVector_);
}
}
inlineSize_ = rhs.inlineSize_;
return *this;
}
C10_NODISCARD c10::ArrayRef<IValue> asArrayRef() const {
if (inlineSize_) {
return c10::ArrayRef<IValue>(elementsInline_, inlineSize_);
} else {
return elementsVector_;
}
}
// Mimic implicit conversion from std::vector to ArrayRef.
operator c10::ArrayRef<IValue>() const {
return asArrayRef();
}
static size_t hash(const TupleElements& v) {
return c10::hash<c10::ArrayRef<IValue>>()(v.asArrayRef());
}
void setContents(std::vector<IValue>&& contents) {
if (inlineSize_) {
destroyInline();
new (&elementsVector_) std::vector<IValue>(std::move(contents));
inlineSize_ = 0;
} else {
elementsVector_ = std::move(contents);
}
}
C10_NODISCARD bool empty() const {
return inlineSize_ ? false : elementsVector_.empty();
}
C10_NODISCARD size_t size() const {
return inlineSize_ ? inlineSize_ : elementsVector_.size();
}
C10_NODISCARD IValue& operator[](size_t idx) {
if (inlineSize_) {
return elementsInline_[idx];
} else {
return elementsVector_[idx];
}
}
C10_NODISCARD const IValue& operator[](size_t idx) const {
if (inlineSize_) {
return elementsInline_[idx];
} else {
return elementsVector_[idx];
}
}
C10_NODISCARD IValue& at(size_t idx) {
if (inlineSize_) {
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(inlineSize_ <= 3);
TORCH_CHECK(idx < inlineSize_, "TupleElements: invalid index Index = ", idx, "; Length = ", inlineSize_);
return elementsInline_[idx];
} else {
return elementsVector_.at(idx);
}
}
C10_NODISCARD const IValue& at(size_t idx) const {
if (inlineSize_) {
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(inlineSize_ <= 3);
TORCH_CHECK(idx < inlineSize_, "TupleElements: invalid index Index = ", idx, "; Length = ", inlineSize_);
return elementsInline_[idx];
} else {
TORCH_CHECK(idx < elementsVector_.size(), "TupleElements: invalid index Index = ", idx, "; Length = ", elementsVector_.size());
return elementsVector_.at(idx);
}
}
C10_NODISCARD iterator begin() {
if (inlineSize_) {
return elementsInline_;
} else {
return elementsVector_.data();
}
}
C10_NODISCARD iterator end() {
if (inlineSize_) {
return elementsInline_ + inlineSize_;
} else {
return elementsVector_.data() + elementsVector_.size();
}
}
C10_NODISCARD const_iterator begin() const {
if (inlineSize_) {
return elementsInline_;
} else {
return elementsVector_.data();
}
}
C10_NODISCARD const_iterator end() const {
if (inlineSize_) {
return elementsInline_ + inlineSize_;
} else {
return elementsVector_.data() + elementsVector_.size();
}
}
C10_NODISCARD const_iterator cbegin() const {
return begin();
}
C10_NODISCARD const_iterator cend() const {
return end();
}
C10_NODISCARD std::vector<IValue> vec() const & {
return asArrayRef().vec();
}
C10_NODISCARD IValue& back() {
return *(end() - 1);
}
C10_NODISCARD const IValue& back() const {
return *(end() - 1);
}
C10_NODISCARD std::vector<IValue> vec() && {
std::vector<IValue> result;
result.reserve(size());
for (auto&& iv : *this) {
result.push_back(std::move(iv));
}
return result;
}
// More compatibility shims for the overwhelming amount of code that
// likes to copy tuple elements into a vector; see comment above the
// copy constructor.
operator std::vector<IValue>() const & {
return vec();
}
operator std::vector<IValue>() && {
return vec();
}
};
template <typename T>
struct TupleTypeFactory {};
template <>
struct TORCH_API TupleTypeFactory<TupleType> {
static TupleTypePtr create(std::vector<TypePtr> types) {
return TupleType::create(std::move(types));
}
static TupleTypePtr fallback(const Type& type);
};
template <>
struct TORCH_API TupleTypeFactory<c10::DynamicType> {
static DynamicTypePtr create(std::vector<TypePtr> elemTypes);
static DynamicTypePtr fallback(const Type&);
};
struct TORCH_API Tuple : c10::intrusive_ptr_target {
private:
TupleElements elements_;
mutable c10::TypePtr type_; // lazily computed for unnamed tuples
public:
// named tuples have additional type information, so we
// directly create them tagged
static c10::intrusive_ptr<Tuple> createNamed(
std::vector<IValue> elements_,
c10::TypePtr type_) {
return c10::make_intrusive<Tuple>(std::move(elements_), std::move(type_));
}
static c10::intrusive_ptr<Tuple> createNamed(
TupleElements elements_,
std::shared_ptr<TupleType> type_) {
return c10::make_intrusive<Tuple>(std::move(elements_), std::move(type_));
}
static c10::intrusive_ptr<Tuple> createNamed(
std::initializer_list<IValue> elements_,
std::shared_ptr<TupleType> type_) {
return createNamed(TupleElements(c10::ArrayRef<IValue>(elements_)), std::move(type_));
}
// MSVC apparently can't disambiguate the other two overloads of
// create when passed an initializer_list without this.
static c10::intrusive_ptr<Tuple> create(std::initializer_list<IValue> elements_) {
return create(c10::ArrayRef<IValue>(elements_));
}
static c10::intrusive_ptr<Tuple> create(std::vector<IValue> elements_) {
return c10::make_intrusive<Tuple>(std::move(elements_));
}
static c10::intrusive_ptr<Tuple> create(TupleElements elements_) {
return c10::make_intrusive<Tuple>(std::move(elements_));
}
static c10::intrusive_ptr<Tuple> create(c10::ArrayRef<IValue> elements_) {
return create(TupleElements(elements_));
}
static c10::intrusive_ptr<Tuple> create(IValue e1) {
return c10::make_intrusive<Tuple>(std::move(e1));
}
static c10::intrusive_ptr<Tuple> create(IValue e1, IValue e2) {
return c10::make_intrusive<Tuple>(std::move(e1), std::move(e2));
}
static c10::intrusive_ptr<Tuple> create(IValue e1, IValue e2, IValue e3) {
return c10::make_intrusive<Tuple>(std::move(e1), std::move(e2), std::move(e3));
}
private:
// Workaround inability to use `>` operator in template argument list.
template <typename... Args>
static constexpr bool hasMoreThanThreeArgs() {
return sizeof...(Args) > 3;
}
public:
template <typename... Args>
static c10::intrusive_ptr<Tuple> create(Args&&... elements_) {
switch (sizeof...(Args)) {
case 1:
case 2:
case 3:
return create(IValue(std::forward<Args>(elements_))...);
default:
return create(
std::vector<IValue>{IValue(std::forward<Args>(elements_))...});
}
}
// Again, it would be nice to make this noncopyable, but there's a
// lot of extant code that copies Tuples.
// Tuple(const Tuple& rhs) = delete;
const TupleElements& elements() const& {
return elements_;
}
TupleElements elements() && {
return std::move(elements_);
}
void setElements(std::vector<IValue>&& elements) {
elements_.setContents(std::move(elements));
}
void setElements(TupleElements&& elements) {
elements_ = std::move(elements);
}
void unsafeSetElement(size_t idx, const IValue& element) {
elements_[idx] = element;
}
void unsafeSetElement(size_t idx, IValue&& element) {
elements_[idx] = std::move(element);
}
size_t size() const {
return elements_.size();
}
template <typename T = c10::TupleType>
std::shared_ptr<T> type() const {
if (!type_) {
type_ = TupleTypeFactory<T>::create(fmap(elements(), [&](const IValue& v) {
return v.type<typename T::ElementType>();
}));
}
if (auto t = type_->cast<T>()) {
return t;
}
return TupleTypeFactory<T>::fallback(*type_);
}
static size_t hash(const Tuple& t) {
return c10::get_hash(t.elements());
}
TORCH_API friend bool operator==(
const ivalue::Tuple& lhs,
const ivalue::Tuple& rhs);
private:
// NOTE: If we try to avoid the overloads without
// `std::shared_ptr<TupleType> type` by defaulting it to nullptr, we
// end up having to call (part of) the shared_ptr destructor for
// `type` even though we should know statically it won't do
// anything.
explicit Tuple(std::vector<IValue> elements)
: elements_(std::move(elements)){}
explicit Tuple(std::vector<IValue> elements, c10::TypePtr type)
: elements_(std::move(elements)), type_(std::move(type)) {}
explicit Tuple(TupleElements&& elements)
: elements_(std::move(elements)) {}
explicit Tuple(TupleElements&& elements, std::shared_ptr<TupleType> type)
: elements_(std::move(elements)), type_(std::move(type)) {}
explicit Tuple(IValue&& e1)
: elements_(std::move(e1)) {}
explicit Tuple(IValue&& e1, std::shared_ptr<TupleType> type)
: elements_(std::move(e1)), type_(std::move(type)) {}
explicit Tuple(IValue&& e1, IValue&& e2)
: elements_(std::move(e1), std::move(e2)) {}
explicit Tuple(IValue&& e1, IValue&& e2, std::shared_ptr<TupleType> type)
: elements_(std::move(e1), std::move(e2)), type_(std::move(type)) {}
explicit Tuple(IValue&& e1, IValue&& e2, IValue&& e3)
: elements_(std::move(e1), std::move(e2), std::move(e3)) {}
explicit Tuple(IValue&& e1, IValue&& e2, IValue&& e3, std::shared_ptr<TupleType> type)
: elements_(std::move(e1), std::move(e2), std::move(e3)), type_(std::move(type)) {}
friend class c10::intrusive_ptr<Tuple>;
};
struct Object;
struct PyObjectHolder;
struct EnumHolder;
} // namespace ivalue
// Future
struct C10_EXPORT ivalue::Future final : c10::intrusive_ptr_target {
private:
// Keep this private in order to force users to go through make_intrusive and
// thus prevent creating a Future that's not held by an intrusive_ptr.
explicit Future(TypePtr type, std::vector<c10::Device> devices={})
: type_(std::move(type)),
impl_(getTypeOfDevices(devices)),
devices_(sortAndDeduplicateDevices(impl_, std::move(devices))) {}
friend c10::intrusive_ptr<Future>;
struct FutureCallback {
std::function<void(Future&)> callback;
bool uses_future; // whether the Future& passed in is actually used
template <typename T>
FutureCallback(T callback, bool uses_future)
: callback(std::move(callback)), uses_future(uses_future) {}
};
public:
Future(const Future&) = delete;
Future(Future&&) = delete;
Future& operator=(const Future&) = delete;
Future& operator=(Future&&) = delete;
struct TORCH_API FutureError final : public std::exception {
explicit FutureError(std::string&& error_msg_)
: error_msg(std::move(error_msg_)) {}
FutureError() = default;
const char* what() const noexcept override {
return error_msg.c_str();
}
std::string error_msg;
};
/**
* Wait on the future until it completes.
*/
void wait() {
std::unique_lock<std::mutex> lock(mutex_);
finished_cv_.wait(lock, [&]() -> bool { return completed_; });
synchronizeWithCurrentStreams();
}
/**
* Wait on the future until it completes and throw an
* exception if an error exists.
*/
void waitAndThrow() {
wait();
if (eptr_) {
std::rethrow_exception(eptr_);
}
}
/**
* Explicitly mark the future as completed with the output value. Optionally,
* the storages for all tensors in IValue can be passed as well. The DataPtrs
* of these storages are used to synchronize CUDA streams. If storages isn't
* given we will attempt to extract it from the value, if we need to (this
* happens if a non-empty set of devices was given to the constructor). Thus
* one only needs to provide storages when 1) they cannot be extracted through
* IValue::getSubValues() or through pickling in case of Python object; or
* when 2) customized storage extraction is more efficient.
*/
using WeakStorage = c10::weak_intrusive_ptr<c10::StorageImpl>;
void markCompleted(
IValue value,
c10::optional<std::vector<WeakStorage>> storages = c10::nullopt) {
// Start by performing all steps that can throw, before setting any field.
// Do this before even acquiring the mutex, because extractStorages might
// acquire the GIL, which could lead to a lock inversion with our mutex.
// See https://github.com/pytorch/pytorch/issues/58239.
std::vector<WeakStorage> actualStorages;
std::vector<c10::Device> usedDevices;
try {
// FIXME We should always extract DataPtrs, in order to catch the case of
// users using CUDA values but forgetting to set devices, which currently
// leads to a silent synchronization/correctness issue. However, as this
// might worsen perf in CPU-only cases, we should only do so after careful
// benchmarks.
if (impl_.type() != c10::kCPU) {
actualStorages =
storages.has_value() ? std::move(*storages) : extractStorages(value);
usedDevices = getDevicesOfStorages(impl_, actualStorages);
ensureIsSubsetOfDevices(usedDevices, devices_);
}
} catch (const std::exception&) {
setError(std::current_exception());
return;
}
std::unique_lock<std::mutex> lock(mutex_);
TORCH_CHECK(
!completed(),
"Attempting to mark a completed Future as complete again. Note that "
"a Future can only be marked completed once.");
// Only set value_ and completed_ flag once all checks and preparation steps
// have returned successfully to allow for proper error propagation.
value_ = std::move(value);
completed_ = true;
currentDevice_ = impl_.getDevice();
storages_ = std::move(actualStorages);
for (const c10::Device& device : usedDevices) {
c10::Event event(impl_.type());
event.record(impl_.getStream(device));
events_.push_back(std::move(event));
}
std::vector<FutureCallback> cbs;
cbs.swap(callbacks_);
lock.unlock();
finished_cv_.notify_all();
for (auto& callback : cbs) {
invokeCallback(std::move(callback.callback), callback.uses_future);
}
}
void markCompleted() {
markCompleted(IValue{});
}
void setError(std::exception_ptr eptr) {
std::unique_lock<std::mutex> lock(mutex_);
setErrorInternal(std::move(eptr), lock);
}
void setErrorIfNeeded(std::exception_ptr eptr) {
std::unique_lock<std::mutex> lock(mutex_);
if (completed_) {
// This should be rare and shouldn't cause log spew. Its important to
// log errors and thats why we have this log here.
std::string msg = c10::str(
"Skipping setting following error on the Future since "
"it is already marked completed (this is not necessarily "
"an error):\n",
tryRetrieveErrorMessageInternal(std::move(eptr)));
if (eptr_) {
msg += c10::str(
", \nOriginal exception:\n",
tryRetrieveErrorMessageInternal(eptr_));
}
LOG(INFO) << msg;
return;
} else {
setErrorInternal(std::move(eptr), lock);
}
}
// Get the result of the current future.
IValue value() {
std::unique_lock<std::mutex> lock(mutex_);
AT_ASSERT(completed());
if (eptr_) {
std::rethrow_exception(eptr_);