-
Notifications
You must be signed in to change notification settings - Fork 21.3k
/
kernel.cpp
2136 lines (1932 loc) · 71.2 KB
/
kernel.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/tensorexpr/kernel.h>
#include <ATen/ExpandUtils.h>
#include <ATen/Parallel.h>
#include <ATen/TensorGeometry.h>
#include <c10/core/ScalarTypeToTypeMeta.h>
#include <c10/util/irange.h>
#include <c10/util/string_utils.h>
#include <torch/csrc/jit/jit_log.h>
#include <torch/csrc/jit/passes/graph_rewrite_helper.h>
#include <torch/csrc/jit/passes/mkldnn_rewrite.h>
#include <torch/csrc/jit/passes/symbolic_shape_runtime_fusion.h>
#include <torch/csrc/jit/tensorexpr/analysis.h>
#include <torch/csrc/jit/tensorexpr/expr.h>
#include <torch/csrc/jit/tensorexpr/graph_opt.h>
#include <torch/csrc/jit/tensorexpr/ir_printer.h>
#include <torch/csrc/jit/tensorexpr/ir_simplifier.h>
#include <torch/csrc/jit/tensorexpr/loopnest.h>
#include <torch/csrc/jit/tensorexpr/loopnest_randomization.h>
#include <torch/csrc/jit/tensorexpr/operators/operators.h>
using namespace torch::jit;
using namespace torch::jit::tensorexpr;
namespace torch::jit::tensorexpr {
std::string buildErrorMessage(const std::string& s) {
static const std::string generic_error_message =
"This error occurred in the fuser. You can turn off the fuser with "
"torch.jit.enable_fusion(False).";
if (s.empty()) {
return generic_error_message;
}
if (s.back() == '.') {
return s + " " + generic_error_message;
}
return s + ". " + generic_error_message;
}
static int te_cuda_pointwise_loop_levels = -1;
static int te_cuda_pointwise_block_count = -1;
static int te_cuda_pointwise_block_size = -1;
static bool fallback_allowed = false;
static bool te_generate_block_code = false;
static bool te_must_use_llvm_on_cpu = true;
static bool cat_wo_conditionals = true; // NOLINT
static bool opt_conditionals = false; // NOLINT
bool setFallbackAllowed(bool value) {
bool old_value = fallback_allowed;
fallback_allowed = value;
return old_value;
}
bool fallbackAllowed() {
static const char* enable_c_str = std::getenv("PYTORCH_TENSOREXPR_FALLBACK");
if (!enable_c_str) {
return fallback_allowed;
}
if (std::string(enable_c_str) == "0") {
return false;
}
return true;
}
static bool fallbackEnforced() {
static const char* enable_c_str = std::getenv("PYTORCH_TENSOREXPR_FALLBACK");
if (tensorexpr::getTEGenerateBlockCode()) {
return false;
}
if (!enable_c_str) {
return fallback_allowed;
}
if (std::string(enable_c_str) == "2") {
return true;
}
return false;
}
static int64_t randomTransformsRequested() {
const char* enable_c_str =
std::getenv("PYTORCH_TENSOREXPR_RANDOM_TRANSFORM_SEED");
if (!enable_c_str) {
return 0;
}
return std::stoi(std::string(enable_c_str));
}
#ifdef TORCH_ENABLE_LLVM
static bool dontUseLLVMFlag() {
static const char* enable_c_str =
std::getenv("PYTORCH_TENSOREXPR_DONT_USE_LLVM");
if (!enable_c_str) {
return false;
}
return std::string(enable_c_str) == "1";
}
#endif
int& getTECudaPointwiseLoopLevels() {
return te_cuda_pointwise_loop_levels;
}
int& getTECudaPointwiseBlockCount() {
return te_cuda_pointwise_block_count;
}
int& getTECudaPointwiseBlockSize() {
return te_cuda_pointwise_block_size;
}
// TODO: Remove this global var
// Ideally Block code gen should be decided
// based on device type in tensor.
bool& getTEGenerateBlockCode() {
return te_generate_block_code;
}
bool& getTEMustUseLLVMOnCPU() {
return te_must_use_llvm_on_cpu;
}
bool& getCatWoConditionals() {
return cat_wo_conditionals;
}
bool& getOptConditionals() {
return opt_conditionals;
}
std::optional<at::Device> pickDeviceType(
const at::ArrayRef<torch::jit::Value*>& inputs) {
std::optional<at::Device> device = c10::nullopt;
for (auto const& input : inputs) {
auto tt = input->type()->cast<TensorType>();
if (tt && tt->device()) {
if (device && *device != *tt->device()) {
return c10::nullopt;
}
device = *tt->device();
}
}
return device;
}
static std::optional<at::Device> pickDeviceType(
const std::shared_ptr<Graph>& graph) {
std::optional<at::Device> device = c10::nullopt;
for (auto const& node : graph->nodes()) {
for (auto const& input : node->inputs()) {
if (auto tt = input->type()->cast<TensorType>()) {
if (auto inputDevice = tt->device()) {
TORCH_INTERNAL_ASSERT(
!device || *device == *inputDevice,
buildErrorMessage(
"Different devices specified for inputs to the fuser."));
device = inputDevice;
}
}
}
}
for (auto const& input : graph->inputs()) {
if (auto tt = input->type()->cast<TensorType>()) {
if (auto inputDevice = tt->device()) {
TORCH_INTERNAL_ASSERT(
!device || *device == *inputDevice,
buildErrorMessage(
"Different devices specified for inputs to the fuser."));
device = inputDevice;
}
}
}
if (!device) {
// By default assume the device is CPU
device = at::kCPU;
}
return device;
}
// If v is a Tensor with concretely-known sizes and dtype, return them, else
// nullopt.
static std::optional<TensorInfo> getTensorInfoJit(torch::jit::Value* v) {
auto const& it = v->type()->cast<TensorType>();
c10::ScalarType dtype = c10::ScalarType::Float;
if (!it) {
return c10::nullopt;
}
if (!it->isComplete()) {
return c10::nullopt;
}
if (it->scalarType()) {
// TODO: ideally we should be strict here and return nullopt if the dtype is
// absent in the JIT IR. We're assuming a default Float dtype for now, until
// dtype propagation is implemented.
dtype = *it->scalarType();
}
auto concrete_sizes = it->sizes().concrete_sizes();
if (!concrete_sizes) {
return c10::nullopt;
}
return TensorInfo{*concrete_sizes, dtype};
}
static std::vector<int64_t> _pair_int(IValue v) {
if (v.isIntList()) {
return v.toIntVector();
} else {
return {v.toInt(), v.toInt()};
}
}
bool isContiguous(const torch::jit::Value* v, at::MemoryFormat memory_format) {
auto const& tt = v->type()->cast<TensorType>();
if (!tt) {
return false;
}
if (!tt->isComplete()) {
return false;
}
auto const& sizes = tt->sizes().concrete_sizes();
auto const& strides = tt->strides().concrete_sizes();
if (!sizes || !strides) {
return false;
}
// Check dimension size first
int ndims = (*sizes).size();
if ((memory_format == at::MemoryFormat::ChannelsLast && ndims != 4) ||
(memory_format == at::MemoryFormat::ChannelsLast3d && ndims != 5)) {
return false;
}
return *strides == TensorType::contiguousStridesOf(*sizes, memory_format);
}
static size_t get_conv_groups_index(const torch::jit::Node* node) {
switch (node->kind()) {
case aten::conv2d:
return 6;
case aten::_convolution:
return 8;
default:
TORCH_CHECK(
false,
"mkldnnPrepackedConvIsSupportedJit expects node kind to be conv2d or _convolution but got ",
node->kind());
}
}
// The fuser only supports conv2d with very specific properties:
// - Static shapes: 4-d input and filter, 1-d bias.
// - Constant strides/padding/dilation/groups
// - Equal padding and strides, dilation == 1.
// - Depthwise (groups == in_channels == out_channels)
// - 3x3 kernel
bool conv2dIsSupportedJit(const torch::jit::Node* node) {
auto const& input = getTensorInfoJit(node->input(0));
auto const& weight = getTensorInfoJit(node->input(1));
auto const& bias = getTensorInfoJit(node->input(2));
auto const& stride = toIValue(node->input(3));
auto const& pad = toIValue(node->input(4));
auto const& dilation = toIValue(node->input(5));
size_t groups_index = get_conv_groups_index(node);
auto const& groups = toIValue(node->input(groups_index));
// Everything should be statically known.
if (!input || !weight || !bias || !stride || !pad || !dilation || !groups) {
GRAPH_DEBUG("some params aren't static");
return false;
}
// All inputs should be contiguous so no transposition is required.
if (!isContiguous(node->input(0)) || !isContiguous(node->input(1)) ||
!isContiguous(node->input(2))) {
GRAPH_DEBUG("conv2dIsSupported: some inputs are not contiguous");
return false;
}
return conv2dIsSupported(
*input,
*weight,
*bias,
_pair_int(*stride),
_pair_int(*pad),
_pair_int(*dilation),
groups->toInt());
}
bool mkldnnPrepackedConvIsSupportedJit(const torch::jit::Node* node) {
#if AT_MKLDNN_ENABLED()
auto const& input = getTensorInfoJit(node->input(0));
auto const& weight = getTensorInfoJit(node->input(1));
auto const& stride = toIValue(node->input(3));
auto const& pad = toIValue(node->input(4));
auto const& dilation = toIValue(node->input(5));
size_t groups_index = get_conv_groups_index(node);
auto const& groups = toIValue(node->input(groups_index));
// Everything should be statically known (bias could be NoneType =
// prim::Constant()).
if (!input || !weight || !stride || !pad || !dilation || !groups) {
GRAPH_DEBUG("some params aren't static");
return false;
}
// Weights and bias should be Constant when using mkldnn backend
if (node->input(1)->node()->kind() != prim::Constant ||
node->input(2)->node()->kind() != prim::Constant) {
GRAPH_DEBUG(
"mkldnnPrepackedConvIsSupported: weight or bias is not Constant");
return false;
}
// Input and weight should be NHWC contiguous.
if (!(isContiguous(node->input(0), at::MemoryFormat::ChannelsLast) &&
isContiguous(node->input(1), at::MemoryFormat::ChannelsLast))) {
GRAPH_DEBUG(
"mkldnnPrepackedConvIsSupported: input or weight is not ChannelsLast contiguous");
return false;
}
return mkldnnPrepackedConvIsSupported(
*input,
*weight,
_pair_int(*stride),
_pair_int(*pad),
_pair_int(*dilation),
groups->toInt());
#endif
return false;
}
bool isConv2d(const Node* node) {
if (node->kind() != aten::_convolution) {
return false;
}
auto const& stride = toIValue(node->input(3));
auto const& pad = toIValue(node->input(4));
auto const& dilation = toIValue(node->input(5));
auto const& transposed = toIValue(node->input(6));
auto const& output_padding = toIValue(node->input(7));
if (!stride || !pad || !dilation || !transposed || !output_padding) {
GRAPH_DEBUG("some params aren't static");
return false;
}
if (stride.value().toIntList().size() != 2 ||
pad.value().toIntList().size() != 2 ||
dilation.value().toIntList().size() != 2 ||
output_padding.value().toIntList().size() != 2) {
GRAPH_DEBUG("Conv not 2d");
return false;
}
if (transposed.value().toBool()) {
GRAPH_DEBUG("transposed Conv");
return false;
}
return true;
}
// The fuser currently only supports matmul of 2D x 2D matrices
bool matmulIsSupported(const torch::jit::Node* node) {
auto const& input0 = getTensorInfoJit(node->input(0));
auto const& input1 = getTensorInfoJit(node->input(1));
// Everything should be statically known.
if (!input0 || !input1) {
GRAPH_DEBUG("matmulIsSupported: Input shapes aren't static");
return false;
}
// Proper ndim for tensor inputs.
if (input0->dims.size() != 2 || input1->dims.size() != 2) {
GRAPH_DEBUG("matmulIsSupported: Unsupported input sizes");
return false;
}
// Inputs should be contiguous, or the TE will needlessly transpose them.
if (!isContiguous(node->input(0)) || !isContiguous(node->input(1))) {
GRAPH_DEBUG("matmulIsSupported: Input shapes are not contiguous");
return false;
}
return true;
}
} // namespace torch::jit::tensorexpr
static at::ScalarType tensorType(BufPtr b) {
return static_cast<at::ScalarType>(b->dtype().scalar_type());
}
ExprHandle TensorExprKernel::constant(const torch::jit::Value* v) {
if (v->node()->kind() == prim::Constant) {
auto val = toIValue(v).value();
if (val.isDouble()) {
return DoubleImm::make(val.toDouble());
} else if (val.isInt()) {
return LongImm::make(val.toInt());
} else if (val.isBool()) {
return BoolImm::make(val.toBool());
} else if (val.isNone()) {
// This is just a placeholder so we don't throw. None-handling
// is operator-specific and should be handled properly in
// the operator-specific lowering code.
return IntImm::make(0);
} else {
throw unsupported_dtype();
}
}
if (!scalars_.count(v)) {
throw malformed_input("no scalar in Constant");
}
return scalars_.at(v);
}
ArgValue TensorExprKernel::toArg(const torch::jit::Value* v) const {
auto vi = scalars_.find(v);
if (vi != scalars_.end()) {
return VarHandle(vi->second);
}
auto ti = bufs_.find(v);
if (ti != bufs_.end()) {
return BufHandle(ti->second);
}
if (v->node()->kind() == prim::ListConstruct) {
std::vector<ArgValue> vec;
for (auto el : v->node()->inputs()) {
vec.push_back(toArg(el));
}
if (vec.empty()) {
return BufList(); // Return arbitrarily typed vector
} else if (std::get_if<BufHandle>(&vec[0])) {
return convertVecArgValue<BufHandle>(vec);
} else if (std::get_if<int64_t>(&vec[0])) {
return convertVecArgValue<int64_t>(vec);
}
throw unsupported_dtype();
}
if (v->node()->kind() == prim::Constant) {
auto val = toIValue(v).value();
if (val.isDouble()) {
return val.toDouble();
} else if (val.isInt()) {
return val.toInt();
} else if (val.isBool()) {
return val.toBool();
} else if (val.isNone()) {
// This is just a placeholder so we don't throw. None-handling
// is operator-specific and should be handled properly in
// the operator-specific lowering code.
return ArgNone();
} else if (val.isIntList()) {
return val.toIntVector();
} else if (val.isDoubleList()) {
return val.toDoubleVector();
} else if (val.isString()) {
return val.toStringRef();
} else {
throw unsupported_dtype(val.type()->str());
}
}
if (!scalars_.count(v)) {
throw malformed_input("no scalar in Constant");
}
return scalars_.at(v);
}
ExprHandle TensorExprKernel::getVarForShape(const c10::ShapeSymbol& ss) {
if (ss.is_static()) {
return LongImm::make(ss.static_size());
}
auto value = ss.value();
auto it = shapeSymbolToVar_.find(value);
if (it == shapeSymbolToVar_.end()) {
VarHandle var("ss" + std::to_string(-value), kLong);
shapeSymbolToVar_.emplace(value, var);
return std::move(var);
}
return it->second;
}
std::vector<ExprHandle> TensorExprKernel::sizesFromSymbolicShape(
const c10::SymbolicShape& shape) {
std::vector<ExprHandle> dims;
auto maybe_rank = shape.rank();
TORCH_INTERNAL_ASSERT(maybe_rank);
auto rank = *maybe_rank;
for (const auto i : c10::irange(rank)) {
dims.push_back(getVarForShape(shape[i]));
}
return dims;
}
std::vector<ExprHandle> TensorExprKernel::sizesForValue(
const torch::jit::Value* v) {
if (known_sizes_.count(v)) {
return known_sizes_.at(v);
}
// If the shape is present in the type info, just extract it from here. No
// need to infer it.
if (v->type()->kind() == TypeKind::TensorType) {
auto tt = v->type()->cast<TensorType>();
return sizesFromSymbolicShape(tt->symbolic_sizes());
}
if (v->type()->isSubtypeOf(*FloatType::get()) ||
v->type()->isSubtypeOf(*BoolType::get()) ||
v->type()->isSubtypeOf(*IntType::get())) {
return {};
}
if (v->type()->isSubtypeOf(*NoneType::get())) {
return {};
}
GRAPH_DEBUG("Unknown sizes for the node: ", *v->node());
GRAPH_DEBUG("Full fusion group graph:\n", *v->node()->owningGraph());
std::string msg = std::string("Unhandled node kind (in sizesForValue): ") +
v->node()->kind().toQualString();
throw malformed_input(msg);
}
static std::optional<ScalarType> findDtypeForValue(const torch::jit::Value* v) {
if (v->type()->kind() == TypeKind::TensorType) {
auto tt = v->type()->cast<TensorType>();
if (tt->scalarType()) {
return static_cast<ScalarType>(*tt->scalarType());
}
}
return tryScalarTypeFromJitType(*v->type());
}
static bool constZeroDimTensorAsScalarArg(
const Value* v,
std::vector<ArgValue>& args) {
if (v->node()->kind() != prim::Constant || !v->type()->cast<TensorType>()) {
return false;
}
const auto t = toIValue(v)->toTensor();
if (!t.sizes().empty()) {
return false;
}
c10::ScalarType dtype = c10::typeMetaToScalarType(t.dtype());
switch (dtype) {
case ScalarType::Float:
args.emplace_back(t.item().toFloat());
return true;
case ScalarType::Long:
args.emplace_back(t.item().toLong());
return true;
default:
std::stringstream ss;
ss << "Unsupported tensor dtype:" << dtype
<< " for converting constant 0-dim Tensor to scalar" << std::endl;
throw unsupported_dtype(ss.str());
}
}
Tensor TensorExprKernel::computeValue(const torch::jit::Value* v) {
auto inputs = v->node()->inputs();
auto op = v->node()->kind();
if (op == aten::rand_like) {
hasRandom_ = true;
}
auto outputType = findDtypeForValue(v);
std::vector<ExprHandle> outputShape = sizesForValue(v);
std::vector<ExprHandle> outputStrides = {};
if (memory_layout_policy_ == MemoryLayoutPolicy::kChannelsLastNdContiguous) {
outputStrides =
c10::fmap<ExprHandle>(make_channels_last_strides(outputShape));
} else {
// Default
outputStrides = c10::fmap<ExprHandle>(make_contiguous_strides(outputShape));
}
std::vector<ArgValue> argInputs;
if (op == prim::ConstantChunk) {
auto const& n = v->node();
argInputs.emplace_back(toArg(inputs[0]));
argInputs.emplace_back(static_cast<int64_t>(v->offset()));
argInputs.emplace_back(n->i(attr::dim));
argInputs.emplace_back(n->i(attr::chunks));
} else if (op == aten::to) {
argInputs.emplace_back(toArg(inputs[0]));
} else if (op == aten::quantize_per_tensor) {
argInputs.emplace_back(toArg(inputs[0]));
if (!constZeroDimTensorAsScalarArg(inputs[1], argInputs)) {
argInputs.emplace_back(toArg(inputs[1]));
}
if (!constZeroDimTensorAsScalarArg(inputs[2], argInputs)) {
argInputs.emplace_back(toArg(inputs[2]));
}
argInputs.emplace_back(toArg(inputs[3]));
} else if (op == aten::conv2d) {
for (auto inp : inputs) {
argInputs.emplace_back(toArg(inp));
}
// handle optional bias
if (std::get_if<ArgNone>(&argInputs[2])) {
Dtype dtype = outputType ? Dtype(*outputType) : kFloat;
std::vector<ExprHandle> biasShape;
biasShape.push_back(outputShape[1]);
auto bias_tensor = at::zeros({outputShape[1].AsNode<LongImm>()->value()});
unpacked_constant_tensors_.push_back(bias_tensor);
BufPtr buf = alloc<Buf>(
"conv2d_bias_opt_" + sanitizeName(v->debugName()),
ExprHandleVectorToExprVector(biasShape),
dtype);
constants_.push_back({buf, bias_tensor.data_ptr()});
argInputs[2] = BufHandle(buf);
}
} else {
for (auto inp : inputs) {
argInputs.emplace_back(toArg(inp));
}
}
if (NNCLoweringFunction custom_lowering = getCustomLoweringFor(op)) {
return custom_lowering(
argInputs, outputShape, outputStrides, outputType, device_);
}
if (v->node()->maybeSchema()) {
if (NNCLoweringFunction lowering =
getStandardLoweringFor(c10::toString(v->node()->schema()))) {
return lowering(
argInputs, outputShape, outputStrides, outputType, device_);
}
}
std::string msg = std::string("Unhandled node kind (in computeValue): ") +
op.toQualString();
if (v->node()->maybeSchema()) {
msg += std::string("\nSchema: ") + c10::toString(v->node()->schema());
}
throw malformed_input(msg);
}
// True if all the loops in this vector have equal bounds.
static bool loopBoundsAllEqual(const std::vector<ForPtr>& loops) {
if (loops.size() <= 1) {
return true;
}
const auto& start = loops.front()->start();
const auto& stop = loops.front()->stop();
for (size_t i = 1; i < loops.size(); ++i) {
const auto& curr_start = loops[i]->start();
const auto& curr_stop = loops[i]->stop();
if (!exprEquals(start, curr_start) || !exprEquals(stop, curr_stop)) {
return false;
}
}
return true;
}
// Recursively fuse all the loops with matching bounds in `st`. Stops fusing
// at any level containing non-loops or non-matching bounds. The restriction
// on matching bounds exists to avoid inserting conditionals on the loop
// indices where none would be needed, which would significantly complicate
// vectorization.
static void fuseAllLoops(StmtPtr st) {
auto block = to<tensorexpr::Block>(st);
if (block == nullptr) {
return;
}
std::vector<std::vector<ForPtr>> all_outer_loops;
std::vector<ForPtr> outer_loops;
for (const auto& stmt : *block) {
auto loop = to<For>(stmt);
auto hasReduction = !NodeFinder<ReduceOp>::find(stmt).empty();
if (!loop || hasReduction) {
all_outer_loops.push_back(outer_loops);
outer_loops.clear();
} else {
outer_loops.push_back(loop);
}
}
all_outer_loops.push_back(outer_loops);
for (const auto& outer_loops : all_outer_loops) {
if (outer_loops.empty()) {
continue;
}
if (!loopBoundsAllEqual(outer_loops)) {
continue;
}
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
ForPtr fusedLoop;
if (!LoopNest::fuseLoops(outer_loops, &fusedLoop)) {
continue;
}
fuseAllLoops(fusedLoop->body());
}
}
// Compute the trip count of a loop if it is a constant.
static std::optional<int64_t> tripCount(ForPtr loop) {
auto tc = IRSimplifier::simplify(
cast<int64_t>(ExprHandle(loop->stop()) - ExprHandle(loop->start())));
if (auto val = to<LongImm>(tc.node())) {
return val->value();
}
return c10::nullopt;
}
// Prune innermost loops until iterations satisfies a minimum grain size.
static void pruneByGrainSize(std::vector<ForPtr>& loops) {
constexpr int64_t minGrainSize = 32768;
int64_t grainSize = 1;
for (int64_t i = loops.size(); i > 0; i--) {
auto tc = tripCount(loops[i - 1]);
if (!tc) {
break;
}
grainSize *= *tc;
if (grainSize < minGrainSize) {
loops.pop_back();
}
}
}
// Retain enough outermost loops to fill the number of threads.
static void pruneByThreadCount(std::vector<ForPtr>& loops) {
int64_t trips = 1;
auto threads = at::get_num_threads();
auto it = loops.begin();
for (; it != loops.end(); it++) {
if (trips >= threads) {
break;
}
auto tc = tripCount(*it);
if (!tc) {
break;
}
trips *= *tc;
}
loops.erase(it, loops.end());
}
// Flatten and parallelize outer loops, subject to a minimum number of elements
// in the inner loop, and a maximum level of thread-level parallelism in the
// outer loops.
template <typename Bufs>
static void parallelizeOuterLoops(LoopNest& l, Bufs&& bufs) {
for (auto const& buf : bufs) {
auto loops = l.getLoopStmtsFor(buf);
pruneByGrainSize(loops);
pruneByThreadCount(loops);
// There are no loops to parallelize; give up.
if (loops.size() == 0) {
continue;
}
// The loop nest contains a reduction; give up.
auto reductions = NodeFinder<ReduceOp>::find(loops[0]);
if (reductions.size() > 0) {
continue;
}
// The loop nest has loop carried dependences; give up.
if (LoopNest::hasLoopCarriedDependence(loops[0])) {
continue;
}
// Try to flatten the outer loops and parallelize them if successful.
ForPtr flattened = nullptr;
if (loops.size() == 1) {
flattened = loops[0];
} else {
LoopNest::flatten(loops, &flattened);
}
if (flattened) {
flattened->set_parallel();
}
}
}
StmtPtr TensorExprKernel::transformLoops(BackendType backendType, StmtPtr st) {
torch::jit::tensorexpr::LoopNest l(st, bufOutputs_);
LoopNest::sanitizeNames(l.root_stmt());
GRAPH_DEBUG("Original Stmt:\n", std::to_string(l.root_stmt()), "\n");
int64_t random_tr_seed = randomTransformsRequested();
if (random_tr_seed) {
if (random_tr_seed == -1)
random_tr_seed = std::time(nullptr);
loopnestRandomization(random_tr_seed, l);
GRAPH_DEBUG(
"After random transform:\n", std::to_string(l.root_stmt()), "\n");
}
bool hasReduction = !NodeFinder<ReduceOp>::find(l.root_stmt()).empty();
// For Block codegen we create a map of tensor dims before
// inlining. Like GPU codegen we need to inline. But the order
// where this analysis is run matters.
auto block_analysis = std::make_unique<CreateBufferMap>();
if (backendType == kBlockCodeGen) {
// Run Block analysis to get multi dim buffer info
auto root_stmt = l.root_stmt();
root_stmt->accept(block_analysis.get());
}
l.simplify();
GRAPH_DEBUG("after simplify", *l.root_stmt());
// Inlining output & intermediate buffers can duplicate computation.
// Duplicating work can slow down the program if it's not ameliorated in some
// way, but we've empirically found that:
// - On CPU, LLVM's CSE does a good job as long as you horizontally fuse
// output loops.
// - On GPU, there's enough compute to hide the extra work, and inlining
// avoids synchronizing between kernels.
l.inlineIntermediateBufs(/*allow_duplicated_work=*/true);
GRAPH_DEBUG("after inline", *l.root_stmt());
// Optimizing conditionals needs to be performed after inlining because
// inlining wouldn't work once the loops are split. Also, it has to be
// performed before loop fusion because loop fusion introduces cases where
// multiple conditionals are in the same loop and this optimization does not
// handle such cases yet.
if (getOptConditionals()) {
l.optimizeConditionals();
GRAPH_DEBUG("after optimizing conditionals: ", *l.root_stmt());
}
// Fuse loops "horizontally". This pass allows us to combine loops that
// write to different output buffers, as long as they have the same bounds.
if (backendType == kLLVMCodeGen) {
fuseAllLoops(l.root_stmt());
GRAPH_DEBUG("after fuse", *l.root_stmt());
parallelizeOuterLoops(l, bufsToBeParallelized_);
GRAPH_DEBUG("after parallelize", *l.root_stmt());
}
if (backendType == kCudaCodeGen) {
for (const auto& buf : bufOutputs_) {
std::vector<ForPtr> loops = l.getLoopStmtsFor(buf);
if (loops.empty()) {
// This happens when Buf is 0-dim
continue;
}
ForPtr flattened = nullptr;
LoopNest::flatten(loops, &flattened);
assert(flattened);
int loopLevels = getTECudaPointwiseLoopLevels();
const int kDefaultLoopLevels = 2;
loopLevels = (loopLevels > 0) ? loopLevels : kDefaultLoopLevels;
int blockCount = getTECudaPointwiseBlockCount();
int blockSize = getTECudaPointwiseBlockSize();
if (loopLevels == 2) {
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
ForPtr inner;
const int kDefaultBlockSize = 512;
if (blockSize < 0) {
blockSize = kDefaultBlockSize;
}
LoopNest::splitWithMask(flattened, blockSize, &inner);
flattened->set_gpu_block_index(0);
inner->set_gpu_thread_index(0);
} else if (loopLevels == 3) {
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
ForPtr inner;
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
ForPtr inner1;
// TODO: change the number of microprocessors
const int kDefaultBlockCount = 1280;
const int kDefaultBlockSize = 256;
blockCount = (blockCount > 0) ? blockCount : kDefaultBlockCount;
blockSize = (blockSize > 0) ? blockSize : kDefaultBlockSize;
LoopNest::splitWithMask(flattened, blockCount * blockSize, &inner);
LoopNest::splitWithMask(inner, blockSize, &inner1);
inner->set_gpu_block_index(0);
inner1->set_gpu_thread_index(0);
} else {
throw std::runtime_error(
"Invalid loop-level: " + c10::to_string(loopLevels));
}
}
}
if (backendType == kBlockCodeGen) {
for (const auto& buf : bufOutputs_) {
const int default_fp16_blocksize = 16;
const int default_uint8_blocksize = 32;
int blockSize = default_fp16_blocksize;
// We only handle looplevels == 2 for now
if (buf->dtype().scalar_type() == ScalarType::Byte) {
blockSize = default_uint8_blocksize;
}
std::vector<ForPtr> loops = l.getLoopStmtsFor(buf);
TORCH_INTERNAL_ASSERT(
!loops.empty(),
buildErrorMessage(
"No loops found for the buffer " + buf->name_hint() +
" in the fuser."));
ForPtr flattened = nullptr;
LoopNest::flatten(loops, &flattened);
assert(flattened);
ForPtr inner = nullptr;
LoopNest::splitWithMask(flattened, blockSize, &inner);
flattened->set_gpu_block_index(0);
inner->set_gpu_thread_index(0);
flattened->set_buffer_map(block_analysis->getBufferMap());
}
}
if (pre_alloc_) {
auto interm_bufs = l.getIntermediateBufs();
preAllocIntermediateBufs(interm_bufs);
}
l.prepareForCodegen();
GRAPH_DEBUG("after prepareForCodegen", *l.root_stmt());
l.simplify();
GRAPH_DEBUG("after simplification", *l.root_stmt());
if (backendType == kLLVMCodeGen && !hasReduction) {
l.vectorizeInnerLoops();
GRAPH_DEBUG("after vectorization", *l.root_stmt());
}
StmtPtr stmt = l.root_stmt();
// Arithmetic Simplification.
stmt = IRSimplifier::simplify(stmt);
GRAPH_DEBUG("Final Stmt:\n", std::to_string(stmt), "\n");
return stmt;
}
std::string TensorExprKernel::getCodeGenName(BackendType backendType) {
switch (backendType) {
case kCudaCodeGen:
return "cuda_codegen";
case kLLVMCodeGen:
return "llvm_codegen";
case kSimpleIREval:
return "simple_ir_eval";
case kBlockCodeGen:
return "block_codegen";
default:
throw std::runtime_error(
"invalid backend type: " +
c10::to_string(static_cast<int>(backendType)));
}
}
template <typename T>
static bool isValidPrimProperty(const std::optional<T>& a, T b) {
return !a.has_value() || *a == b;
}
TensorExprKernel::BackendType TensorExprKernel::inferBackendTypeFromDevice(
at::Device device) {
BackendType backendType = BackendType::kUninitialized;
if (device.type() == at::kCUDA) {
backendType = kCudaCodeGen;
} else if (device.type() == at::kCPU && getTEGenerateBlockCode()) {
backendType = kBlockCodeGen;
} else if (device.type() == at::kCPU) {
#ifdef TORCH_ENABLE_LLVM
backendType = dontUseLLVMFlag() ? kSimpleIREval : kLLVMCodeGen;
#else
backendType = kSimpleIREval;
#endif
if (getTEMustUseLLVMOnCPU() && backendType == kSimpleIREval) {
throw std::runtime_error("LLVM Backend not found");
}
} else {
throw std::runtime_error("Invalid device type");
}
return backendType;
}
// we use the debug names in printing cuda code, they need to be removed
// of characters that can't be used in a variable identifier
void TensorExprKernel::genInputDebugNames() {
std::unordered_map<std::string, const torch::jit::Value*> name_to_value;
std::unordered_set<std::string> name_set;
std::unordered_map<const torch::jit::Value*, std::string> value_to_name;
for (const torch::jit::Value* input : graph_->inputs()) {
std::string sanitized_name = sanitizeName(input->debugName());
// we could get fancier here, but name conflict is extremely unlikely
while (name_set.count(sanitized_name)) {
sanitized_name.append("_");
}
value_to_name[input] = sanitized_name;
name_set.insert(sanitized_name);