forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
operator.h
1636 lines (1464 loc) · 58.6 KB
/
operator.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
#ifndef CAFFE2_CORE_OPERATOR_H_
#define CAFFE2_CORE_OPERATOR_H_
#include <array>
#include <cfenv>
#include <climits>
#include <cstddef>
#include <exception>
#include <functional>
#include <set>
#include <string>
#include <typeinfo>
#include <vector>
#include <c10/macros/Macros.h>
#include <c10/util/Registry.h>
#include <c10/util/typeid.h>
#include "caffe2/core/blob.h"
#include "caffe2/core/common.h"
#include "caffe2/core/net.h"
#include "caffe2/core/observer.h"
#include "caffe2/core/operator_gradient.h"
#include "caffe2/core/operator_schema.h"
#include "caffe2/core/tensor.h"
#include "caffe2/core/tensor_int8.h"
#include "caffe2/core/types.h"
#include "caffe2/core/workspace.h"
#include "caffe2/proto/caffe2_pb.h"
#include "caffe2/utils/proto_utils.h"
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
#include <ATen/core/Tensor.h>
#include <ATen/core/ivalue.h>
#endif
C10_DECLARE_bool(caffe2_operator_throw_if_fp_exceptions);
C10_DECLARE_bool(caffe2_operator_throw_if_fp_overflow_exceptions);
#ifdef __GNU_LIBRARY__
C10_DECLARE_bool(caffe2_operator_throw_on_first_occurrence_if_fp_exceptions);
#endif
namespace c10 {
struct FunctionSchema;
}
namespace caffe2 {
class CAFFE2_API OperatorBase;
typedef ObserverBase<OperatorBase> OperatorObserver;
class CAFFE2_API OperatorBase : public Observable<OperatorBase> {
public:
explicit OperatorBase(const OperatorDef& operator_def, Workspace* ws);
/*
* Notes: All outputs ivalues must be tensors. Input ivalue list must start
* with all tensors ("inputs" in caffe2 terminology),
* followed by non-tensors ("arguments" in caffe2 terminology).
* Alternatively, inputs can be one tensor list ivalue followed by non-tensors
* to represent operators with a variable number of inputs.
*/
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
explicit OperatorBase(
const c10::FunctionSchema& schema,
std::vector<c10::IValue> inputs,
c10::List<at::Tensor> outputs);
#endif
virtual ~OperatorBase() noexcept;
/** @brief Return true if the operator was instantiated with OperatorDef
* New operators should be instantiated with FunctionSchema
*/
bool isLegacyOperator() const {
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
return !fn_schema_;
#else
return true;
#endif
}
const c10::FunctionSchema& getFunctionSchema() const {
CAFFE_ENFORCE(!isLegacyOperator());
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
return *fn_schema_.get();
#else
CAFFE_THROW("Non-legacy operators are not legal in xplat/caffe2");
#endif
}
/** @brief Checks if the operator has an argument of the given name.
*/
inline bool HasArgument(const string& name) const {
if (isLegacyOperator()) {
CAFFE_ENFORCE(operator_def_, "operator_def was null!");
return ArgumentHelper::HasArgument(*operator_def_, name);
}
return argumentIndexWithName(name).has_value();
}
// Functions that deal with arguments. Basically, this allows us to map an
// argument name to a specific type of argument that we are trying to access.
template <typename T>
inline T GetSingleArgument(const string& name, const T& default_value) const {
if (isLegacyOperator()) {
CAFFE_ENFORCE(operator_def_, "operator_def was null!");
return ArgumentHelper::GetSingleArgument<OperatorDef, T>(
*operator_def_, name, default_value);
}
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
auto index = argumentIndexWithName(name);
CAFFE_ENFORCE(index.has_value(), "Couldn't get index for argument!", name);
const auto& value = newstyle_inputs_[index.value()];
return value.template to<T>();
#else
CAFFE_THROW("Non-legacy operators are not legal in xplat/caffe2");
#endif
}
template <typename T>
inline bool HasSingleArgumentOfType(const string& name) const {
CAFFE_ENFORCE(operator_def_, "operator_def was null!");
return ArgumentHelper::HasSingleArgumentOfType<OperatorDef, T>(
*operator_def_, name);
}
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
template <typename T>
inline vector<T> GetVectorFromIValueList(const c10::IValue& value) const {
return value.template to<List<T>>().vec();
}
#endif
template <typename T>
inline vector<T> GetRepeatedArgument(
const string& name,
const vector<T>& default_value = {}) const;
// Get the inputs and outputs as specific types.
template <typename T>
inline const T& Input(int idx) {
static_assert(
!std::is_same<T, Tensor>::value,
"You should use Input<Tensor>(int, DeviceType) for "
"Tensor.");
DCHECK_LT((size_t)idx, inputs_.size());
try {
return inputs_.at(idx)->template Get<T>();
} catch (::caffe2::EnforceNotMet& enf) {
if (has_debug_def()) {
enf.AppendMessage(".\nOffending Blob name: ");
enf.AppendMessage(debug_def().input(idx));
enf.AppendMessage(".\n");
}
throw enf;
}
}
// TODO(jerryzh): Remove template
// and the type argument?
// This is to keep the API changes minimal and make refactoring
// a bit easier
template <typename T>
inline const T& Input(int idx, DeviceType type) {
if (isLegacyOperator()) {
static_assert(
std::is_same<T, Tensor>::value,
"Input(int, DeviceType) is only available for Tensor");
DCHECK_LT((size_t)idx, inputs_.size());
try {
// TODO(jerryzh): We'll need to check device type in Get<T>() later
// Get<T>() -> Get<T>(type)
const auto& tensor = inputs_.at(idx)->template Get<T>();
return tensor;
} catch (::caffe2::EnforceNotMet& enf) {
if (has_debug_def()) {
enf.AppendMessage(".\nOffending Blob name: ");
enf.AppendMessage(debug_def().input(idx));
enf.AppendMessage(".\n");
}
throw enf;
}
}
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
DCHECK_LT(0, newstyle_inputs_.size());
IValue ival;
if (newstyle_inputs_[0].isTensorList()) {
// if the first input is a tensor list, we get input tensors by indexing into that list.
// currently, this means that only tensors from that list are accessible as inputs.
// any hypothetical input tensors that come after the list are not accessible.
auto tensorList = newstyle_inputs_[0].toTensorVector();
DCHECK_LT((size_t)idx, tensorList.size());
ival = tensorList[idx];
} else {
// if the first input is not a tensor list, we get input tensors by indexing into the inputs.
DCHECK_LT((size_t)idx, newstyle_inputs_.size());
ival = newstyle_inputs_[idx];
}
CAFFE_ENFORCE(
ival.isTensor(),
"Input(int, DeviceType) is only available for IValues that store Tensors");
Tensor tensor = caffe2::Tensor(ival.toTensor());
CAFFE_ENFORCE_EQ(tensor.GetDeviceType(), type);
input_tensors_[idx] = std::move(tensor);
return input_tensors_[idx];
#else
CAFFE_THROW("Non-legacy operators are not legal in xplat/caffe2");
#endif
}
template <typename T>
inline T* Output(int idx) {
CAFFE_ENFORCE(
isLegacyOperator(),
"Output(idx) not supported for operators exported to c10. Please use XOutput instead.");
static_assert(
!std::is_same<T, Tensor>::value,
"You should use Output<Tensor>(int, DeviceType) for "
"Tensor.");
return outputs_.at(idx)->template GetMutable<T>();
}
// TODO(jerryzh): Remove this template
template <typename T>
inline T* Output(int idx, DeviceType type) {
if (isLegacyOperator()) {
static_assert(
std::is_same<T, Tensor>::value,
"Output(int, DeviceType) is only available for Tensor");
// When you get a Tensor here it is not fully initialized
return BlobGetMutableTensor(outputs_.at(idx), type);
}
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
at::Tensor output = newstyle_outputs_[idx];
Tensor tensor = caffe2::Tensor(output);
if (!tensor.defined() || tensor.GetDeviceType() != type) {
// Fix tensor type
tensor = Tensor(type);
output = at::Tensor(std::move(tensor.getIntrusivePtr()));
}
output_tensors_[idx] = caffe2::Tensor(output);
newstyle_outputs_[idx] = std::move(output);
return &output_tensors_[idx];
#else
CAFFE_THROW("Non-legacy operators are not legal in xplat/caffe2");
#endif
}
inline Tensor
XOutputTensor(int idx, at::IntArrayRef dims, at::TensorOptions options) {
CAFFE_ENFORCE_WITH_CALLER(
options.device_opt() != c10::nullopt,
"device must be provided in option.");
if (isLegacyOperator()) {
return XBlobGetMutableTensor(outputs_.at(idx), dims, options);
}
return OutputTensor(idx, dims, options)->UnsafeSharedInstance();
}
void SetOutputTensor(int idx, Tensor tensor) {
if (!isLegacyOperator()) {
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
newstyle_outputs_[idx] = at::Tensor(tensor);
// also update the tensor in the hack
output_tensors_[idx] = std::move(tensor);
#else
CAFFE_THROW("Non-legacy operators are not legal in xplat/caffe2");
#endif
} else {
// update the tensor in the workspace
BlobSetTensor(outputs_.at(idx), std::move(tensor));
}
}
Tensor OutputTensorOrUndefined(int idx) {
if (isLegacyOperator()) {
return BlobGetTensorOrUndefined(*outputs_.at(idx));
}
return output_tensors_[idx].UnsafeSharedInstance();
}
inline Tensor*
OutputTensor(int idx, at::IntArrayRef dims, at::TensorOptions options) {
if (isLegacyOperator()) {
CAFFE_ENFORCE_WITH_CALLER(
options.device_opt() != c10::nullopt,
"device must be provided in options.");
return BlobGetMutableTensor(outputs_.at(idx), dims, options);
}
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
at::Tensor output = newstyle_outputs_[idx];
Tensor tensor =
GetSizedTensorWithOptions(caffe2::Tensor(output), dims, options);
// assign it back in case it changed
output = at::Tensor(std::move(tensor.getIntrusivePtr()));
output_tensors_[idx] = caffe2::Tensor(output);
newstyle_outputs_[idx] = std::move(output);
return &output_tensors_[idx];
#else
CAFFE_THROW("Non-legacy operators are not legal in xplat/caffe2");
#endif
}
// Get output Tensor of the operator and CopyFrom the given Tensor
Tensor* OutputTensorCopyFrom(
int idx,
at::TensorOptions options,
const Tensor& src,
bool async = false) {
CAFFE_ENFORCE_WITH_CALLER(
options.device_opt() != c10::nullopt,
"device must be provided in options.");
// Ouptut Tensor will always have the same data type as `src`
if (!options.has_dtype()) {
options = options.dtype(src.dtype());
}
CAFFE_ENFORCE_WITH_CALLER(
options.dtype() == src.dtype(),
"We don't allow change of src data type in OutputTensorCopyFrom");
Tensor* t = OutputTensor(idx, src.sizes(), options);
t->CopyFrom(src, async);
return t;
}
Tensor* OutputTensorAlias(int idx, const Tensor& src) {
CAFFE_ENFORCE(
isLegacyOperator(),
"OutputTensorAlias(idx, src) not (yet) supported for operators exported to c10.");
return BlobSetTensor(OutputBlob(idx),
src.Alias());
}
template <typename T>
inline T* Output(int idx, T* allocated) {
CAFFE_ENFORCE(
isLegacyOperator(),
"Output(idx, allocated) not supported for operators exported to c10. Please use XOutput.");
outputs_.at(idx)->Reset(allocated);
return allocated;
}
inline const Blob& InputBlob(int idx) {
CAFFE_ENFORCE(
isLegacyOperator(),
"InputBlob(idx) not (yet) supported for operators exported to c10.");
return *inputs_.at(idx);
}
inline Blob* OutputBlob(int idx) {
CAFFE_ENFORCE(
isLegacyOperator(),
"OutputBlob(idx) not (yet) supported for operators exported to c10.");
return outputs_.at(idx);
}
// Check whether output j is an alias of input i by comparing Blob pointers,
// note this does not check if the two Blobs points to the same Tensor, or if
// the Tensor pointers point to the same TensorImpl, or if the Storages alias
inline bool IsInputOutputAlias(int i, int j) {
CAFFE_ENFORCE(
isLegacyOperator(),
"IsInputOutputAlias(i, j) not (yet) supported for operators exported to c10.");
return inputs_.at(i) == outputs_.at(j);
}
template <typename T>
inline bool InputIsType(int idx) {
CAFFE_ENFORCE(
isLegacyOperator(),
"InputIsType(idx) not (yet) supported for operators exported to c10.");
static_assert(
!std::is_same<T, Tensor>::value,
"You should use InputIsTensorType(int, DeviceType) for "
"Tensor.");
return inputs_.at(idx)->template IsType<T>();
}
inline bool InputIsTensorType(int idx, DeviceType device_type) {
CAFFE_ENFORCE(
isLegacyOperator(),
"InputIsTensorType(idx, device_type) not (yet) supported for operators exported to c10.");
return BlobIsTensorType(*inputs_.at(idx), device_type);
}
template <typename T>
inline bool OutputIsType(int idx) {
CAFFE_ENFORCE(
isLegacyOperator(),
"OutputIsType(idx) not (yet) supported for operators exported to c10.");
static_assert(
!std::is_same<T, Tensor>::value,
"You should use OutputIsTensorType(int, DeviceType) for "
"Tensor.");
return outputs_.at(idx)->template IsType<T>();
}
inline bool OutputIsTensorType(int idx, DeviceType type) {
CAFFE_ENFORCE(
isLegacyOperator(),
"OutputIsTensorType(idx, type) not (yet) supported for operators exported to c10.");
return BlobIsTensorType(*outputs_.at(idx), type);
}
inline int InputSize() const {
return input_size_;
}
inline int OutputSize() const {
if (isLegacyOperator()) {
return outputs_.size();
}
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
return newstyle_outputs_.size();
#else
CAFFE_THROW("Non-legacy operators are not legal in xplat/caffe2");
#endif
}
inline const vector<const Blob*>& Inputs() const {
CAFFE_ENFORCE(
isLegacyOperator(),
"Inputs() not supported for operators exported to c10.");
return inputs_;
}
inline const vector<Blob*>& Outputs() {
CAFFE_ENFORCE(
isLegacyOperator(),
"Outputs() not supported for operators exported to c10.");
return outputs_;
}
vector<TensorShape> InputTensorShapes() const;
virtual void WaitEvent(const Event& ev, int /*stream_id */ = -1) {
ev.Finish();
}
inline void Wait(const OperatorBase& other, int stream_id = -1) {
if (!other.IsEventDisabled()) {
WaitEvent(other.event(), stream_id);
}
}
virtual void WaitEvents(
const std::vector<const Event*>& events,
int /*stream_id*/ = -1) {
for (const auto& ev : events) {
ev->Finish();
}
}
virtual void Finish() {
if (event_) {
event_->Finish();
}
}
virtual bool Run(int /* unused */ /*stream_id*/ = 0) {
CAFFE_NOT_IMPLEMENTED;
}
virtual bool HasAsyncPart() const {
return false;
}
virtual bool SupportsAsyncScheduling() const {
return false;
}
virtual void CancelAsyncCallback() {}
// RunAsync, if implemenented by the specific operators, will schedule the
// computation on the corresponding context and record the event in its
// event_ member object. If the specific operator does not support RunAsync,
// it will simply be synchronous as a fallback.
virtual bool RunAsync(int stream_id = 0) {
try {
auto result = Run(stream_id);
if (result) {
if (HasAsyncPart()) {
RecordEvent();
} else {
SetEventFinished();
}
} else {
SetEventFinished(getErrorMsg().c_str());
}
return result;
} catch (EnforceNotMet& err) {
SetEventFinishedWithException(err.what());
throw;
} catch (const std::exception& err) {
SetEventFinishedWithException(err.what());
throw;
} catch (...) {
SetEventFinishedWithException(getErrorMsg().c_str());
throw;
}
}
virtual void AddRelatedBlobInfo(EnforceNotMet* err) {
CAFFE_ENFORCE(
isLegacyOperator(),
"AddRelatedBlobInfo(err) not supported for operators exported to c10.");
if (!has_debug_def()) {
return;
}
bool found_input;
if (err->caller() != nullptr) {
for (size_t i = 0; i < inputs_.size(); i++) {
if (inputs_[i]->GetRaw() == err->caller()) {
found_input = true;
err->AppendMessage(
"\n** while accessing input: " + debug_def().input(i));
break;
}
}
for (size_t i = 0; i < outputs_.size(); i++) {
if (outputs_[i]->GetRaw() == err->caller()) {
if (found_input) {
err->AppendMessage("\n OR ");
}
err->AppendMessage(
"\n** while accessing output: " + debug_def().output(i));
break;
}
}
}
}
virtual std::string debug_info_string() const {
return "";
}
inline const OperatorDef& debug_def() const {
CAFFE_ENFORCE(has_debug_def(), "operator_def was null!");
return *operator_def_;
}
inline void set_debug_def(
const std::shared_ptr<const OperatorDef>& operator_def) {
operator_def_ = operator_def;
}
inline bool has_debug_def() const {
return operator_def_ != nullptr;
}
public:
void RecordLastFailedOpNetPosition() {
if (net_position_ != kNoNetPositionSet) {
VLOG(1) << "Operator with id " << net_position_ << " failed";
operator_ws_->last_failed_op_net_position = net_position_;
} else {
VLOG(1) << "Failed operator doesn't have id set";
}
}
int net_position() const {
return net_position_;
}
void set_net_position(int idx) {
net_position_ = idx;
}
const DeviceOption& device_option() const {
return device_option_;
}
const Event& event() const {
CAFFE_ENFORCE(event_, "Event is disabled");
return *event_;
}
Event& event() {
CAFFE_ENFORCE(event_, "Event is disabled");
return *event_;
}
void ResetEvent() {
if (event_) {
event_->Reset();
}
}
void DisableEvent() {
event_ = nullptr;
}
bool IsEventDisabled() const {
return !event_;
}
// Internal API invoked by observers. Normal callers shouldn't invoke it.
virtual void SyncDeviceBarrierForObservers() {
CAFFE_NOT_IMPLEMENTED;
}
// Checks whether stream is ready to execute new computation,
// used in stream allocation optimization to skip stream that is currently
// busy. Depends on context and operator's device, returns true by default
virtual bool IsStreamFree(int /* unused */) const {
return true;
}
const std::string& type() const {
return type_;
}
void annotate_engine(const std::string& engine) {
engine_ = engine;
}
const std::string& engine() const {
return engine_;
}
void SetExecutorHelper(ExecutorHelper* helper) {
helper_ = helper;
}
ExecutorHelper* GetExecutorHelper() const {
return helper_;
}
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
c10::List<at::Tensor> move_newstyle_outputs() && {
return std::move(newstyle_outputs_);
}
#endif
public:
static const int kNoNetPositionSet = -1;
private:
Workspace* operator_ws_;
std::shared_ptr<const OperatorDef> operator_def_;
DeviceOption device_option_;
std::string engine_;
std::string type_;
vector<const Blob*> inputs_;
vector<Blob*> outputs_;
// Preferably use c10::optional, but nvcc doesn't work
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
std::unique_ptr<const c10::FunctionSchema> fn_schema_;
vector<c10::IValue> newstyle_inputs_;
c10::List<at::Tensor> newstyle_outputs_;
#endif
// HACK
// We preserve the fact that Output() returns Tensor*
// by storing Tensor in a vector owned by the
// operator.
vector<caffe2::Tensor> input_tensors_;
vector<caffe2::Tensor> output_tensors_;
int input_size_;
int net_position_{kNoNetPositionSet};
ExecutorHelper* helper_ = nullptr;
protected:
virtual void RecordEvent(const char* /*err_msg*/ = nullptr) {
CAFFE_NOT_IMPLEMENTED;
}
void SetEventFinished(const char* err_msg = nullptr) {
if (event_) {
event_->SetFinished(err_msg);
}
}
void SetEventFinishedWithException(const char* err_msg = nullptr) {
if (event_) {
event_->SetFinishedWithException(err_msg);
}
}
std::string getErrorMsg() {
if (has_debug_def()) {
return "Error from operator: " + ProtoDebugString(debug_def());
} else {
return "Error from operator: no op def";
}
}
c10::optional<int> argumentIndexWithName(const std::string& name) const;
// An event used by asynchronous execution.
std::unique_ptr<Event> event_;
C10_DISABLE_COPY_AND_ASSIGN(OperatorBase);
};
template <>
inline NetDef OperatorBase::GetSingleArgument<NetDef>(
const std::string& name,
const NetDef& default_value) const {
if (isLegacyOperator()) {
CAFFE_ENFORCE(operator_def_, "operator_def was null!");
return ArgumentHelper::GetSingleArgument<OperatorDef, NetDef>(
*operator_def_, name, default_value);
}
CAFFE_THROW("Cannot get NetDefs from IValue");
return NetDef();
}
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
template <>
inline vector<int> OperatorBase::GetVectorFromIValueList<int>(
const c10::IValue& value) const {
auto vs = value.toIntVector();
vector<int> out;
out.reserve(vs.size());
for (int64_t v : vs) {
out.emplace_back(v);
}
return out;
}
template <>
inline vector<float> OperatorBase::GetVectorFromIValueList<float>(
const c10::IValue& value) const {
const auto& vs = value.toDoubleVector();
vector<float> out;
out.reserve(vs.size());
for (double v : vs) {
out.emplace_back(v);
}
return out;
}
template <>
inline vector<string> OperatorBase::GetVectorFromIValueList<string>(
const c10::IValue& value) const {
CAFFE_THROW("Cannot extract vector<string> from ivalue.");
vector<string> out;
return out;
}
// We need this specialisation because IValue based lists don't support
// int16_t. We need to load it as List<int64_t> and transform to int16_t.
template <>
inline vector<int16_t> OperatorBase::GetVectorFromIValueList<int16_t>(
const c10::IValue& value) const {
auto list = value.template to<c10::List<int64_t>>();
std::vector<int16_t> result;
result.reserve(list.size());
for (int64_t elem : list) {
result.push_back(static_cast<int16_t>(elem));
}
return result;
}
#endif
// OP_SINGLE_ARG provides a shorter initialization choice for initialization of
// member variables for the class constructors.
// This is a workaround for CUDA9.2 and GCC7
#if defined(CUDART_VERSION) && CUDART_VERSION >= 9020 && __GNUC__ >= 7
#define OP_SINGLE_ARG(type, name, variable, default) \
variable(this->template GetSingleArgument<type>(name, (default)))
#else
#define OP_SINGLE_ARG(type, name, variable, default) \
variable(OperatorBase::GetSingleArgument<type>(name, (default)))
#endif
// INPUT_TAGS and OUTPUT_TAGS are optional features to name the indices of the
// operator's inputs and outputs, in order to avoid confusion. For example, for
// a fully convolution layer that has input, weight and bias, you can define its
// input tags as:
// INPUT_TAGS(INPUT, WEIGHT, BIAS);
// And in the code, instead of doing
// auto& weight = Input(1);
// you can now do
// auto& weight = Input(WEIGHT);
// to make it more clear.
#define INPUT_TAGS(first_input, ...) \
enum _InputTags { first_input = 0, __VA_ARGS__ }
#define OUTPUT_TAGS(first_input, ...) \
enum _OutputTags { first_input = 0, __VA_ARGS__ }
template <typename T>
inline vector<T> OperatorBase::GetRepeatedArgument(
const string& name,
const vector<T>& default_value) const {
if (isLegacyOperator()) {
CAFFE_ENFORCE(operator_def_, "operator_def was null!");
return ArgumentHelper::GetRepeatedArgument<OperatorDef, T>(
*operator_def_, name, default_value);
}
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
auto index = argumentIndexWithName(name);
CAFFE_ENFORCE(index.has_value(), "Couldn't get index for argument!", name);
const auto& value = newstyle_inputs_[index.value()];
return GetVectorFromIValueList<T>(value);
#else
CAFFE_THROW("Non-legacy operators are not legal in xplat/caffe2");
#endif
}
// We need this specialisation because IValue based lists don't support
// int16_t. We need to load it as List<int64_t> and transform to int16_t.
template <>
inline vector<int16_t> OperatorBase::GetRepeatedArgument<int16_t>(
const string& name,
const vector<int16_t>& default_value) const {
if (isLegacyOperator()) {
CAFFE_ENFORCE(operator_def_, "operator_def was null!");
return ArgumentHelper::GetRepeatedArgument<OperatorDef, int16_t>(
*operator_def_, name, default_value);
}
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
auto index = argumentIndexWithName(name);
CAFFE_ENFORCE(index.has_value(), "Couldn't get index for argument!", name);
const auto& value = newstyle_inputs_[index.value()];
auto vec = GetVectorFromIValueList<int64_t>(value);
std::vector<int16_t> result;
result.reserve(vec.size());
for (int64_t elem : vec) {
result.push_back(static_cast<int16_t>(elem));
}
return result;
#else
CAFFE_THROW("Non-legacy operators are not legal in xplat/caffe2");
#endif
}
// Operator is the class that you usually want to derive, if your operator will
// run on different devices. You should then implement the RunOnDevice()
// function.
template <class Context>
class Operator : public OperatorBase {
public:
explicit Operator(const OperatorDef& operator_def, Workspace* ws)
: OperatorBase(operator_def, ws), context_(operator_def.device_option()) {
// In the constructor, we switch to the device so that the child class
// constructors will run on that device.
context_.SwitchToDevice();
}
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
explicit Operator(
const c10::FunctionSchema& fn_schema,
std::vector<c10::IValue> inputs,
c10::List<at::Tensor> outputs)
: OperatorBase(fn_schema, std::move(inputs), std::move(outputs)) {
// In the constructor, we switch to the device so that the child class
// constructors will run on that device.
context_.SwitchToDevice();
}
#endif
~Operator() noexcept override {}
/// Retrieve a non-owning reference to the input at position 'idx' for this
/// operator. The returned reference is valid for the duration of the
/// RunOnDevice call. The optional 'type' parameter can be used to assert a
/// required device type for the input (by default, we assert that the tensor
/// is consistent with the device type implied by the Context parameter of an
/// Operator.)
inline const Tensor& Input(
int idx,
DeviceType type = Context::GetDeviceType()) {
return OperatorBase::template Input<Tensor>(idx, type);
}
/// XOutput is a modernized version of Output which returns a Tensor
/// rather than a Tensor* (the raw pointer in the latter case is
/// useless, as Tensor is a pointer type.)
Tensor XOutput(int idx, at::IntArrayRef dims, at::TensorOptions options) {
// We'll default device to the device of the current Operator Context
if (options.device_opt() == c10::nullopt) {
return OperatorBase::XOutputTensor(
idx, dims, options.device(context_.device()));
}
return OperatorBase::XOutputTensor(idx, dims, options);
}
/// Retrieve a non-owning pointer to the output at position 'idx',
/// initializing it to have size 'dims' and properties 'options' if
/// there is no pre-existing output or the pre-existing output does
/// not have the correct options. The returned pointer is valid for
/// the duration of the RunOnDevice call. If device is not explicitly
/// specified in options, we default to allocating output on the
/// current device of the device type implied by the Context parameter
/// of this Operator.
///
/// Note [Operator::Output what?]
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// The contract of Operator::Output is somewhat complex; it is perhaps better
/// understood in terms of what was historically an idiomatic Caffe2 operator
/// implementation:
///
/// void RunOnDevice() override {
/// auto* output = Output(0, output_size, dtype<float>());
/// float* output_ptr = output->data<float>();
/// // write into output_ptr
/// }
///
/// In the simple case, this code does the following things:
///
/// 1. Allocates a new tensor with size 'output_size' and dtype 'float'
/// (and device type whatever the Operator's device type is)
/// 2. "Registers" this tensor as the 0th output tensor of this operator
/// (Caffe2 operators don't "return" outputs; instead, outputs
/// are shoved into an output vector which the executor reads out.)
/// 3. Returns the tensor, so the operator implementation can write
/// the actual output data into the tensor.
///
/// So what's this business with "pre-existing" outputs? Caffe2
/// commonly applies an optimization whereby it reuses tensors on
/// subsequent runs of operators in a graph. It doesn't know ahead
/// of time what intermediate tensors it will need, so the first
/// time it runs a graph it has all of the operators create the outputs
/// necessary (as described above). However, the second time around,
/// it will reuse all of the tensors created from the first time.
/// If they are lucky, this time the Output() call is a no-op and
/// just returns the old tensor.
///
/// However, we cannot /guarantee/ that the output size will be the
/// same the next time the Operator is called; for example, output
/// size may be data dependent and vary between runs. In this case,
/// we have to resize it to the correct size. Resizing is still
/// helpful, as we may be able to fit the output in the same
/// space that was previously used.
///
Tensor* Output(int idx, at::IntArrayRef dims, at::TensorOptions options) {
// We'll default device to the device of the current Operator Context
if (options.device_opt() == c10::nullopt) {
return OperatorBase::OutputTensor(
idx, dims, options.device(context_.device()));
}
return OperatorBase::OutputTensor(idx, dims, options);
}
/// Legacy: please consider using the version of Output() which also takes
/// dtype and size as arguments.
inline Tensor* Output(int idx, DeviceType type = Context::GetDeviceType()) {
return OperatorBase::template Output<Tensor>(idx, type);
}
/// Get the output Tensor of an operator (allocating it if it is not
/// already initialized), and copy the contents of src into it.
/// You probably don't actually want to use this function (the fact
/// that you have a Tensor to copy from is probably a mistake:
/// you should have written the output into the output tensor,
/// from Output, directly in the first place), but this method
/// is situationally useful.
Tensor* OutputTensorCopyFrom(
int idx,
at::TensorOptions options,
const Tensor& src,
bool async = false) {
if (options.device_opt() == c10::nullopt) {
return OperatorBase::OutputTensorCopyFrom(
idx, options.device(context_.device()), src, async);
}
return OperatorBase::OutputTensorCopyFrom(idx, options, src, async);
}
void WaitEvent(const Event& ev, int stream_id = -1) final {
if (stream_id >= 0) {
context_.SwitchToDevice(stream_id);
}
context_.WaitEvent(ev);
}
void WaitEvents(const std::vector<const Event*>& events, int stream_id = -1)
final {
if (stream_id >= 0) {
context_.SwitchToDevice(stream_id);
}
for (const auto& ev : events) {
context_.WaitEvent(*ev);
}
}
// The run function of Operator switches to the device, and then carries out
// the actual computation with RunOnDevice(). You should implement RunOnDevice
// instead of Run().
// Note: Run does not update operator's event and can be used only with
// non-async executors that do not rely on events
bool Run(int stream_id = 0) final {
try {
StartAllObservers();
context_.SwitchToDevice(stream_id);
// Clear floating point exception flags before RunOnDevice. We will test
// exception flags afterwards, and raise an error if an exception has
// happened.
if (FLAGS_caffe2_operator_throw_if_fp_exceptions ||
FLAGS_caffe2_operator_throw_if_fp_overflow_exceptions) {
std::feclearexcept(FE_ALL_EXCEPT);
}