forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathivalue_inl.h
1294 lines (1146 loc) · 42.4 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 <type_traits>
#include <ATen/core/Dict.h>
#include <ATen/core/List.h>
#include <ATen/core/functional.h>
#include <ATen/core/interned_strings.h>
#include <ATen/core/qualified_name.h>
#include <ATen/core/rref_interface.h>
#include <c10/core/Scalar.h>
#include <c10/core/Stream.h>
#include <c10/core/TensorImpl.h>
#include <c10/core/UndefinedTensorImpl.h>
#include <c10/util/intrusive_ptr.h>
#include <c10/util/hash.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(
static_cast<T*>(payload.as_intrusive_ptr));
clearToNone();
return t;
}
template <typename T, class NullType>
c10::intrusive_ptr<T, NullType> IValue::toIntrusivePtr() const {
auto r = c10::intrusive_ptr<T, NullType>::reclaim(
static_cast<T*>(payload.as_intrusive_ptr));
auto p = r;
r.release();
return p;
}
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<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 at::Tensor IValue::toTensor() && {
AT_ASSERT(isTensor(), "Expected Tensor but got ", tagKind());
return at::Tensor(
moveToIntrusivePtr<at::TensorImpl, at::UndefinedTensorImpl>());
}
inline at::Tensor IValue::toTensor() const& {
AT_ASSERT(isTensor(), "Expected Tensor but got ", tagKind());
return at::Tensor(toIntrusivePtr<at::TensorImpl, at::UndefinedTensorImpl>());
}
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() && {
return c10::Stream::unpack(payload.as_int);
}
inline c10::Stream IValue::toStream() const& {
return c10::Stream::unpack(payload.as_int);
}
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>());
}
namespace ivalue {
void TORCH_API
checkCustomClassType(const Type* 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)) {}
static c10::intrusive_ptr<ConstantString> create(std::string str_);
const std::string& string() 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 Tuple : c10::intrusive_ptr_target {
private:
std::vector<IValue> elements_;
mutable std::shared_ptr<TupleType>
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_,
std::shared_ptr<TupleType> type_) {
return c10::make_intrusive<Tuple>(std::move(elements_), type_);
}
static c10::intrusive_ptr<Tuple> create(std::vector<IValue> elements_) {
return c10::make_intrusive<Tuple>(std::move(elements_));
}
template <typename... Args>
static c10::intrusive_ptr<Tuple> create(Args... elements_) {
return c10::make_intrusive<Tuple>(
std::vector<IValue>{IValue(elements_)...});
}
const std::vector<IValue>& elements() const& {
return elements_;
}
operator const std::vector<IValue>&() const {
return elements();
}
std::vector<IValue>& elements() & {
return elements_;
}
operator std::vector<IValue>&() {
return elements();
}
std::vector<IValue>&& elements() && {
return std::move(elements_);
}
std::shared_ptr<TupleType> type() const;
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:
Tuple(std::vector<IValue> elements, std::shared_ptr<TupleType> type = nullptr)
: elements_(std::move(elements)), type_(std::move(type)) {}
friend class c10::intrusive_ptr<Tuple>;
};
struct Object;
struct PyObjectHolder;
struct EnumHolder;
} // namespace ivalue
// Future
struct C10_EXPORT ivalue::Future : c10::intrusive_ptr_target {
private:
c10::intrusive_ptr<Future> intrusive_from_this() {
c10::raw::intrusive_ptr::incref(this); // we are creating a new pointer
// from a raw `this` pointer
// so we need to bump the refcount
// to account for this ownership
return c10::intrusive_ptr<Future>::reclaim(this);
}
public:
explicit Future(TypePtr type) : type_(type) {}
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_);
while (!completed_) {
finished_cv_.wait(lock);
}
if (!eptr_) {
postWaitHook(value_);
}
}
/**
* Wait on the future until it completes and throw an
* exception if an error exists.
*/
void waitAndThrow() {
std::unique_lock<std::mutex> lock(mutex_);
while (!completed_) {
finished_cv_.wait(lock);
}
if (eptr_) {
std::rethrow_exception(eptr_);
}
postWaitHook(value_);
}
/**
* Explicitly mark the future as completed with the output value.
*/
void markCompleted(IValue value) {
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.");
completed_ = true;
value_ = std::move(value);
postMarkCompletedHook(value_);
std::vector<std::function<void(void)>> cbs;
cbs.swap(callbacks_);
lock.unlock();
finished_cv_.notify_all();
for (auto& callback : cbs) {
callback();
}
}
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.
LOG(INFO)
<< "Skipping setting following error on the Future since "
<< "it is already marked completed (this is not neccessarily an error): "
<< tryRetrieveErrorMessageInternal(eptr);
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_);
}
return value_;
}
// This accessor should only be used if we know that the future is
// completed() with no error.
const IValue& constValue() {
std::unique_lock<std::mutex> lock(mutex_);
AT_ASSERT(completed());
AT_ASSERT(!eptr_);
return value_;
}
/**
* Add a callback to the future.
* The callbacks will be executed once the future completes.
* If the future has already completed,
* this function will execute the callback immediately.
*/
void addCallback(std::function<void(void)> callback) {
std::unique_lock<std::mutex> lock(mutex_);
callback = wrapCallback(std::move(callback));
if (completed()) {
lock.unlock();
callback();
return;
}
callbacks_.emplace_back(std::move(callback));
}
/**
* Add a callback to the future, and return another Future to hold the return
* value of the callback. This is necessary when the callback provider needs
* to know for sure when the callback has finished.
*/
c10::intrusive_ptr<Future> then(
std::function<IValue(void)> callback,
TypePtr type) {
auto fut = createInstance(std::move(type));
addCallback(
[fut, cb = std::move(callback)]() {
try {
fut->markCompleted(cb());
} catch (std::exception&) {
fut->setError(std::current_exception());
}
});
return fut;
}
// Tries to retrieve the error message from std::exception_ptr.
std::string tryRetrieveErrorMessage() {
TORCH_CHECK(hasError(), "No error present on the future.");
std::unique_lock<std::mutex> lock(mutex_);
return tryRetrieveErrorMessageInternal(eptr_);
}
// Check if the current future has completed
bool completed() const {
return completed_;
}
bool hasValue() const {
std::unique_lock<std::mutex> lock(mutex_);
return completed_ && !eptr_;
}
bool hasError() const {
std::unique_lock<std::mutex> lock(mutex_);
return eptr_ ? true : false;
}
std::exception_ptr exception_ptr() const {
std::unique_lock<std::mutex> lock(mutex_);
return eptr_;
}
TORCH_API friend std::ostream& operator<<(
std::ostream& out,
const Future& v);
TypePtr elementType() const {
return type_;
}
protected:
// This hook is called by this class's then() method when it prepares the
// instance it returns to the caller. It should be overridden by subclasses so
// that they can produce an instace of their own type.
virtual c10::intrusive_ptr<Future> createInstance(at::TypePtr type) {
return c10::make_intrusive<Future>(type);
}
// This hook will be called by this class (the superclass) when the future is
// marked completed _with a value_ (hence not in case of error). This is done
// right away, while the mutex is still held, before any callbacks are run.
// It allows subclasses to further update their state if they so need. For
// example the CUDAFuture subclass uses it to determine what devices the value
// resides on and record an event in those devices' current streams.
virtual void postMarkCompletedHook(const at::IValue& value) {}
// This hook will be called by the addCallback() and the then() methods before
// storing the callback for later execution (or before running it inline if
// the future is already complete). Note that this method could thus be called
// while the future is _not_ yet complete. By default this method does nothing
// but subclasses can override this method to add functionality. For example
// the CUDAFuture subclass ensures the callback runs with CUDA streams which
// are synchronized with the events recorded in the I/O streams.
virtual std::function<void(void)> wrapCallback(
std::function<void(void)> callback) {
return callback;
}
// This hook will be called by this class after a user thread has completed
// waiting on a successful future. It will thus not be called if the future
// completes with an error. It will also not be called if the user accesses
// the future's value without synchronization. Subclasses can override this
// to add some synchronization to the wait. For example, the CUDAFuture
// subclass ensures the user's current CUDA streams synchronize with the I/O
// events stored by the future.
virtual void postWaitHook(const at::IValue& value) {}
private:
void setErrorInternal(
std::exception_ptr eptr,
std::unique_lock<std::mutex>& lock) {
AT_ASSERT(!completed());
completed_ = true;
eptr_ = std::move(eptr);
// Do not call postMarkCompletedHook() here as there isn't any value.
std::vector<std::function<void(void)>> cbs;
cbs.swap(callbacks_);
lock.unlock();
finished_cv_.notify_all();
for (auto& callback : cbs) {
callback();
}
}
// Tries to retrieve the error message from std::exception_ptr.
std::string tryRetrieveErrorMessageInternal(std::exception_ptr eptr) {
try {
std::rethrow_exception(eptr);
} catch (const std::exception& e) {
return e.what();
} catch (...) {
return "Unknown Exception Type";
}
}
mutable std::mutex mutex_;
std::atomic_bool completed_ = {false}; // is this future complete
std::condition_variable finished_cv_;
IValue value_; // when finished the value
TypePtr type_;
std::vector<std::function<void(void)>> callbacks_;
std::exception_ptr eptr_;
};
// Input is a list of Futures with the same target type.
// Output is a Future to the List of completed Futures.
TORCH_API intrusive_ptr<ivalue::Future> collectAll(
c10::List<c10::intrusive_ptr<ivalue::Future>> srcs);
// Input is a List of Futures with the same target type.
// Output is a Future that will be updated with a seen value.
TORCH_API intrusive_ptr<ivalue::Future> collectAny(
c10::List<c10::intrusive_ptr<ivalue::Future>> srcs);
// User-defined object.
struct C10_EXPORT ivalue::Object final : c10::intrusive_ptr_target {
public:
Object(StrongTypePtr type, size_t numSlots) : type_(std::move(type)) {
slots_.resize(numSlots);
}
static c10::intrusive_ptr<Object> create(
StrongTypePtr type,
size_t numSlots) {
return c10::make_intrusive<Object>(std::move(type), numSlots);
}
/**
* Slot API.
*
* Attributes are stored as a simple vector so that lookups are fast at
* runtime. A "slot" is just an index into that vector, which can be computed
* statically if you have access to the class type. Use this API if you are
* writing compiler stuff.
*/
void setSlot(size_t slot, IValue v) {
if (slot >= slots_.size()) {
// for module types, it is possible that the members of the class have
// expanded after the object was created. In this case, we expand
// the slots to the right size
resizeObject(slot);
}
slots_[slot] = std::move(v);
}
const IValue& getSlot(size_t slot) const {
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(slot < slots_.size());
// NOTE: This lookup is fairly hot, so we use unchecked access to the
// vector. Errors should still be detectable with ASan.
return slots_[slot];
}
void unsafeRemoveSlot(size_t slot) {
TORCH_CHECK(slot < slots_.size());
slots_.erase(slots_.begin() + slot);
}
/**
* Attribute API.
*
* Wrappers around the slot stuff so that users can access attributes
* directly. Use this API if you are a user.
*
* Note: Unlike in Python, TorchScript must make a distinction between
* attributes (which are IValues) and methods (which are Methods). If you
* want a method, use `obj.type()->getMethod()`
*/
IValue getAttr(const std::string& name) const;
void setAttr(const std::string& name, IValue v);
// Remove attribute by name, caller is responsible for
// the safety of this operation
// We didn't remove the attribute in the type because the type
// might be shared by multiple objects.
// Therefore after removing attribute, the object is in an inconsistent
// state where it has more attribute types in its Type than
// the attribute slots it has, user needs to make sure the object
// has consistent by removing the attribute in type as well
void unsafeRemoveAttr(const std::string& name);
std::string name() const;
const std::vector<IValue>& slots() const {
return slots_;
}
std::shared_ptr<ClassType> type() const;
std::shared_ptr<torch::jit::CompilationUnit> compilation_unit() {
return type_.cu_;
}
c10::intrusive_ptr<Object> copy() const;
c10::intrusive_ptr<Object> deepcopy() const;
c10::intrusive_ptr<Object> deepcopy(IValue::HashAliasedIValueMap& memo) const;
private:
void resizeObject(size_t slot);
StrongTypePtr type_;
std::vector<IValue> slots_;
};
// virtual ivalue PyObjectHolder that hold a py::object, we make this virtual
// because the py::object and refcounting logic should happen in libtorch_python
// see concrete implementation in python_ivalue.h
struct ivalue::PyObjectHolder : c10::intrusive_ptr_target {
public:
virtual PyObject* getPyObject() = 0;
virtual c10::InferredType tryToInferType() = 0;
virtual IValue toIValue(const TypePtr& type, c10::optional<int32_t> N = c10::nullopt) = 0;
virtual std::string toStr() = 0;
virtual ~PyObjectHolder(){};
};
struct ivalue::EnumHolder : c10::intrusive_ptr_target {
public:
EnumHolder(std::shared_ptr<EnumType> type, std::string name, IValue value)
: type_(std::move(type)),
name_(std::move(name)),
value_(std::move(value)) {}
bool is(const ivalue::EnumHolder& rhs) {
return *this == rhs;
}
friend bool operator==(
const ivalue::EnumHolder& lhs,
const ivalue::EnumHolder& rhs);
TORCH_API friend std::ostream& operator<<(
std::ostream& out,
const EnumHolder& v);
TORCH_API const std::string qualifiedClassName() const;
const std::string unqualifiedClassName() const;
const std::string& name() const {
return name_;
}
const IValue& value() const {
return value_;
}
std::shared_ptr<EnumType> type() const {
return type_;
}
private:
std::shared_ptr<EnumType> type_;
std::string name_;
IValue value_;
};
#undef TORCH_FORALL_TAGS
namespace detail {
struct _guarded_unsigned_long_unique_dummy final {
_guarded_unsigned_long_unique_dummy(int64_t){};
};
using _guarded_unsigned_long = std::conditional_t<
std::is_same<unsigned long, uint32_t>::value ||
std::is_same<unsigned long, uint64_t>::value,
_guarded_unsigned_long_unique_dummy,
unsigned long>;
} // namespace detail
inline const ivalue::Object& IValue::toObjectRef() const {
AT_ASSERT(isObject(), "Expected Object but got ", tagKind());
return *static_cast<const c10::ivalue::Object*>(payload.as_intrusive_ptr);
}
// note: when adding a DEFINE_TO case here you should also add a
// toX method to IValue. These named methods are much more discoverable
// than the to templated function.
#define DEFINE_TO(type, method_name) \
template <> \
inline type IValue::to<type>()&& { \
return std::move(*this).method_name(); \
} \
template <> \
inline type IValue::to<type>() const& { \
return this->method_name(); \
}
DEFINE_TO(at::Tensor, toTensor)
DEFINE_TO(at::Storage, toStorage)
DEFINE_TO(c10::Stream, toStream)
DEFINE_TO(float, toDouble)
DEFINE_TO(double, toDouble)
DEFINE_TO(unsigned char, toInt)
DEFINE_TO(signed char, toInt)
DEFINE_TO(unsigned short, toInt)
DEFINE_TO(short, toInt)
DEFINE_TO(int, toInt)
DEFINE_TO(uint32_t, toInt)
DEFINE_TO(uint64_t, toInt)
DEFINE_TO(detail::_guarded_unsigned_long, toInt)
DEFINE_TO(int64_t, toInt)
DEFINE_TO(bool, toBool)
DEFINE_TO(c10::intrusive_ptr<caffe2::Blob>, toBlob);
DEFINE_TO(c10::intrusive_ptr<ivalue::ConstantString>, toString)
DEFINE_TO(c10::intrusive_ptr<ivalue::Object>, toObject)
DEFINE_TO(at::Scalar, toScalar)
DEFINE_TO(c10::List<int64_t>, toIntList)
DEFINE_TO(c10::List<double>, toDoubleList)
DEFINE_TO(c10::List<bool>, toBoolList)
DEFINE_TO(c10::List<at::Tensor>, toTensorList)
DEFINE_TO(c10::impl::GenericList, toList)
DEFINE_TO(c10::impl::GenericDict, toGenericDict)
DEFINE_TO(c10::intrusive_ptr<ivalue::Tuple>, toTuple)
DEFINE_TO(std::string, toStringRef)
DEFINE_TO(c10::intrusive_ptr<ivalue::Future>, toFuture)
DEFINE_TO(c10::intrusive_ptr<c10::RRefInterface>, toRRef)
DEFINE_TO(c10::intrusive_ptr<at::Quantizer>, toQuantizer)
DEFINE_TO(IValue, toIValue)
DEFINE_TO(c10::Device, toDevice)
DEFINE_TO(at::ScalarType, toScalarType)
DEFINE_TO(at::Layout, toLayout)
DEFINE_TO(at::MemoryFormat, toMemoryFormat)
DEFINE_TO(at::QScheme, toQScheme)
DEFINE_TO(at::Dimname, toDimname)
DEFINE_TO(at::Generator, toGenerator)
template <class T>
struct _fake_type {};
// generic_to<T> converts an IValue from a generic list or generic dict
// to a concrete list/dict type likelike List<T>, Dict<...> or optional<T>.
// Note that in the case of lists, this only works for IValue-based lists,
// i.e. not for int64_t, double, ...
// generic_to<T> is an implementation detail of IValue::to<T> and not
// supposed to be called directly.
// The _fake_type<T> parameter allows us to overload
// based on the return type.
template <class Elem>
// TODO this is deprecated but we don't throw a warning because a lot of ops in
// native_functions.yaml still return std::vector.
// C10_DEPRECATED_MESSAGE("IValues based on std::vector<T> are potentially slow
// and deprecated. Please use torch::List<T> instead.")
std::vector<Elem> generic_to(IValue ivalue, _fake_type<std::vector<Elem>>) {
// We need to do a deep copy of the vector because there might be other
// references to this same IValue that also use the list. We can't just
// move the elements out.
auto list = std::move(ivalue).to<List<Elem>>();
std::vector<Elem> result;
result.reserve(list.size());
for (Elem v : list) {
result.push_back(std::move(v));
}
return result;
}
template <typename T>
c10::intrusive_ptr<T> IValue::toCustomClass() && {
static_assert(
std::is_base_of<torch::CustomClassHolder, T>::value == true,
"toCustomClass requires that template parameter T must inherit "
"from torch::CustomClassHolder");
auto obj = toObject();
TORCH_CHECK(
obj->slots().size() == 1,
"Tried to cast IValue to custom class but it did "
"not contain a custom class!");
const Type* expected_type = c10::getCustomClassType<c10::intrusive_ptr<T>>().get();
ivalue::checkCustomClassType(expected_type, type().get());
auto userObj =
c10::static_intrusive_pointer_cast<T>(obj->getSlot(0).toCapsule());
return userObj;
}
template <typename T>
c10::intrusive_ptr<T> IValue::toCustomClass() const& {
static_assert(
std::is_base_of<torch::CustomClassHolder, T>::value == true,
"toCustomClass requires that template parameter T must inherit "
"from torch::CustomClassHolder");
auto obj = toObject();
TORCH_CHECK(
obj->slots().size() == 1,
"Tried to cast IValue to custom class but it did "
"not contain a custom class!");
const Type* expected_type = c10::getCustomClassType<c10::intrusive_ptr<T>>().get();
ivalue::checkCustomClassType(expected_type, type().get());
auto userObj =
c10::static_intrusive_pointer_cast<T>(obj->getSlot(0).toCapsule());
return userObj;
}
template <typename T>
T generic_to(IValue ivalue, _fake_type<T>) {
using ElemType = typename std::remove_pointer<T>::type::element_type;
return std::move(ivalue).toCustomClass<ElemType>();
}
template <typename T>
tagged_capsule<T> generic_to(IValue ivalue, _fake_type<tagged_capsule<T>>) {
return tagged_capsule<T>{std::move(ivalue)};
}
template <typename Elem>
c10::List<Elem> generic_to(IValue ivalue, _fake_type<c10::List<Elem>>) {
return impl::toTypedList<Elem>(std::move(ivalue).toList());
}
template <typename T>
static std::vector<T> createVectorFromList(const c10::detail::ListImpl* impl) {
std::vector<T> result;
result.reserve(impl->list.size());
for (size_t i = 0, N = impl->list.size(); i < N; ++i) {
result.push_back(impl->list[i].to<T>());
}
return result;
}
template <typename T>
static std::vector<T> createVectorFromList(const c10::List<T>& impl) {
std::vector<T> result;
result.reserve(impl.size());
for (size_t i = 0, N = impl.size(); i < N; ++i) {
result.push_back(impl[i]);
}
return result;
}
template <typename T>
OptionalArray<T> generic_to(IValue ivalue, _fake_type<OptionalArray<T>>) {
if (ivalue.isNone()) {
return {};
}
return createVectorFromList<T>(
std::move(ivalue).to<c10::List<T>>()
);
}
namespace detail {
template <typename Elem, size_t... I>
std::array<Elem, sizeof...(I)> generic_to_array(
IValue ivalue,
_fake_type<std::array<Elem, sizeof...(I)>>,
std::index_sequence<I...>) {
// We need to do a deep copy of the array because there might be other
// references to this same IValue that also use the list. We can't just
// move the elements out.
auto list = std::move(ivalue).to<List<Elem>>();
TORCH_CHECK(
list.size() == sizeof...(I),
"Tried to convert a List with ",
list.size(),
" elements to a fixed-size array of size ",
sizeof...(I));
return {list[I]...};
}
} // namespace detail
template <typename Elem, size_t N>
std::array<Elem, N> generic_to(
IValue ivalue,
_fake_type<std::array<Elem, N>> ft) {
return detail::generic_to_array(ivalue, ft, std::make_index_sequence<N>());
}
template <typename Key, typename Value>
c10::Dict<Key, Value> generic_to(
IValue ivalue,
_fake_type<c10::Dict<Key, Value>>) {
return impl::toTypedDict<Key, Value>(std::move(ivalue).toGenericDict());
}
template <typename K, typename V>
C10_DEPRECATED_MESSAGE(
"IValues based on std::unordered_map are slow and deprecated. Please use c10::Dict<K, V> instead.")
std::unordered_map<K, V> generic_to(
IValue ivalue,
_fake_type<std::unordered_map<K, V>>) {
std::unordered_map<K, V> specialized_dict;
for (const auto& item : std::move(ivalue).toGenericDict()) {
specialized_dict[item.key().to<K>()] = item.value().to<V>();
}
return specialized_dict;
}
template <typename T>
c10::optional<T> generic_to(IValue ivalue, _fake_type<c10::optional<T>>) {
if (ivalue.isNone()) {
return c10::nullopt;
}
return std::move(ivalue).to<T>();
}
namespace detail {
template <typename Tuple, std::size_t... INDEX>
Tuple generic_to_tuple_impl(
const std::vector<IValue>& t,
std::index_sequence<INDEX...>) {
return std::make_tuple(
t[INDEX].to<typename std::tuple_element<INDEX, Tuple>::type>()...);
}
} // namespace detail
template <
typename... Args,
typename Indices = std::make_index_sequence<sizeof...(Args)>,
std::enable_if_t<
!guts::disjunction<
std::is_lvalue_reference<Args>...,
guts::negation<std::is_constructible<IValue, Args>>...>::value,
std::nullptr_t> = nullptr>
std::tuple<Args...> generic_to(IValue ivalue, _fake_type<std::tuple<Args...>>) {
auto vals = ivalue.toTuple()->elements();
TORCH_CHECK(vals.size() == sizeof...(Args));
return detail::generic_to_tuple_impl<std::tuple<Args...>>(vals, Indices{});
}
template <typename T>
inline T IValue::to() && {
return generic_to(std::move(*this), _fake_type<T>{});
}
template <typename T>
inline T IValue::to() const& {
return generic_to(*this, _fake_type<T>{});
}
inline c10::List<int64_t> IValue::toIntList() && {
AT_ASSERT(isIntList(), "Expected IntList but got ", tagKind());
return c10::List<int64_t>(moveToIntrusivePtr<c10::detail::ListImpl>());
}
inline c10::List<int64_t> IValue::toIntList() const& {
AT_ASSERT(isIntList(), "Expected IntList but got ", tagKind());
return c10::List<int64_t>(toIntrusivePtr<c10::detail::ListImpl>());
}
inline std::vector<int64_t> IValue::toIntVector() const {
AT_ASSERT(isIntList(), "Expected IntList but got ", tagKind());
return createVectorFromList<int64_t>(
static_cast<const c10::detail::ListImpl*>(payload.as_intrusive_ptr));
}
inline c10::List<double> IValue::toDoubleList() && {
AT_ASSERT(isDoubleList(), "Expected DoubleList but got ", tagKind());
return c10::List<double>(moveToIntrusivePtr<c10::detail::ListImpl>());
}
inline c10::List<double> IValue::toDoubleList() const& {
AT_ASSERT(isDoubleList(), "Expected DoubleList but got ", tagKind());
return c10::List<double>(toIntrusivePtr<c10::detail::ListImpl>());
}
inline std::vector<double> IValue::toDoubleVector() const {
AT_ASSERT(isDoubleList(), "Expected DoubleList but got ", tagKind());
return createVectorFromList<double>(
static_cast<const c10::detail::ListImpl*>(payload.as_intrusive_ptr));
}
inline c10::List<bool> IValue::toBoolList() && {
AT_ASSERT(isBoolList(), "Expected BoolList but got ", tagKind());