forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathops.cpp
2915 lines (2695 loc) · 101 KB
/
ops.cpp
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
#include <torch/csrc/jit/runtime/static/ops.h>
#include <ATen/CPUFunctions.h>
#include <ATen/InferSize.h>
#include <ATen/NativeFunctions.h>
#include <ATen/Parallel.h>
#include <ATen/ScalarOps.h>
#include <ATen/TensorUtils.h>
#include <ATen/cpu/vec/functional.h>
#include <ATen/cpu/vec/vec.h>
#include <ATen/native/Fill.h>
#include <ATen/native/IndexingUtils.h>
#include <ATen/native/Resize.h>
#include <ATen/native/SharedReduceOps.h>
#include <ATen/native/TensorAdvancedIndexing.h>
#include <ATen/native/TensorConversions.h>
#include <ATen/native/cpu/SerialStackImpl.h>
#include <ATen/native/layer_norm.h>
#include <ATen/native/quantized/cpu/fbgemm_utils.h>
#include <ATen/native/quantized/cpu/qembeddingbag.h>
#include <ATen/native/quantized/cpu/qembeddingbag_prepack.h>
#include <ATen/quantized/QTensorImpl.h>
#include <ATen/quantized/Quantizer.h>
#include <c10/core/ScalarType.h>
#include <c10/core/WrapDimMinimal.h>
#include <c10/util/irange.h>
#include <torch/csrc/jit/ir/constants.h>
#include <torch/csrc/jit/ir/ir.h>
#include <torch/csrc/jit/passes/symbolic_shape_runtime_fusion.h>
#include <torch/csrc/jit/runtime/static/impl.h>
#include <torch/csrc/jit/runtime/static/processed_node_wrapper.h>
#include <torch/csrc/jit/runtime/static/te_wrapper.h>
#include <torch/csrc/jit/runtime/vararg_functions.h>
#include <torch/csrc/jit/tensorexpr/ir.h>
#include <torch/csrc/jit/tensorexpr/ir_simplifier.h>
#include <torch/csrc/jit/tensorexpr/llvm_codegen.h>
#include <torch/csrc/jit/tensorexpr/loopnest.h>
#include <iterator>
#include <mutex>
#include <unordered_map>
#include <ATen/CompositeExplicitAutogradFunctions.h>
C10_DEFINE_bool(
static_runtime_enable_fast_math,
true,
"If on, static runtime may use use optimizations that cause accurary loss "
"vs the jit interpreter");
namespace at {
namespace native {
void repeat_out(at::Tensor& result, const Tensor& self, IntArrayRef repeats) {
TORCH_CHECK(
repeats.size() >= static_cast<size_t>(self.dim()),
"Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor");
// Add new leading dimensions to the tensor if the
// number of target dimensions is larger than the
// number of source dimensions.
int64_t num_new_dimensions = repeats.size() - self.dim();
DimVector padded_size(num_new_dimensions, 1);
padded_size.insert(
padded_size.end(), self.sizes().begin(), self.sizes().end());
DimVector target_size(repeats.size());
bool zero_tensor = false;
for (const auto idx : c10::irange(repeats.size())) {
if (repeats[idx] == 0) {
zero_tensor = true;
}
target_size[idx] = padded_size[idx] * repeats[idx];
}
// return an empty tensor if one of the repeat dimensions is zero
at::native::resize_(result, target_size, c10::nullopt);
if (zero_tensor) {
return;
}
Tensor xtensor = at::compositeexplicitautograd::expand(self, padded_size);
Tensor urtensor = at::native::alias(result);
for (const auto i : c10::irange(xtensor.dim())) {
// can't unfold with step 0, so make sure step is at least 1
// (it doesn't matter what it is in that case, because the size is 0).
urtensor = urtensor.unfold(
i, xtensor.size(i), std::max<int64_t>(xtensor.size(i), 1));
}
at::native::copy_(urtensor, xtensor.expand_as(urtensor));
}
// copy version of view ops
at::Tensor& reshape_copy_out(
at::Tensor& out,
const at::Tensor& self,
const at::DimVector& proposed_shape,
bool infer_size) {
const auto& shape = infer_size
? at::infer_size_dv(proposed_shape, self.numel())
: proposed_shape;
at::native::resize_(out, shape, c10::nullopt);
auto self_contig = self.expect_contiguous();
size_t nbytes = self.nbytes();
if (nbytes == 0) {
return out;
}
const void* self_data = self_contig->data_ptr();
void* out_data = out.data_ptr();
memcpy(out_data, self_data, nbytes);
return out;
}
at::Tensor& flatten_copy_out(
at::Tensor& out,
const at::Tensor& self,
int64_t start_dim,
int64_t end_dim) {
start_dim =
start_dim < 0 ? c10::maybe_wrap_dim(start_dim, self.dim()) : start_dim;
end_dim = end_dim < 0 ? c10::maybe_wrap_dim(end_dim, self.dim()) : end_dim;
TORCH_CHECK(
start_dim <= end_dim,
"flatten() has invalid args: start_dim cannot come after end_dim");
if (self.dim() == 0) {
return reshape_copy_out(out, self, at::DimVector{1}, false);
}
if (start_dim == end_dim) {
auto shape = at::DimVector{self.sizes()};
return reshape_copy_out(out, self, shape, false);
}
// We don't want to infer_size on the entire shape, because that can give us
// an extra degree of freedom we don't want; for example, consider shape [0,
// 1, 3, 0], with start_dim=1, end_dim=2. It's clear we want result shape [0,
// 3, 0] but passing [0, -1, 0] to infer_size means the -1 can take on any
// value and satisfy the constraints.
auto iter = self.sizes().data();
auto slice_numel = std::accumulate(
iter + start_dim,
iter + end_dim + 1,
static_cast<int64_t>(1),
// NOLINTNEXTLINE(modernize-use-transparent-functors)
std::multiplies<int64_t>());
at::DimVector shape;
shape.reserve(self.dim() - end_dim + start_dim);
for (const auto i : c10::irange(start_dim)) {
shape.push_back(self.sizes()[i]);
}
shape.push_back(slice_numel);
for (int64_t i = end_dim + 1; i < self.dim(); i++) {
shape.push_back(self.sizes()[i]);
}
return reshape_copy_out(out, self, shape, false);
}
namespace {
// This is annoying and sily, but it's solving a real problem: the
// _MSC_VER version causes an ICE on our old clang5 builds. The
// non-_MSC_VER version is a syntax error according to MSVC. Use the
// appropriate version depending on if we're MSVC or not.
#define TO_COPY_OUT_FAST_PATH_LOGIC(out, self, self_t) \
do { \
const auto N = self.numel(); \
const auto self_data = self.data_ptr<self_t>(); \
AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( \
kHalf, \
kBFloat16, \
kBool, \
out.scalar_type(), \
"to_copy_out_inner_loop", \
[&]() { \
const auto out_data = out.data_ptr<scalar_t>(); \
for (const auto idx : c10::irange(N)) { \
/* NOLINTNEXTLINE(bugprone-signed-char-misuse) */ \
out_data[idx] = static_cast<scalar_t>(self_data[idx]); \
} \
}); \
} while (0)
#ifdef _MSC_VER
template <typename T>
void to_copy_out_fast_path(Tensor& out, const Tensor& self) {
TO_COPY_OUT_FAST_PATH_LOGIC(out, self, T);
}
#define TO_COPY_OUT_FAST_PATH_BODY(out, self) \
to_copy_out_fast_path<scalar_t>(out, self)
#else
#define TO_COPY_OUT_FAST_PATH_BODY(out, self) \
using self_t = scalar_t; \
TO_COPY_OUT_FAST_PATH_LOGIC(out, self, self_t)
#endif
} // namespace
at::Tensor& to_copy_out(
Tensor& out,
const Tensor& self,
bool non_blocking,
bool copy_strides,
c10::optional<MemoryFormat> memory_format) {
if (copy_strides) {
at::native::resize_impl_cpu_(
out.unsafeGetTensorImpl(), self.sizes(), self.strides());
} else {
at::native::resize_(out, self.sizes(), c10::nullopt);
}
auto is_unsupported_dtype = [](ScalarType t) {
#define TORCH_OPS_UNSUPPORTED_TYPE(_, type) \
case k##type: \
return true;
switch (t) {
AT_FORALL_QINT_TYPES(TORCH_OPS_UNSUPPORTED_TYPE)
AT_FORALL_COMPLEX_TYPES(TORCH_OPS_UNSUPPORTED_TYPE)
default:
return false;
}
#undef TORCH_OPS_UNSUPPORTED_TYPE
};
// Fast path: can we just copy the data ourselves? Avoids creating a
// TensorIterator in at::native::copy_, which is relatively
// expensive.
if (self.is_contiguous() && !non_blocking &&
// Did the user request us to make a copy that isn't contiguous?
(memory_format == c10::nullopt ||
memory_format == c10::MemoryFormat::Preserve ||
memory_format == c10::MemoryFormat::Contiguous) &&
// CopyKernel.cpp handles this case specially, so let's not mess
// with it.
!self.is_neg() && !is_unsupported_dtype(self.dtype().toScalarType()) &&
!is_unsupported_dtype(out.dtype().toScalarType()) &&
!(
// FBGEMM optimization might kick in, don't interfere with
// that.
(self.dtype() == kFloat && out.dtype() == kHalf) ||
(self.dtype() == kHalf && out.dtype() == kFloat))) {
AT_DISPATCH_ALL_TYPES_AND3(
kHalf, kBFloat16, kBool, self.scalar_type(), "to_copy_out", [&]() {
TO_COPY_OUT_FAST_PATH_BODY(out, self);
});
return out;
}
at::native::copy_(out, self, non_blocking);
return out;
}
Tensor& linear_out(
Tensor& output,
const Tensor& input,
const Tensor& weight,
const c10::optional<Tensor>& bias_opt) {
TORCH_CHECK(!input.is_mkldnn());
auto bias = bias_opt.has_value()
? c10::MaybeOwned<Tensor>::borrowed(*bias_opt)
: c10::MaybeOwned<Tensor>::owned(c10::in_place);
if (input.dim() == 2 && bias->defined()) {
// Fused op is marginally faster.
return at::cpu::addmm_out(output, *bias, input, weight.t());
}
at::native::matmul_out(input, weight.t(), output);
if (bias->defined()) {
at::cpu::add_(output, *bias);
}
return output;
}
Tensor& c2_argmin_out(
Tensor& output,
const Tensor& input,
const int64_t dim,
const bool keepdim) {
const auto ndim = input.dim();
int64_t dim_ = maybe_wrap_dim(dim, ndim);
TORCH_CHECK(dim_ >= 0 && dim_ < ndim);
const auto in_dims = input.sizes();
c10::SmallVector<int64_t, 5> out_dims;
out_dims.reserve(ndim);
int prev_size = 1;
int next_size = 1;
for (int i = 0; i < dim_; ++i) {
out_dims.push_back(in_dims[i]);
prev_size *= in_dims[i];
}
if (keepdim) {
out_dims.push_back(1);
}
for (auto i = dim_ + 1; i < ndim; ++i) {
out_dims.push_back(in_dims[i]);
next_size *= in_dims[i];
}
at::native::resize_(output, out_dims, c10::nullopt);
const auto n = in_dims[dim_];
if (next_size == 1) {
AT_DISPATCH_ALL_TYPES_AND2(
kHalf, kBFloat16, input.scalar_type(), "argmin_input", [&]() {
const auto in_ptr = input.data_ptr<scalar_t>();
const auto out_ptr = output.data_ptr<int64_t>();
// input is a [prev_size, n] tensor.
// output is a [prev_size,] tensor.
// Thus, access is contiguous/coalesced.
for (int i = 0; i < prev_size; ++i) {
auto v = std::min_element(
in_ptr + i * n,
in_ptr + (i + 1) * n,
[](scalar_t a, scalar_t b) {
// if a is nan, then a is *less* than b with LessOrNan
// semantics
if (at::_isnan(a)) {
return true;
}
// if a is not nan and b is nan, then a is not less than b
// with LessOrNan semantics otherwise, act normally. If `b` is
// NaN then a < b will always return false, so this is
// equivalent to the first snippet.
return a < b;
});
out_ptr[i] = std::distance(in_ptr + i * n, v);
}
});
} else {
AT_DISPATCH_ALL_TYPES_AND2(
kHalf, kBFloat16, input.scalar_type(), "argmin_input", [&]() {
const auto less_or_nan = native::detail::LessOrNan<scalar_t>{};
const auto in_ptr = input.data_ptr<scalar_t>();
const auto out_ptr = output.data_ptr<int64_t>();
std::memset(out_ptr, 0, prev_size * next_size * sizeof(int64_t));
for (int i = 0; i < prev_size; ++i) {
const scalar_t* cur_in_ptr = in_ptr + i * n * next_size + next_size;
for (int k = 1; k < n; ++k) {
for (int j = 0; j < next_size; ++j) {
int64_t* cur_out_ptr = out_ptr + i * next_size + j;
if (less_or_nan(
*cur_in_ptr,
in_ptr
[i * n * next_size + *cur_out_ptr * next_size + j],
*cur_out_ptr,
k)) {
*cur_out_ptr = k;
}
++cur_in_ptr;
}
}
}
});
}
return output;
}
at::Tensor& dequantize_copy_out(Tensor& out, const Tensor& self) {
if (C10_UNLIKELY(!self.is_quantized())) {
// fallback to dequantize_cpu equivalent case: make sure out is at::kFloat
DCHECK(out.scalar_type() == kFloat);
return at::native::to_copy_out(out, self, false, false, c10::nullopt);
}
return get_qtensorimpl(self)->quantizer()->dequantize_out(out, self);
}
} // namespace native
} // namespace at
namespace torch {
namespace jit {
C10_DEFINE_REGISTRY(SROperatorRegistry, SROperatorFunctor);
bool opIsRegistered(const c10::Symbol& op_name) {
const std::string name(op_name.toQualString());
return SROperatorRegistry()->Has(name);
}
bool disableUnsafeMathOp(const char* op_name) {
if (FLAGS_static_runtime_enable_fast_math) {
return false;
}
// This list contains ops that use caffe2 math library or use NNC that does
// not guarantee bit exactness vs the jit interpreter. Note aten::relu is not
// included even though it uses NNC because the results of relu should always
// match.
static const FastSet<std::string> fast_ops{
"aten::add", "aten::tanh", "aten::sigmoid", "aten::logit"};
return fast_ops.count(op_name) > 0;
}
SROperator getOutOfPlaceOperation(Node* n) {
auto op_name = n->kind().toQualString();
if (SROperatorRegistry()->Has(op_name) && !disableUnsafeMathOp(op_name)) {
return SROperatorRegistry()->Create(op_name)->Generate(n);
}
return nullptr;
}
// Returns true if the node represents an op with variadic arguments.
bool hasVarArgs(Node* n) {
if (n->kind() == prim::VarConcat || n->kind() == prim::VarStack) {
return true;
}
return false;
}
bool canReuseInputsOutputs(
Node* n,
const FastMap<Node*, bool>& node_has_out_variant) {
auto it = node_has_out_variant.find(n);
if (it != node_has_out_variant.end()) {
return it->second;
}
return getOutOfPlaceOperation(n) != nullptr;
}
// returns true if the producers of the inputs
// to this operations are out of place.
// This means the IValues will not change run to run
bool inputsCanRunOutOfPlace(
Node* n,
const FastMap<Node*, bool>& node_has_out_variant) {
for (auto* input : n->inputs()) {
if (!canReuseInputsOutputs(input->node(), node_has_out_variant)) {
return false;
}
}
return true;
}
bool isOptimizableContainerType(
Node* n,
const FastMap<Node*, bool>& node_has_out_variant) {
const auto& type = n->output()->type();
bool is_supported_type = false;
if (type->kind() == TypeKind::ListType) {
const auto& list_type = type->expectRef<ListType>();
is_supported_type =
list_type.getElementType()->kind() == TypeKind::TensorType;
} else if (type->kind() == TypeKind::TupleType) {
const auto& tuple_type = type->expectRef<TupleType>();
auto types = tuple_type.containedTypes();
const auto& iter =
std::find_if(types.begin(), types.end(), [](const TypePtr& elem) {
return elem->kind() == TypeKind::TensorType;
});
is_supported_type = iter != types.end();
}
return is_supported_type && inputsCanRunOutOfPlace(n, node_has_out_variant);
}
static inline void listConstructSlowPath(
const ListType& list_type,
const size_t size,
ProcessedNode* p_node) {
c10::List<IValue> vals(list_type.getElementType());
vals.reserve(size);
for (const auto i : c10::irange(size)) {
vals.push_back(p_node->Input(i));
}
p_node->Output(0) = vals;
}
bool sr_schema_check_kind(torch::jit::Node* node, c10::Symbol node_kind) {
auto is_match = node->kind() == node_kind;
if (!is_match) {
torch::jit::LogAndDumpSchema(node);
}
return is_match;
}
REGISTER_OPERATOR_FUNCTOR(
prim::ListConstruct,
prim_ListConstruct,
[](Node* n) -> SROperator {
if (!sr_schema_check_kind(n, prim::ListConstruct)) {
return nullptr;
}
const bool can_optimize =
isOptimizableContainerType(n, FastMap<Node*, bool>());
const auto& type = n->output()->type()->expectRef<ListType>();
const size_t size = n->inputs().size();
if (!can_optimize) {
return [&type, size](ProcessedNode* p_node) {
DCHECK(p_node->num_inputs() == size);
listConstructSlowPath(type, size, p_node);
};
}
return [&type, size](ProcessedNode* p_node) {
DCHECK(p_node->num_inputs() == size);
const auto& out_l = p_node->Output(0);
if (!out_l.isNone()) {
return;
}
listConstructSlowPath(type, size, p_node);
};
});
static inline void tupleConstructSlowPath(
const size_t size,
ProcessedNode* p_node) {
// prepare inputs
switch (size) {
case 1:
p_node->Output(0) = c10::ivalue::Tuple::create(p_node->Input(0));
break;
case 2:
p_node->Output(0) =
c10::ivalue::Tuple::create(p_node->Input(0), p_node->Input(1));
break;
case 3:
p_node->Output(0) = c10::ivalue::Tuple::create(
p_node->Input(0), p_node->Input(1), p_node->Input(2));
break;
default: {
std::vector<IValue> vals;
vals.reserve(size);
for (const auto i : c10::irange(size)) {
vals.push_back(p_node->Input(i));
}
p_node->Output(0) = c10::ivalue::Tuple::create(std::move(vals));
break;
}
}
}
REGISTER_OPERATOR_FUNCTOR(
prim::TupleConstruct,
prim_TupleConstruct,
[](Node* n) -> SROperator {
if (!sr_schema_check_kind(n, prim::TupleConstruct)) {
return nullptr;
}
const bool can_optimize =
isOptimizableContainerType(n, FastMap<Node*, bool>());
const size_t size = n->inputs().size();
if (!can_optimize) {
return [size](ProcessedNode* p_node) {
DCHECK(p_node->num_inputs() == size);
tupleConstructSlowPath(size, p_node);
};
}
return [size](ProcessedNode* p_node) {
DCHECK(p_node->num_inputs() == size);
const auto& out_l = p_node->Output(0);
if (!out_l.isNone()) {
return;
}
tupleConstructSlowPath(size, p_node);
};
});
REGISTER_OPERATOR_FUNCTOR(aten::abs, aten_abs, [](Node* n) -> SROperator {
if (!n->matches(torch::schema("aten::abs(Tensor self) -> Tensor"))) {
LogAndDumpSchema(n);
return nullptr;
}
return [](ProcessedNode* p_node) {
const auto& in0_t = p_node->Input(0).toTensor();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = at::native::abs(in0_t);
return;
}
auto& out_t = p_node->Output(0).toTensor();
fastResizeToZero(out_t);
at::native::abs_out(in0_t, out_t);
};
});
REGISTER_OPERATOR_FUNCTOR(aten::mul, aten_mul, [](Node* n) -> SROperator {
if (!n->matches(torch::schema(
"aten::mul.Tensor(Tensor self, Tensor other) -> Tensor"))) {
LogAndDumpSchema(n);
return nullptr;
}
return [](ProcessedNode* p_node) {
const auto& in0_t = p_node->Input(0).toTensor();
const auto& in1_t = p_node->Input(1).toTensor();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = at::cpu::mul(in0_t, in1_t);
return;
}
auto& out_t = p_node->Output(0).toTensor();
fastResizeToZero(out_t);
at::cpu::mul_out(out_t, in0_t, in1_t);
};
});
REGISTER_OPERATOR_FUNCTOR(aten::addmm, aten_addmm, [](Node* n) -> SROperator {
if (!n->matches(torch::schema(
"aten::addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor"))) {
LogAndDumpSchema(n);
return nullptr;
}
return [](ProcessedNode* p_node) {
const auto& in0_t = p_node->Input(0).toTensor();
const auto& in1_t = p_node->Input(1).toTensor();
const auto& in2_t = p_node->Input(2).toTensor();
const auto in3_s = p_node->Input(3).toScalar();
const auto in4_s = p_node->Input(4).toScalar();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = at::cpu::addmm(in0_t, in1_t, in2_t, in3_s, in4_s);
return;
}
auto& out_t = p_node->Output(0).toTensor();
fastResizeToZero(out_t);
at::cpu::addmm_out(out_t, in0_t, in1_t, in2_t, in3_s, in4_s);
};
});
#ifdef FBCODE_CAFFE2
// Disable externally to avoid MSVC errors in open-source CI
REGISTER_OPERATOR_FUNCTOR(
static_runtime::clamp_nan_to_num,
static_runtime_clamp_nan_to_num,
[](Node* n) -> SROperator {
if (!sr_schema_check(
n,
"static_runtime::clamp_nan_to_num(Tensor input, Scalar? min, Scalar? max, float? nan, float? posinf, float? posinf) -> Tensor")) {
return nullptr;
}
auto clamp_min_ival_opt = toIValue(n->input(1));
auto clamp_max_ival_opt = toIValue(n->input(2));
TORCH_CHECK(
clamp_min_ival_opt.has_value() && clamp_max_ival_opt.has_value());
auto clamp_min_opt = clamp_min_ival_opt->toOptional<at::Scalar>();
auto clamp_max_opt = clamp_max_ival_opt->toOptional<at::Scalar>();
TORCH_CHECK(clamp_min_opt.has_value() && clamp_max_opt.has_value());
return [te = createClampNanToNum(),
clamp_min = clamp_min_opt->to<float>(),
clamp_max =
clamp_max_opt->to<float>()](ProcessedNode* p_node) mutable {
const auto& in0_t = p_node->Input(0).toTensor();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = create_empty_from(in0_t);
}
auto& out_t = p_node->Output(0).toTensor();
fastResizeToZero(out_t);
auto in3_s = p_node->Input(3).toOptional<double>();
if (!te || !te->checkInput<float>(in0_t)) {
at::cpu::nan_to_num_out(
out_t,
at::cpu::clamp(in0_t, clamp_min, clamp_max),
in3_s,
c10::nullopt,
c10::nullopt);
return;
}
at::native::resize_(out_t, in0_t.sizes(), c10::nullopt);
auto output_size = in0_t.numel();
// This might be UB if in3_s is absurdly large, but most implementations
// just turn it into `inf` in that case. The PyTorch core nan_to_num
// kernel just static_cast()s the limits to the destination type, so
// we'll ignore overflow issues here as well.
auto nan = in3_s.has_value() ? static_cast<float>(*in3_s) : 0.f;
te->call(
{out_t.data_ptr(),
in0_t.data_ptr(),
&clamp_min,
&clamp_max,
&nan,
&output_size});
};
});
#endif
REGISTER_OPERATOR_FUNCTOR(aten::clamp, aten_clamp, [](Node* n) -> SROperator {
if (n->matches(torch::schema(
"aten::clamp(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor"))) {
return [te = createClamp()](ProcessedNode* p_node) {
const auto& in0_t = p_node->Input(0).toTensor();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = create_empty_from(in0_t);
}
auto& out_t = p_node->Output(0).toTensor();
fastResizeToZero(out_t);
auto in1_s = p_node->Input(1).toOptional<at::Scalar>();
auto in2_s = p_node->Input(2).toOptional<at::Scalar>();
if (!te->checkInput<float>(in0_t)) {
at::cpu::clamp_out(out_t, in0_t, in1_s, in2_s);
return;
}
at::native::resize_(out_t, in0_t.sizes(), c10::nullopt);
auto output_size = in0_t.numel();
auto min = in1_s.has_value() ? in1_s->toFloat()
: -std::numeric_limits<float>::infinity();
auto max = in2_s.has_value() ? in2_s->toFloat()
: std::numeric_limits<float>::infinity();
te->call({out_t.data_ptr(), in0_t.data_ptr(), &min, &max, &output_size});
};
}
if (n->matches(
"aten::clamp.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor")) {
return [](ProcessedNode* p_node) {
const auto& in0_t = p_node->Input(0).toTensor();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = create_empty_from(in0_t);
}
auto& out_t = p_node->Output(0).toTensor();
fastResizeToZero(out_t);
auto in1_t = p_node->Input(1).toOptional<at::Tensor>();
auto in2_t = p_node->Input(2).toOptional<at::Tensor>();
at::cpu::clamp_out(out_t, in0_t, in1_t, in2_t);
};
}
LogAndDumpSchema(n);
return nullptr;
});
REGISTER_OPERATOR_FUNCTOR(aten::bmm, aten_bmm, [](Node* n) -> SROperator {
if (!n->matches(
torch::schema("aten::bmm(Tensor self, Tensor mat2) -> Tensor"))) {
LogAndDumpSchema(n);
return nullptr;
}
return [](ProcessedNode* p_node) {
const auto& in0_t = p_node->Input(0).toTensor();
const auto& in1_t = p_node->Input(1).toTensor();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = create_empty_from(in0_t);
}
auto& out_t = p_node->Output(0).toTensor();
fastResizeToZero(out_t);
at::cpu::bmm_out(out_t, in0_t, in1_t);
};
});
REGISTER_OPERATOR_FUNCTOR(aten::nan_to_num, aten_nan_to_num, [](Node* n) -> SROperator {
if (!n->matches(torch::schema(
"aten::nan_to_num(Tensor self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor"))) {
LogAndDumpSchema(n);
return nullptr;
}
return [](ProcessedNode* p_node) {
const auto& in0_t = p_node->Input(0).toTensor();
const auto in1_d = p_node->Input(1).toOptional<double>();
const auto in2_d = p_node->Input(2).toOptional<double>();
const auto in3_d = p_node->Input(3).toOptional<double>();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = at::native::nan_to_num(in0_t, in1_d, in2_d, in3_d);
return;
}
auto& out_t = p_node->Output(0).toTensor();
fastResizeToZero(out_t);
at::native::nan_to_num_out(in0_t, in1_d, in2_d, in3_d, out_t);
};
});
namespace {
void varStackSerialOut(
at::Tensor& result,
int64_t dim,
const ProcessedNodeInputWrapper& inputs) {
auto result_sizes = inputs[0].sizes().vec();
result_sizes.insert(result_sizes.begin() + dim, inputs.size());
at::native::resize_(result, result_sizes);
AT_DISPATCH_FLOATING_TYPES(
result.scalar_type(), "varstack_serial_kernel", [&]() {
at::native::detail::
stack_serial_kernel_impl<scalar_t, ProcessedNodeInputWrapper>(
result, inputs, dim);
});
}
std::vector<at::Tensor> unsqueezeVarStackInputs(
const ProcessedNodeInputWrapper& inputs,
const int64_t dim) {
std::vector<at::Tensor> result;
result.reserve(inputs.size());
for (const auto i : c10::irange(inputs.size())) {
result.push_back(at::native::unsqueeze(inputs[i], dim));
}
return result;
}
void varstackNonserialOut(
at::Tensor& result,
const int64_t dim,
const ProcessedNodeInputWrapper& inputs) {
std::vector<at::Tensor> inputs_unsqueezed =
unsqueezeVarStackInputs(inputs, dim);
fastResizeToZero(result);
at::cpu::cat_outf(inputs_unsqueezed, dim, result);
}
void varStackFastOut(
at::Tensor& out,
int64_t dim,
const ProcessedNodeInputWrapper& inputs) {
DCHECK(out.is_contiguous());
const auto num_inputs = static_cast<int64_t>(inputs.size());
TORCH_CHECK(num_inputs > 0, "stack expects a non-empty list of tensors");
const auto first_tensor_shape = inputs[0].sizes();
for (const auto i : c10::irange(1, num_inputs)) {
const auto shape = inputs[i].sizes();
TORCH_CHECK(
shape == first_tensor_shape,
"Stack expects each tensor to be the same size, but got ",
first_tensor_shape,
" at position 0 and ",
shape,
" at position ",
i);
}
const std::array<int64_t, 2> output_size = (dim == 0 || dim == -2)
? std::array<int64_t, 2>{num_inputs, 1}
: std::array<int64_t, 2>{1, num_inputs};
at::native::resize_(out, output_size, c10::nullopt);
AT_DISPATCH_ALL_TYPES(out.scalar_type(), "varStackFastOut", [&]() {
auto* out_data = out.data_ptr<scalar_t>();
for (const auto i : c10::irange(num_inputs)) {
auto& tensor = inputs[i];
auto* input_ptr = tensor.data_ptr<scalar_t>();
out_data[i] = *input_ptr;
}
});
}
bool inputsAreScalars(const ProcessedNodeInputWrapper& inputs) {
// All stack inputs should have the same size, so we only check
// the first one. If this isn't true, an exception will be thrown
// in the VarStack implementation
const auto& first_tensor = inputs[0];
return first_tensor.sizes()[0] == 1 && first_tensor.dim() == 1;
}
void varStackOut(ProcessedNode& pnode, int64_t dim) {
const auto num_inputs = pnode.num_inputs();
TORCH_CHECK(num_inputs > 1, "stack expects a non-empty list of tensors");
dim = c10::maybe_wrap_dim(dim, pnode.Input(0).toTensor().dim() + 1);
auto inputs = ProcessedNodeInputWrapper(pnode);
auto& output = pnode.Output(0).toTensor();
if (output.is_contiguous() && inputsAreScalars(inputs)) {
varStackFastOut(output, dim, inputs);
return;
}
bool can_use_serial = at::native::detail::CanUseNativeSerialStack<
ProcessedNodeInputWrapper,
/*skip_overlap_check*/ true>::call(output, inputs, dim);
if (can_use_serial) {
varStackSerialOut(output, dim, inputs);
return;
}
varstackNonserialOut(output, dim, inputs);
}
} // namespace
// Split out into a function to appease MSVC's pre-processor
SROperator aten_stack(Node* n) {
if (!n->matches(torch::schema(
"aten::stack(Tensor[] tensors, int dim=0) -> Tensor"))) {
LogAndDumpSchema(n);
return nullptr;
}
return [](ProcessedNode* p_node) {
const auto inputs = p_node->Input(0).toTensorVector();
TORCH_CHECK(inputs.size() > 0, "stack expects non-empty tensor list");
const auto dim = p_node->Input(1).toInt();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = at::native::_stack_cpu(inputs, dim);
return;
}
auto& out_t = p_node->Output(0).toTensor();
fastResizeToZero(out_t);
at::native::_stack_out_cpu(inputs, dim, out_t);
};
}
REGISTER_OPERATOR_FUNCTOR(aten::stack, aten_stack, aten_stack);
REGISTER_OPERATOR_FUNCTOR(
prim::VarStack,
prim_VarStack,
[](Node* n) -> SROperator {
if (!sr_schema_check_kind(n, prim::VarStack)) {
return nullptr;
}
return [](ProcessedNode* p_node) {
const size_t num_inputs = p_node->num_inputs();
const auto dim = p_node->Input(num_inputs - 1).toInt();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = create_empty_from(p_node->Input(0).toTensor());
}
varStackOut(*p_node, dim);
};
});
REGISTER_OPERATOR_FUNCTOR(aten::leaky_relu, aten_leaky_relu, [](Node* n) -> SROperator {
if (!n->matches(torch::schema(
"aten::leaky_relu(Tensor self, Scalar negative_slope=0.01) -> Tensor"))) {
LogAndDumpSchema(n);
return nullptr;
}
return [](ProcessedNode* p_node) {
const auto& in0_t = p_node->Input(0).toTensor();
const auto in1_s = p_node->Input(1).toScalar();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = at::cpu::leaky_relu(in0_t, in1_s);
return;
}
auto& out_t = p_node->Output(0).toTensor();
at::cpu::leaky_relu_out(out_t, in0_t, in1_s);
};
});
REGISTER_OPERATOR_FUNCTOR(aten::relu, aten_relu, [](Node* n) -> SROperator {
if (!n->matches(torch::schema("aten::relu(Tensor self) -> Tensor"))) {
LogAndDumpSchema(n);
return nullptr;
}
auto te = createRelu();
return [te](ProcessedNode* p_node) {
const auto& in0_t = p_node->Input(0).toTensor();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = create_empty_from(in0_t);
}
auto& out_t = p_node->Output(0).toTensor();
if (!te->checkInput<float>(in0_t)) {
fastResizeToZero(out_t);
at::cpu::threshold_out(out_t, in0_t, 0, 0);
return;
}
at::native::resize_(out_t, in0_t.sizes(), c10::nullopt);
int64_t nn = in0_t.numel();
te->call({out_t.data_ptr(), in0_t.data_ptr(), &nn});
};
});
REGISTER_OPERATOR_FUNCTOR(aten::tanh, aten_tanh, [](Node* n) -> SROperator {
if (!n->matches(torch::schema("aten::tanh(Tensor self) -> Tensor"))) {
LogAndDumpSchema(n);
return nullptr;
}
auto te = createTanh();
return [te](ProcessedNode* p_node) {
const auto& in0_t = p_node->Input(0).toTensor();
if (p_node->Output(0).isNone()) {
p_node->Output(0) = create_empty_from(in0_t);
}
auto& out_t = p_node->Output(0).toTensor();
if (!te->checkInput<float>(in0_t)) {
fastResizeToZero(out_t);
at::cpu::tanh_out(out_t, in0_t);
return;
}
at::native::resize_(out_t, in0_t.sizes(), c10::nullopt);
int64_t nn = in0_t.numel();
te->call({out_t.data_ptr(), in0_t.data_ptr(), &nn});
};
});
REGISTER_OPERATOR_FUNCTOR(
prim::TensorExprDynamicGroup,
prim_TensorExprDynamicGroup,
[](Node* n) -> SROperator {
if (!sr_schema_check_kind(n, prim::TensorExprDynamicGroup)) {
return nullptr;
}
auto graph = n->g(attr::Subgraph);
Code code(graph, "");
return [code](ProcessedNode* p_node) {
auto num_outputs = p_node->num_outputs();
Stack stack;
if (p_node->Output(0).isNone()) {
stack.reserve(p_node->num_inputs());
} else {
stack.reserve(p_node->num_inputs() + num_outputs);
for (const auto& o : p_node->outputs()) {
stack.emplace_back(o);