forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ivalue_inl.h
1672 lines (1497 loc) · 57.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 <type_traits>
#include <utility>
#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/impl/DeviceGuardImplInterface.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/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(
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<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() && {
return c10::Stream::unpack(payload.u.as_int);
}
inline c10::Stream IValue::toStream() const& {
return c10::Stream::unpack(payload.u.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)) {}
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 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(std::forward<Args>(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 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>;
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 storage pointers for all tensors in IValue can be passed as well. These
* DataPtrs are used to synchronize CUDA streams. If data_ptrs 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 data_ptrs when 1) DataPtrs cannot be extracted through IValue's
* getSubValues() or through pickling in case of Python object; or when 2)
* customized DataPtrs extraction is more efficient.
*/
void markCompleted(
IValue value,
c10::optional<std::vector<std::reference_wrapper<const at::DataPtr>>>
data_ptrs = c10::nullopt) {
// Start by performing all steps that can throw, before setting any field.
// Do this before even acquiring the mutex, because extractDataPtrs might
// acquire the GIL, which could lead to a lock inversion with our mutex.
// See https://github.com/pytorch/pytorch/issues/58239.
std::vector<std::reference_wrapper<const at::DataPtr>> actualDataPtrs;
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) {
actualDataPtrs =
data_ptrs.has_value() ? std::move(*data_ptrs) : extractDataPtrs(value);
usedDevices = getDevicesOfDataPtrs(impl_, actualDataPtrs);
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();
dataPtrs_ = std::move(actualDataPtrs);
for (const c10::Device& device : usedDevices) {
c10::Event event(impl_.type());
event.record(impl_.getStream(device));
events_.push_back(std::move(event));
}
std::vector<std::function<void(Future&)>> cbs;
cbs.swap(callbacks_);
lock.unlock();
finished_cv_.notify_all();
for (auto& callback : cbs) {
invokeCallback(std::move(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.
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(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_);
}
return value_;
}
// This accessor should only be used if we know that the future is
// completed() with no error.
const IValue& constValue() const {
std::unique_lock<std::mutex> lock(mutex_);
AT_ASSERT(completed());
AT_ASSERT(!eptr_);
return value_;
}
// This accessor should only be used if we know that the future is
// completed() with no error.
const std::vector<std::reference_wrapper<const at::DataPtr>>& dataPtrs() const {
std::unique_lock<std::mutex> lock(mutex_);
AT_ASSERT(completed());
AT_ASSERT(!eptr_);
return dataPtrs_;
}
/**
* 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.
*/
template <typename T>
void addCallback(T callback) {
#if __cpp_lib_is_invocable >= 201703
static_assert(
std::is_invocable_r<void, T, Future&>::value,
"The callback must have signature void(Future&)");
#endif
std::unique_lock<std::mutex> lock(mutex_);
if (completed()) {
lock.unlock();
invokeCallback(std::move(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.
*/
template <typename T>
c10::intrusive_ptr<Future> then(T callback, TypePtr type) {
#if __cpp_lib_is_invocable >= 201703
static_assert(
std::is_invocable_r<IValue, T, Future&>::value,
"The callback must have signature IValue(Future&)");
#endif
auto childFut = createInstance(std::move(type));
addCallback(
[childFut, cb = std::move(callback)](Future& parentFut) mutable {
try {
childFut->markCompleted(cb(parentFut));
} catch (std::exception&) {
childFut->setError(std::current_exception());
}
});
return childFut;
}
template <typename T>
c10::intrusive_ptr<Future> thenAsync(T callback, TypePtr type) {
#if __cpp_lib_is_invocable >= 201703
static_assert(
std::is_invocable_r<c10::intrusive_ptr<Future>, T, Future&>::value,
"The callback must have signature c10::intrusive_ptr<Future>(Future&)");
#endif
auto childFut = createInstance(std::move(type));
addCallback(
[childFut, cb = std::move(callback)](Future& parentFut) mutable {
c10::intrusive_ptr<Future> intermediateFut;
try {
intermediateFut = cb(parentFut);
} catch (std::exception&) {
childFut->setError(std::current_exception());
return;
}
intermediateFut->addCallback(
[childFut = std::move(childFut)](Future& intermediateFut) {
if (intermediateFut.hasError()) {
childFut->setError(intermediateFut.exception_ptr());
} else {
childFut->markCompleted(
intermediateFut.value(), intermediateFut.dataPtrs());
}
});
});
return childFut;
}
// Tries to retrieve the error message from std::exception_ptr.
std::string tryRetrieveErrorMessage() const {
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_;
}
const std::vector<c10::Device>& devices() const {
return devices_;
}
// This method should be used when one intends to manually create a child
// future, for example when implementing a customized version of then().
c10::intrusive_ptr<Future> createInstance(at::TypePtr type) {
return c10::make_intrusive<Future>(std::move(type), devices_);
}
private:
// This method should always be used when invoking a callback (regardless of
// how/when that happens) as it will ensure that the proper "environment" is
// set up before running the callback, as in, it will set up the CUDA streams,
// synchronize them with the value, and so on (if needed).
template<typename T>
void invokeCallback(T callback) {
#if __cpp_lib_is_invocable >= 201703
static_assert(
std::is_invocable_r<void, T, Future&>::value,
"The callback must have signature void(Future&)");
#endif
c10::OptionalDeviceGuard deviceGuard(currentDevice_);
std::vector<c10::Stream> streams;
for (const c10::Device& device : devices_) {
streams.push_back(impl_.getStreamFromGlobalPool(device));
}
c10::MultiStreamGuard streamGuard(streams);
synchronizeWithCurrentStreams();
callback(*this);
}
// This method should be called before this future's value is used, as it
// ensures that the CUDA streams that are "current" at the callsite properly
// synchronize with the value.
void synchronizeWithCurrentStreams() {
for (c10::Event& event : events_) {
event.block(impl_.getStream(event.device()));
}
for (const at::DataPtr& data_ptr : dataPtrs_) {
if (!data_ptr.device().is_cpu()) {
impl_.recordDataPtrOnStream(
data_ptr, impl_.getStream(data_ptr.device()));
}
}
}
void setErrorInternal(
std::exception_ptr eptr,
std::unique_lock<std::mutex>& lock) {
TORCH_CHECK(
!eptr_,
"Error already set on this Future: ",
tryRetrieveErrorMessageInternal(eptr_),
", trying to set error: ",
tryRetrieveErrorMessageInternal(eptr));
TORCH_INTERNAL_ASSERT(!completed(), "Future is already marked completed");
completed_ = true;
eptr_ = std::move(eptr);
std::vector<std::function<void(Future&)>> cbs;
cbs.swap(callbacks_);
lock.unlock();
finished_cv_.notify_all();
for (auto& callback : cbs) {
invokeCallback(std::move(callback));
}
}
// Tries to retrieve the error message from std::exception_ptr.
std::string tryRetrieveErrorMessageInternal(std::exception_ptr eptr) const {
try {
std::rethrow_exception(eptr);
} catch (const std::exception& e) {
return e.what();
} catch (...) {
return "Unknown Exception Type";
}
}
// Defined in ivalue.cpp.
static std::vector<std::reference_wrapper<const at::DataPtr>> extractDataPtrs(
const at::IValue& value);
static std::vector<c10::Device> getDevicesOfDataPtrs(
const c10::impl::VirtualGuardImpl& impl,
const std::vector<std::reference_wrapper<const at::DataPtr>>& data_ptrs) {
c10::DeviceIndex deviceCount = impl.deviceCount();
std::vector<bool> isDeviceUsed(deviceCount, false);
for (const at::DataPtr& data_ptr : data_ptrs) {
if (!data_ptr.device().is_cpu()) {
TORCH_CHECK_VALUE(
data_ptr.device().type() == impl.type(),
"Expected all data ptrs to be on a device of type ",
impl.type(),
", got one on device ",
data_ptr.device());
isDeviceUsed[data_ptr.device().index()] = true;
}
}
std::vector<c10::Device> devices;
for (c10::DeviceIndex idx = 0; idx < deviceCount; idx++) {
if (isDeviceUsed[idx]) {
devices.emplace_back(impl.type(), idx);
}
}
return devices;
}
static std::string formatSetOfDevices(
const std::vector<c10::Device>& devices) {
if (devices.empty()) {
return "(none)";
}
std::ostringstream oss;
oss << devices[0];
for (size_t idx = 1; idx < devices.size(); idx++) {
if (idx == devices.size() - 1) {
oss << " and ";
} else {
oss << ", ";
}
oss << devices[idx];
}
return oss.str();
}
static c10::DeviceType getTypeOfDevices(
const std::vector<c10::Device>& devices) {
if (devices.empty()) {
return c10::kCPU;
}
c10::DeviceType deviceType = devices[0].type();
for (size_t idx = 1; idx < devices.size(); idx++) {
TORCH_CHECK_VALUE(
devices[idx].type() == deviceType,
"Expected all devices to be of the same type, but got a mismatch between ",
devices[0],
" and ",
devices[idx]);
}
return deviceType;
}
// We need devices to be sorted in order to use ensureIsSubsetOfDevices.
static std::vector<c10::Device> sortAndDeduplicateDevices(
const c10::impl::VirtualGuardImpl& impl,
std::vector<c10::Device> devices) {
std::sort(
devices.begin(), devices.end(),
[](const c10::Device& a, const c10::Device& b) { return a.index() < b.index(); });
// Deduplicate by compacting.
size_t targetIdx = 0;
for (size_t sourceIdx = 0; sourceIdx < devices.size(); sourceIdx++) {
TORCH_CHECK_VALUE(
devices[sourceIdx].has_index(),
"Expected devices to have indices, got ", devices[sourceIdx]);
if (targetIdx > 0 && devices[targetIdx - 1].index() == devices[sourceIdx].index()) {
// It's a duplicate, skip it.
continue;
}
if (sourceIdx != targetIdx) {
devices[targetIdx] = devices[sourceIdx];
}
targetIdx++;
}
// If there were duplicates there's now a gap at the end: trim it. Resizing
// requires the item type to be default-constructible (which c10::Device is
// not) because in principle it could be required to create new items. Since
// we know we'll shrink the vector, we provide a custom dummy value instead.
devices.resize(targetIdx, c10::Device(c10::kCPU));
return devices;
}
static void ensureIsSubsetOfDevices(
const std::vector<c10::Device>& subset,
const std::vector<c10::Device>& superset) {
// We assume the devices in both vectors have the same consistent type, and
// their indices are unique and sorted.
std::vector<c10::Device> excessDevices;
std::set_difference(
subset.begin(),
subset.end(),
superset.begin(),
superset.end(),
std::back_inserter(excessDevices),
[](const c10::Device& a, const c10::Device& b) { return a.index() < b.index(); });
TORCH_CHECK_VALUE(
excessDevices.empty(),
"The result contained tensors residing on device(s) ",
formatSetOfDevices(excessDevices),
" which are not among the expected device(s) ",
formatSetOfDevices(superset));
}
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(Future&)>> callbacks_;
std::exception_ptr eptr_;
// An upcast pointer to a virtual class which allows us to manipulate events,
// streams, ... in a generic way, without an explicit dependency on CUDA.
const c10::impl::VirtualGuardImpl impl_;
// The device that was current when markCompleted was called, which we'll
// restore when invoking callbacks. It's optional because we'll only store it
// if the future completes successfully.
optional<c10::Device> currentDevice_;
// The events that correspond to the completion of the async I/O kernels. They
// are recorded on the appropriate streams when the future is marked completed
// and can then be queried/waited/blocked on. There is one event for each
// distinct device on which the value's tensors reside.
std::vector<c10::Event> events_;
// A cached version of the data ptrs extracted from the value when the future
// is first marked completed.
std::vector<std::reference_wrapper<const at::DataPtr>> dataPtrs_;
// The bounding set of devices that this future, and any of its children, is
// allowed to use. This is a superset of the set of devices used by the events
// above. We need this to know what streams (for which devices) to set as
// current when invoking a callback, thus allowing the callback to use devices
// that the parent future didn't use. This field is set to the value provided
// in the constructor and will be "inherited" by all child futures.
const std::vector<c10::Device> devices_;
};
// 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 std::vector<at::Tensor> extractTensors() = 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<