-
Notifications
You must be signed in to change notification settings - Fork 699
/
Copy pathShapeInferenceEngine.cpp
3502 lines (3067 loc) · 116 KB
/
ShapeInferenceEngine.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
/**
* Copyright (c) Glow Contributors. See CONTRIBUTORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ATen/WrapDimUtils.h>
#include <iostream>
#include <string>
#include <torch/script.h>
#include <unordered_set>
#include <vector>
#include "ShapeInferenceEngine.h"
#include "folly/Overload.h"
#include "folly/String.h"
#include "glow/Support/Error.h"
#include "glow/Support/Support.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/FileSystem.h"
DEFINE_string(shapeInferenceOpBlocklist, "", "Ops to skip shape inference");
DEFINE_int32(max_feature_length, -1, "max feature length");
DEFINE_bool(print_shape_inference_graph, false,
"print graph for shape inference debugging");
DEFINE_bool(skipReferOperatorsOnCpu, false,
"Skip referring shapes running on CPU");
namespace glow {
namespace {
/* Print graph/shapes in GraphViz dot format for debugging */
class GraphDrawer {
public:
GraphDrawer(const torch::jit::Graph &graph,
const std::unordered_map<const torch::jit::Value *, VariableMeta>
&shapeMap)
: graph_(graph), shapeMap_(shapeMap) {}
void dump(std::ostream &os) {
DCHECK(os) << "Failed to create file";
drawNodes();
os << "digraph DAG {\n\trankdir=TB;\n";
// Dump vertices:
for (auto &n : nodes_) {
os << n << "\n";
}
// Dump edges:
for (auto &e : edges_) {
os << e << ";\n";
}
os << "}";
}
private:
void dumpShape(VariableMeta vm, std::ostream &os) {
os << "[";
DCHECK(vm.listOfShape.size() > 0);
folly::variant_match(
vm.listOfShape[0],
[&](const TensorShape &shape) {
for (auto i = 0; i < shape.size(); i++) {
if (i) {
os << ", ";
}
os << shape[i];
}
},
[&](const TensorListShape &shapes) {
for (auto shape : shapes) {
os << "[";
for (auto i = 0; i < shape.size(); i++) {
if (i) {
os << ", ";
}
os << shape[i];
}
os << "]";
}
},
[&](const auto &) { os << "Unsupported shape type"; });
os << "], ";
os << "dtype: " << vm.dtype;
}
void dumpInputsOutputs(const torch::jit::Node *node, bool dumpInputs,
std::ostream &os) {
auto label = dumpInputs ? "\\lInputs" : "\\lOutputs";
auto values = dumpInputs ? node->inputs() : node->outputs();
auto first = true;
for (auto value : values) {
if (first) {
os << label << "\\l";
first = false;
} else {
os << "\\l";
}
os << value->debugName() << " : ";
if (shapeMap_.count(value)) {
auto vm = shapeMap_.find(value)->second;
if (vm.listOfShape.size() > 0) {
dumpShape(vm, os);
} else {
os << "Missing shape";
}
} else {
os << "Missing shape";
}
os << " (" << *value->type() << ")\\l";
}
}
void colorNode(const torch::jit::Node *node, std::ostream &ss) {
if (node->kind() == at::prim::Constant) {
ss << "\tfillcolor=grey\n";
} else {
size_t colorHash =
llvm::hash_value(llvm::StringRef(node->kind().toQualString()));
ss << "\tfillcolor=" << glow::getDotFileNodeColor(colorHash) << "\n";
}
}
void dumpNode(const torch::jit::Node *node, std::ostream &ss) {
if (node_id_map_.count(node)) {
return;
}
size_t node_id = node_id_map_.size();
node_id_map_.insert({node, node_id});
ss << node_id << "[\n";
ss << "\tlabel = \"{{<Kind>" << node->kind().toQualString() << "} | {";
dumpInputsOutputs(node, true, ss);
dumpInputsOutputs(node, false, ss);
for (auto *input : node->inputs()) {
std::ostringstream edge;
if (node_id_map_.count(input->node())) {
auto from_id = node_id_map_.find(input->node())->second;
edge << from_id << ":Result -> " << node_id << ":Kind";
edges_.insert(edge.str());
} else if (input->node()->kind() != at::prim::Param) {
LOG(INFO) << "Missing node " << input->node()->kind().toQualString();
}
}
ss << "}|{<Result>}}";
ss << "\"\n";
ss << "\tshape = \"record\"\n";
ss << "\tstyle=\"filled,rounded\"\n";
colorNode(node, ss);
ss << "penwidth = 2];\n";
}
void addNode(const torch::jit::Node *node) {
std::ostringstream ss;
dumpNode(node, ss);
nodes_.emplace_back(ss.str());
}
void drawNodes() {
for (auto *node : graph_.nodes()) {
addNode(node);
}
}
private:
std::vector<std::string> nodes_;
std::unordered_set<std::string> edges_;
std::unordered_map<const torch::jit::Node *, int> node_id_map_;
const torch::jit::Graph &graph_;
const std::unordered_map<const torch::jit::Value *, VariableMeta> &shapeMap_;
};
static std::vector<std::string> splitStr(const std::string &s,
const char delimiter = ',') {
std::vector<std::string> substrings;
size_t start = 0;
bool lastWasSplit = true;
for (size_t i = 0; i < s.size(); i++) {
if (lastWasSplit && s[i] == ' ') {
start = i + 1;
continue;
}
lastWasSplit = false;
if (s[i] == delimiter) {
substrings.push_back(s.substr(start, i - start));
start = i + 1;
lastWasSplit = true;
}
}
if (start < s.size() - 1) {
substrings.push_back(s.substr(start, s.size() - start));
}
return substrings;
}
} // namespace
ShapeInferenceEngine::ShapeInferenceEngine(
const torch::jit::Graph &graph, const at::ArrayRef<at::IValue> &inputs,
const std::string &fusionNodeSymbol, const bool &compilationMode)
: graph_(graph), inputs_(inputs), fusionNodeSymbol_(fusionNodeSymbol),
compilationMode_(compilationMode) {
if (!FLAGS_shapeInferenceOpBlocklist.empty()) {
auto ret = splitStr(FLAGS_shapeInferenceOpBlocklist);
for (const auto &s : ret) {
blockList_.insert(s);
}
}
};
bool ShapeInferenceEngine::getNodeInputShape(const torch::jit::Node *node,
MetaStack &inputMetas) {
for (size_t i = 0; i < node->inputs().size(); ++i) {
auto &input = node->inputs()[i];
auto it = shapeMap_.find(input);
if (it == shapeMap_.end()) {
LOG(WARNING) << "Missing input #" << i << " '" << input->debugName()
<< "' for node: " << *node;
return false;
}
inputMetas.emplace_back(shapeMap_[input]);
}
return true;
}
const MetaStack &ShapeInferenceEngine::getGraphOutputShape() {
return outputShape_;
}
const std::unordered_map<const torch::jit::Value *, VariableMeta> &
ShapeInferenceEngine::getVariableMap() {
return shapeMap_;
}
Error ShapeInferenceEngine::shapeOnNode(const torch::jit::Node *node) {
/// Get op symbol
const auto kind = node->kind();
const std::string symbol = kind.toQualString();
auto &mapping = getShapeSymbolMapping();
if (!mapping.count(symbol)) {
LOG(WARNING) << "Skip shape inference for unsupported op '" << symbol
<< "' at " << *node;
return Error::success();
}
if (blockList_.count(symbol)) {
// Skip shape inference for this node. If other nodes have dependency
// on this one then later their shape inference would fail explicitly.
LOG(INFO) << "Skip shape inference for " << symbol << " due to block list";
return Error::success();
}
/// Extract shapes of inputs from shape mapping
MetaStack inputMetas;
/// The outputs of each Op shape function include the shape and data
/// type, and the shape could be either the shape or int value
/// generated by prim::consant or prim::ListContruct.
bool ret = getNodeInputShape(node, inputMetas);
if (!ret) {
LOG(WARNING) << "Skip shape inference for " << symbol
<< " due to prior missing shapes";
return Error::success();
}
auto symbolItem = mapping.find(symbol);
if (symbolItem != mapping.end()) {
return symbolItem->second.infer(this, inputMetas, node);
}
return Error::success();
}
Error ShapeInferenceEngine::ShapeInference::infer(
ShapeInferenceEngine *engine, const MetaStack &meta,
const torch::jit::Node *node) const {
auto matchTensorOutputFn = folly::overload(
[&](const InferenceFn0 &metastackInferFn) -> Expected<TensorOutput> {
return metastackInferFn(meta);
},
[&](const InferenceFn1 &nodeInferFn) -> Expected<TensorOutput> {
return nodeInferFn(node);
},
[&](const InferenceFn2 &metastackNodeInferFn) -> Expected<TensorOutput> {
return metastackNodeInferFn(meta, node);
},
[&](const auto &) -> Expected<TensorOutput> {
return MAKE_ERR("Shape inference misconfiguration. Inference function "
"expected to return a TensorOutput. ");
});
auto matchTensorListOutputFn = folly::overload(
[&](const InferenceFn3 &metastackInferFn) -> Expected<TensorListOutput> {
return metastackInferFn(meta);
},
[&](const InferenceFn4 &nodeInferFn) -> Expected<TensorListOutput> {
return nodeInferFn(node);
},
[&](const InferenceFn5 &metastackNodeInferFn)
-> Expected<TensorListOutput> {
return metastackNodeInferFn(meta, node);
},
[&](const auto &) -> Expected<TensorListOutput> {
return MAKE_ERR("Shape inference misconfiguration. Inference function "
"expected to return a TensorListOutput.");
});
auto matchElemOutputFn = folly::overload(
[&](const InferenceFn6 &metastackInferFn) -> Expected<ElemOutput> {
return metastackInferFn(meta);
},
[&](const auto &) -> Expected<ElemOutput> {
return (MAKE_ERR("Shape inference misconfiguration. Inference function "
"expected to return an ElemOutput."));
});
return folly::variant_match(
addShapeFn,
[&](const AddShapeFn0 &addTensorOutput) -> Error {
TensorOutput output;
ASSIGN_VALUE_OR_RETURN_ERR(
output, boost::apply_visitor(matchTensorOutputFn, inferenceFn));
(engine->*(addTensorOutput))(node, output);
return Error::success();
},
[&](const AddShapeFn1 &addTensorListOutput) -> Error {
TensorListOutput output;
ASSIGN_VALUE_OR_RETURN_ERR(
output, boost::apply_visitor(matchTensorListOutputFn, inferenceFn));
(engine->*(addTensorListOutput))(node, output);
return Error::success();
},
[&](const AddShapeFn2 &addElemOutput) -> Error {
ElemOutput output;
ASSIGN_VALUE_OR_RETURN_ERR(
output, boost::apply_visitor(matchElemOutputFn, inferenceFn));
(engine->*(addElemOutput))(node, output);
return Error::success();
},
[&](const auto &) {
return MAKE_ERR("Unsupported types for addShapeFn");
});
}
ShapeInferenceEngine::SymbolToFunctionMap
ShapeInferenceEngine::buildShapeSymbolMapping() {
using SI = ShapeInferenceEngine;
auto map = SymbolToFunctionMap({
{"glow::fused_stack", ShapeInference(&fusedStack, &SI::addShapeDefault)},
{"glow::fused_stack", ShapeInference(&fusedStack, &SI::addShapeDefault)},
{"glow::fused_broadcast_stack",
ShapeInference(&fusedBroadcastStack, &SI::addShapeDefault)},
{"glow::fused_broadcast_stack_rc",
ShapeInference(&fusedBroadcastStackRC, &SI::addShapeDefault)},
{"glow::fused_broadcast_cat",
ShapeInference(&fusedBroadcastConcat, &SI::addShapeDefault)},
{"glow::fused_broadcast_cat_rc",
ShapeInference(&fusedBroadcastConcatRC, &SI::addShapeDefault)},
{"glow::fused_split",
ShapeInference(&fusedSplit, &SI::addShapeDefaultList)},
{"quantized::embedding_bag_byte_rowwise_offsets",
ShapeInference(&quantizedEmbeddingBagByteRowwiseOffsets,
&SI::addShapeDefault)},
{"quantized::embedding_bag_4bit_rowwise_offsets",
ShapeInference(&embeddingBag4BitRowwiseOffsets, &SI::addShapeDefault)},
{"glow::unpacked_quantized_linear",
ShapeInference(&glowUnpackedQuantizedLinear, &SI::addShapeDefault)},
{"fb::quantized_linear_unpacked_weight",
ShapeInference(&glowUnpackedQuantizedLinear, &SI::addShapeDefault)},
{"fb::quantized_linear_unpacked_weight_v2",
ShapeInference(&glowUnpackedQuantizedLinear, &SI::addShapeDefault)},
{"fb::lengths_to_offsets",
ShapeInference(&lengthsToOffsets, &SI::addShapeDefault)},
{"fb::simple_embedding_bag_sum",
ShapeInference(&embeddingBag, &SI::addShapeBag)},
{"fb::glow_embedding_bag",
ShapeInference(&glowEmbeddingBag, &SI::addShapeDefault)},
{"fb::glow_embedding_bag_byte_rowwise_offsets",
ShapeInference(&quantizedGlowEmbeddingBagByteRowwiseOffsets,
&SI::addShapeDefault)},
{"fb::glow_embedding_bag_4bit_rowwise_offsets",
ShapeInference(&quantizedGlowEmbeddingBag4BitRowwiseOffsets,
&SI::addShapeDefault)},
{"fb::xl_embedding_bag",
ShapeInference(&xlEmbeddingBag, &SI::addShapeBag)},
{"fb::xl_embedding_bag_byte_rowwise_offsets",
ShapeInference(&quantizedXLEmbeddingBagByteRowwiseOffsets,
&SI::addShapeBag)},
{"fb::xl_embedding_bag_4bit_rowwise_offsets",
ShapeInference(&quantizedXLEmbeddingBag4BitRowwiseOffsets,
&SI::addShapeBag)},
{"fb::fast_gather", ShapeInference(&fastGather, &SI::addShapeDefault)},
{"fb::lengths_range",
ShapeInference(&lengthsRange, &SI::addShapeDefault)},
// Current shape inference function can handle both cases.
{"fb::lengths_range_w_truncation_size",
ShapeInference(&lengthsRange, &SI::addShapeDefault)},
{"fb::quantize_per_tensor",
ShapeInference(&quantizePerTensor, &SI::addShapeDefault)},
{"aten::quantize_per_tensor",
ShapeInference(&quantizePerTensor, &SI::addShapeDefault)},
{"aten::dequantize", ShapeInference(&dequantize, &SI::addShapeDefault)},
{"quantized::mul", ShapeInference(&quantizedMul, &SI::addShapeDefault)},
{"prim::Constant", ShapeInference(&primConstant, &SI::addShapeConstant)},
{"aten::tanh", ShapeInference(&unaryOp, &SI::addShapeDefault)},
{"aten::relu", ShapeInference(&unaryOp, &SI::addShapeDefault)},
{"aten::sigmoid", ShapeInference(&unaryOp, &SI::addShapeDefault)},
{"aten::sign", ShapeInference(&unaryOp, &SI::addShapeDefault)},
{"aten::abs", ShapeInference(&unaryOp, &SI::addShapeDefault)},
{"aten::log1p", ShapeInference(&unaryOp, &SI::addShapeDefault)},
{"aten::square", ShapeInference(&unaryOp, &SI::addShapeDefault)},
{"aten::sqrt", ShapeInference(&unaryOp, &SI::addShapeDefault)},
{"aten::sub", ShapeInference(&binaryOp, &SI::addShapeDefault)},
{"aten::pow", ShapeInference(&binaryOp, &SI::addShapeDefault)},
{"aten::mul", ShapeInference(&mul, &SI::addShapeDefault)},
{"aten::add", ShapeInference(&add, &SI::addShapeDefault)},
{"aten::div", ShapeInference(&binaryOp, &SI::addShapeDefault)},
{"aten::rsub", ShapeInference(&binaryOp, &SI::addShapeDefault)},
{"aten::mm", ShapeInference(&mm, &SI::addShapeDefault)},
{"aten::addmm", ShapeInference(&addmm, &SI::addShapeDefault)},
{"aten::bmm", ShapeInference(&bmm, &SI::addShapeDefault)},
{"aten::t", ShapeInference(&t, &SI::addShapeDefault)},
{"aten::transpose", ShapeInference(&transpose, &SI::addShapeDefault)},
{"aten::flatten", ShapeInference(&flatten, &SI::addShapeDefault)},
{"prim::FusedConcat", ShapeInference(&fusedConcat, &SI::addShapeDefault)},
{"prim::ConstantChunk",
ShapeInference(&constantChunk, &SI::addShapeDefaultList)},
{"aten::chunk", ShapeInference(&chunk, &SI::addShapeChunk)},
{"prim::ListConstruct",
ShapeInference(&listConstruct, &SI::addShapeListConstruct)},
{"aten::slice", ShapeInference(&slice, &SI::addShapeSlice)},
{"aten::reshape", ShapeInference(&reshape, &SI::addShapeDefault)},
{"aten::cat", ShapeInference(&cat, &SI::addShapeDefault)},
{"aten::permute", ShapeInference(&permute, &SI::addShapeDefault)},
{"aten::embedding_bag", ShapeInference(&embeddingBag, &SI::addShapeBag)},
{"aten::matmul", ShapeInference(&matmul, &SI::addShapeDefault)},
{"aten::layer_norm", ShapeInference(&layerNorm, &SI::addShapeDefault)},
{"aten::linear", ShapeInference(&linear, &SI::addShapeDefault)},
{"aten::stack", ShapeInference(&stack, &SI::addShapeDefault)},
{"aten::to", ShapeInference(&to, &SI::addShapeDefault)},
{"aten::sum", ShapeInference(&reduceOp, &SI::addShapeDefault)},
{"aten::mean", ShapeInference(&reduceOp, &SI::addShapeDefault)},
{"prim::dtype", ShapeInference(&primDtype, &SI::addShapeConstant)},
{"prim::ListUnpack",
ShapeInference(&listUnpack, &SI::addShapeDefaultList)},
{"fbgemm_gpu::Fused8BitRowwiseQuantizedToFloat",
ShapeInference(&fused8BitRowwiseQuantizedToFloat, &SI::addShapeDefault)},
{"fb::compressed_indices_remap",
ShapeInference(&compressedIndicesRemap, &SI::addShapeDefaultList)},
{"fb::xl_compressed_indices_remap",
ShapeInference(&compressedIndicesRemap, &SI::addShapeDefaultList)},
{"quantized::embedding_bag_byte_unpack",
ShapeInference(&embeddingBagByteUnpack, &SI::addShapeDefault)},
{"fb::unsqueeze_n_times",
ShapeInference(&unsqueezeNTimes, &SI::addShapeDefault)},
{"fb::equally_split",
ShapeInference(&equallySplit, &SI::addShapeDefaultList)},
{"aten::squeeze", ShapeInference(&squeeze, &SI::addShapeDefault)},
{"aten::narrow", ShapeInference(&narrow, &SI::addShapeDefault)},
{"fb::index_hash", ShapeInference(&indexHash, &SI::addShapeDefault)},
{"fb::bucketize", ShapeInference(&bucketize, &SI::addShapeDefault)},
{"fb::expand_dims", ShapeInference(&expandDims, &SI::addShapeDefault)},
{"aten::split_with_sizes",
ShapeInference(&splitWithSizes, &SI::addShapeListConstruct)},
{"aten::Int", ShapeInference(&inferInt, &SI::addShapeDefault)},
{"prim::NumToTensor", ShapeInference(&numToTensor, &SI::addShapeDefault)},
{"aten::size", ShapeInference(&size, &SI::addShapeConstant)},
{"fb::scale_gradient",
ShapeInference(&scaleGradient, &SI::addShapeDefault)},
{"fb::to_lengths_to_offsets",
ShapeInference(&toLengthsToOffsets, &SI::addShapeDefault)},
{"aten::repeat", ShapeInference(&repeat, &SI::addShapeDefault)},
{"aten::softmax", ShapeInference(&softmax, &SI::addShapeDefault)},
{"aten::unsqueeze", ShapeInference(&unsqueeze, &SI::addShapeDefault)},
{"aten::clamp_min", ShapeInference(&clampMin, &SI::addShapeDefault)},
{"aten::norm", ShapeInference(&norm, &SI::addShapeDefault)},
{"aten::expand_as", ShapeInference(&expandAs, &SI::addShapeDefault)},
{"aten::argmin", ShapeInference(&argmin, &SI::addShapeDefault)},
{"fb::sigrid_hash_precompute",
ShapeInference(&sigridHashPrecompute, &SI::addShapeDefault)},
{"aten::full_like", ShapeInference(&fullLike, &SI::addShapeDefault)},
});
return map;
}
const ShapeInferenceEngine::SymbolToFunctionMap &
ShapeInferenceEngine::getShapeSymbolMapping() {
static const auto mapping = buildShapeSymbolMapping();
return mapping;
}
/// Put output into map
/// For \p prim::Constant, the output could be either Tensor or NumberType.
/// If the output is TensorType, store the \p outputShapesOrValues
/// into VariableMeta.listOfShape;
/// Else store the \p outputShapesOrValues into VariableMeta.intValue.
/// For \p prim::ListConstruct, if the output is a Scalar[], Bool[],
/// Store the shape of \p outputShapesOrValues into VariableMeta.listOfShape
/// store the value of \p outputShapesOrValues into VariableMeta.intValue
/// Else the output is Tensor[], Store the list of shape
/// \p outputShapesOrValues into VariableMeta.listOfShape
/// For \p aten::embedding_bag, since the output is a std::tuple<Tensor,
/// Tensor, Tensor, Tensor>(ret, offset2bag, bag_size, bag_size), and for now,
/// only the ret tensor shape needed, the embeddingBag() only generate the ret
/// shape.
/// For \p c10::aten::chunk, the output is tensor[],
/// Store the shapes \p outputShapesOrValues into VariableMeta.listOfShape
void ShapeInferenceEngine::addShapeConstant(const torch::jit::Node *node,
TensorOutput &output) {
if (node->output()->type()->isSubtypeOf(at::TensorType::get())) {
shapeMap_[node->output()].listOfShape.emplace_back(
std::move(output.shapeOrIntValues));
shapeMap_[node->output()].dtype = output.dtype;
} else {
shapeMap_[node->output()].listOfShape.emplace_back((TensorShape){1});
shapeMap_[node->output()].intValue = std::move(output.shapeOrIntValues);
shapeMap_[node->output()].dtype = output.dtype;
}
}
void ShapeInferenceEngine::addShapeListConstruct(const torch::jit::Node *node,
TensorListOutput &output) {
auto elem_type =
node->output()->type()->cast<c10::ListType>()->getElementType();
if (elem_type->kind() == at::TensorType::Kind ||
(elem_type->kind() == at::OptionalType::Kind &&
elem_type->cast<c10::OptionalType>()->getElementType()->kind() ==
at::TensorType::Kind)) {
shapeMap_[node->output()].listOfShape.emplace_back(std::move(output.shape));
shapeMap_[node->output()].dtype = output.dtype;
} else {
shapeMap_[node->output()].listOfShape.emplace_back(
(TensorShape){static_cast<long>(output.shape[0].size()), 1});
shapeMap_[node->output()].intValue = std::move(output.shape[0]);
shapeMap_[node->output()].dtype = output.dtype;
}
}
void ShapeInferenceEngine::addShapeBag(const torch::jit::Node *node,
TensorOutput &output) {
shapeMap_[node->output(0)].listOfShape.emplace_back(
std::move(output.shapeOrIntValues));
shapeMap_[node->output(0)].dtype = output.dtype;
}
void ShapeInferenceEngine::addShapeChunk(const torch::jit::Node *node,
TensorListOutput &output) {
shapeMap_[node->output()].listOfShape.emplace_back(std::move(output.shape));
shapeMap_[node->output()].dtype = output.dtype;
}
void ShapeInferenceEngine::addShapeDefault(const torch::jit::Node *node,
TensorOutput &output) {
if (output.scalar) {
CHECK_EQ(output.shapeOrIntValues.size(), 1);
shapeMap_[node->output()].listOfShape.emplace_back((TensorShape){1});
shapeMap_[node->output()].intValue = std::move(output.shapeOrIntValues);
shapeMap_[node->output()].dtype = output.dtype;
} else {
shapeMap_[node->output()].listOfShape.emplace_back(
std::move(output.shapeOrIntValues));
shapeMap_[node->output()].dtype = output.dtype;
}
}
void ShapeInferenceEngine::addShapeDefaultList(const torch::jit::Node *node,
TensorListOutput &output) {
for (int i = 0; i < node->outputs().size(); i++) {
shapeMap_[node->output(i)].listOfShape.emplace_back(
std::move(output.shape[i]));
if (output.dtypeList.size() > 0) {
shapeMap_[node->output(i)].dtype = output.dtypeList[i];
} else {
shapeMap_[node->output(i)].dtype = output.dtype;
}
}
}
void ShapeInferenceEngine::addShapeSlice(const torch::jit::Node *node,
ElemOutput &output) {
folly::variant_match(
output,
[&](TensorOutput &tensorOutput) { addShapeDefault(node, tensorOutput); },
[&](TensorListOutput &tensorListOutput) {
shapeMap_[node->output()].listOfShape.emplace_back(
std::move(tensorListOutput.shape));
shapeMap_[node->output()].dtype = tensorListOutput.dtype;
});
}
Error ShapeInferenceEngine::runSubGraph(
const torch::jit::Graph &graph,
const at::ArrayRef<torch::jit::IValue> &inputs) {
RETURN_IF_ERR(getGraphInputShapeType(graph, inputs));
for (auto *node : graph.nodes()) {
CHECK(!node->hasAttribute(torch::jit::attr::Subgraph));
RETURN_IF_ERR(shapeOnNode(node));
}
return Error::success();
}
Error ShapeInferenceEngine::runGraph(
const torch::jit::Graph &graph,
const at::ArrayRef<torch::jit::IValue> &inputs) {
{
std::ofstream f{"shape_graph.txt"};
f << graph;
}
// Populate input shapes
RETURN_IF_ERR(getGraphInputShapeType(graph, inputs));
int totalFusionNodes = 0;
for (auto *node : graph.nodes()) {
if (node->kind().toQualString() == fusionNodeSymbol_) {
totalFusionNodes += 1;
}
}
int fusionNodeIndex = 0;
/// Run shape inference for each node
for (auto *node : graph.nodes()) {
if (node->hasAttribute(torch::jit::attr::Subgraph)) {
std::string kind = node->kind().toQualString();
CHECK_EQ(kind.find(fusionNodeSymbol_), 0);
// After fusion the input Value of the subgraph and
// input Value of the fusion node are different
// in memory objects. Therefore we populate inputMeta
// beforehand and pass it to recursive run.
std::vector<torch::jit::IValue> subgraphInputs;
for (auto i : node->inputs()) {
auto it = shapeMap_.find(i);
if (it == shapeMap_.end()) {
dumpGraph(graph);
LOG(FATAL) << "missing input " << i->debugName().c_str();
}
// Only support tensor input for now
// TODO Add support for other input types, e.g., tensor list
if (it->second.dtype == at::ScalarType::QUInt8) {
auto emptyTQ = at::_empty_affine_quantized(
it->second.shape<TensorShape>(), at::ScalarType::QUInt8, 0, 1);
subgraphInputs.emplace_back(emptyTQ);
} else {
subgraphInputs.emplace_back(
torch::empty(it->second.shape<TensorShape>(),
torch::TensorOptions().dtype(it->second.dtype)));
}
}
const at::ArrayRef<torch::jit::IValue> inputRefs(subgraphInputs);
auto subgraph = node->g(torch::jit::attr::Subgraph);
RETURN_IF_ERR(runSubGraph(*subgraph, subgraphInputs));
CHECK_EQ(subgraph->outputs().size(), node->outputs().size());
for (int i = 0; i < subgraph->outputs().size(); ++i) {
shapeMap_[node->outputs()[i]] = shapeMap_[subgraph->outputs()[i]];
}
fusionNodeIndex += 1;
} else {
if (compilationMode_ && fusionNodeIndex == totalFusionNodes &&
FLAGS_skipReferOperatorsOnCpu) {
LOG(INFO)
<< "Skip shape inference for node after fusion groups with kind: "
<< node->kind().toQualString();
continue;
} else {
RETURN_IF_ERR(shapeOnNode(node));
}
}
}
return Error::success();
}
Error ShapeInferenceEngine::run() {
RETURN_ERR_IF_NOT(
inputs_.size() == graph_.inputs().size() ||
(inputs_.size() + 1 == graph_.inputs().size() &&
graph_.inputs()[0]->type()->is_module()),
"Number of inputs mismatch between Graph and actual inputs");
if (FLAGS_print_shape_inference_graph) {
printGraph(graph_, 0);
}
/// Put graph input into shape mapping
RETURN_IF_ERR(runGraph(graph_, inputs_));
if (!compilationMode_) {
/// Extract output from shape mapping
RETURN_IF_ERR(generateGraphOutputShape());
}
return Error::success();
}
bool ShapeInferenceEngine::isSupportedNodeSymbol(const torch::jit::Node *node) {
const auto kind = node->kind();
const std::string symbol = kind.toQualString();
auto &mapping = getShapeSymbolMapping();
return mapping.find(symbol) != mapping.end();
}
std::unordered_set<std::string>
ShapeInferenceEngine::findUnsupportedGraphSymbols(bool skipLastFusionNode) {
std::unordered_set<std::string> unsupportedSymbols;
findUnsupportedGraphSymbols(graph_, unsupportedSymbols, skipLastFusionNode);
return unsupportedSymbols;
}
void ShapeInferenceEngine::findUnsupportedGraphSymbols(
const torch::jit::Graph &graph,
std::unordered_set<std::string> &unsupportedSymbols,
bool skipLastFusionNode) {
int totalFusionNodes = 0;
for (auto *node : graph.nodes()) {
if (node->kind().toQualString() == fusionNodeSymbol_) {
totalFusionNodes += 1;
}
}
int fusionNodeIndex = 0;
for (auto *node : graph.nodes()) {
if (node->hasAttribute(torch::jit::attr::Subgraph)) {
auto subgraph = node->g(torch::jit::attr::Subgraph);
findUnsupportedGraphSymbols(*subgraph, unsupportedSymbols, false);
fusionNodeIndex += 1;
} else {
if (fusionNodeIndex == totalFusionNodes && skipLastFusionNode) {
LOG(INFO)
<< "Skip shape inference for node after fusion groups with kind: "
<< node->kind().toQualString();
continue;
} else if (!isSupportedNodeSymbol(node)) {
unsupportedSymbols.insert(node->kind().toQualString());
}
}
}
}
void ShapeInferenceEngine::printShapeMap() {
for (auto elem : shapeMap_) {
std::cout << elem.first->debugName() << ":[ ";
folly::variant_match(
elem.second.listOfShape[0],
[&](const TensorShape &shape) {
for (auto value : shape) {
std::cout << value << " ";
}
},
[&](const TensorListShape &shapes) {
for (auto shape : shapes) {
std::cout << "[ ";
for (auto value : shape) {
std::cout << value << " ";
}
std::cout << "]";
}
},
[&](const auto &) { std::cout << "Type doesn't support yet."; });
std::cout << "]" << std::endl;
}
}
void ShapeInferenceEngine::dumpGraph(const torch::jit::Graph &graph) {
std::string graphPath = "debug_shapes.dot";
LOG(INFO) << "Dumping graph dot file to " << graphPath;
GraphDrawer GD(graph, shapeMap_);
std::ofstream file(graphPath);
if (file) {
GD.dump(file);
} else {
LOG(ERROR) << "Unable to open " << graphPath << "\n " << strerror(errno);
}
file.close();
auto groupId = 0;
std::vector<const torch::jit::Node *> fusions;
for (auto *node : graph.nodes()) {
if (node->hasAttribute(torch::jit::attr::Subgraph)) {
std::string dotFileName =
"debug_shapes_fusion_group_" + std::to_string(groupId) + ".dot";
{
GraphDrawer SGD(*node->g(torch::jit::attr::Subgraph), shapeMap_);
LOG(INFO) << "Dumping fusion subgraph dot file to " << dotFileName;
std::ofstream subgraphFile(dotFileName);
if (subgraphFile) {
SGD.dump(subgraphFile);
} else {
LOG(ERROR) << "Unable to open " << dotFileName << "\n "
<< strerror(errno);
}
}
std::string txtFileName =
"debug_shapes_fusion_group_" + std::to_string(groupId) + ".txt";
{
LOG(INFO) << "Dumping fusion subgraph txt file to " << txtFileName;
std::ofstream subgraphFile(txtFileName);
if (subgraphFile) {
subgraphFile << *node->g(torch::jit::attr::Subgraph);
} else {
LOG(ERROR) << "Unable to open " << txtFileName << "\n "
<< strerror(errno);
}
}
groupId++;
fusions.push_back(node);
}
}
// If more than one group, then we can find unsupported nodes in between
if (fusions.size() > 1) {
LOG(INFO) << "Found more than one fusion group";
std::unordered_set<const torch::jit::Node *> allFusionOutputs;
for (auto f : fusions) {
for (auto o : f->outputs()) {
for (auto use : o->uses()) {
allFusionOutputs.insert(use.user);
}
}
}
std::ostringstream ss;
for (auto n : allFusionOutputs) {
ss << "\n" << *n;
}
LOG(INFO) << "Got " << allFusionOutputs.size()
<< " nodes following fusion groups" << ss.str();
}
}
void ShapeInferenceEngine::printGraph(const torch::jit::Graph &graph,
int64_t level) {
int index = 0;
for (auto *node : graph.nodes()) {
if (node->hasAttribute(torch::jit::attr::Subgraph)) {
auto subgraph = node->g(torch::jit::attr::Subgraph);
LOG(INFO) << "graph level " << level << " node(fusion group) " << index
<< " " << node->kind().toQualString();
printGraph(*subgraph, level + 1);
} else {
LOG(INFO) << "graph level " << level << " node(leaf) " << index << " "
<< node->kind().toQualString();
for (int i = 0; i < node->inputs().size(); i++) {
LOG(INFO) << " input " << i << ": " << node->input(i)->debugName();
}
for (int i = 0; i < node->outputs().size(); i++) {
LOG(INFO) << " output " << i << ": " << node->output(i)->debugName();
}
}
index++;
}
}
/// If the input is tensor, store the shape info only;
/// Else If the input is bool or int, store the value, and set shape as 1.
/// Else if the input is intlist, store the intlist, and set shape as [sizeof
/// intlist, 1]
/// Else return an error
Error ShapeInferenceEngine::getGraphInputShapeType(
const torch::jit::Graph &graph,
const at::ArrayRef<torch::jit::IValue> &inputs) {
int has_self = 0;
if (!graph.inputs().empty() && graph.inputs()[0]->type()->is_module()) {
has_self = 1;
}
for (auto i = 0; i < inputs.size(); i++) {
auto gInName = graph.inputs()[i + has_self];
auto input = inputs[i];
TensorShape shape = {};
std::vector<int64_t> intValue = {};
c10::ScalarType dtype;
if (input.isTensor()) {
auto &ptTensor = input.toTensor();
for (auto s : ptTensor.sizes()) {
shape.emplace_back(s);
}
dtype = ptTensor.scalar_type();
} else if (input.isBool() || input.isInt()) {
shape = {1};
intValue = {input.toInt()};
dtype = input.isBool() ? c10::ScalarType::Bool : c10::ScalarType::Int;
} else if (input.isIntList()) {
intValue = input.toIntVector();
shape = {static_cast<long>(intValue.size()), 1};
dtype = c10::ScalarType::Int;
} else if (input.isNone()) {
dtype = c10::ScalarType::Undefined;
} else {
return MAKE_ERR("Input type isn't supported yet.");
}
shapeMap_[gInName].listOfShape.emplace_back(std::move(shape));
shapeMap_[gInName].intValue = intValue;
shapeMap_[gInName].dtype = dtype;
}
return Error::success();
}
Error ShapeInferenceEngine::generateGraphOutputShape() {
for (auto output : graph_.outputs()) {
auto it = shapeMap_.find(output);
if (it == shapeMap_.end()) {
LOG(WARNING) << "Some output shape is missing. Likely due to "
"blockList. Clearing the output shape vector.";
outputShape_.clear();
return Error::success();
}
outputShape_.emplace_back(it->second);
}
return Error::success();
}
bool ShapeInferenceEngine::isScalarInt(const VariableMeta &vm) {
const auto &shape = vm.shape<TensorShape>();
return shape.size() == 1 && shape[0] == 1 && vm.intValue.size() == 1 &&
vm.dtype == c10::ScalarType::Int;
}
/// The \p prim::Constant may have multiple types of output, eg.
/// int = prim::Constant[value=0]()
/// Float(1:1) = prim::Constant[value={0}]()
/// bool = prim::Constant[value=0]()
/// None = prim::Constant()
/// int[] = prim::Constant[value=[1,2,3]]()
/// Tensor = prim::Constant[value= <Tensor>]()
/// If the output is a tensor, return shape info and dtype;
/// Else, return the value and dtype.
Expected<TensorOutput>
ShapeInferenceEngine::primConstant(const torch::jit::Node *node) {
TensorShape shapeOrValue;
c10::ScalarType dtype;
at::TypePtr type = node->output()->type();
if (type->isSubtypeOf(at::FloatType::get())) {
/// The float type will not affect the shape
/// Set value as 1
shapeOrValue = {1};
dtype = c10::ScalarType::Float;
} else if (type->isSubtypeOf(at::IntType::get())) {
shapeOrValue = {node->i(at::attr::value)};
dtype = c10::ScalarType::Int;
} else if (type->isSubtypeOf(at::BoolType::get())) {
shapeOrValue = {node->i(at::attr::value)};
dtype = c10::ScalarType::Bool;
} else if (type->isSubtypeOf(at::NoneType::get())) {
shapeOrValue = {};
dtype = c10::ScalarType::Undefined;
} else if (type->isSubtypeOf(at::TensorType::get())) {
at::Tensor t = node->t(at::attr::value);
for (auto s : t.sizes()) {
shapeOrValue.emplace_back(s);
}
dtype = t.scalar_type();
} else if (type->isSubtypeOf(at::ListType::ofInts())) {
dtype = c10::ScalarType::Int;
shapeOrValue = node->ival(at::attr::value).toIntVector();
} else if (type->isSubtypeOf(at::StringType::get())) {
shapeOrValue = {1};
dtype = c10::ScalarType::Char;
} else {
std::ostringstream ss;
ss << "Type '" << *type << "' is not supported.\nIt's coming from node "
<< *node;
LOG(ERROR) << ss.str();
return MAKE_ERR(ss.str());
}
TensorOutput output;
output.shapeOrIntValues = shapeOrValue;
output.dtype = dtype;
return output;
}
// Shape inference for aten::tanh, aten::relu, aten::sigmoid, aten::abs,
// aten::sign, aten::log1p
Expected<TensorOutput>
ShapeInferenceEngine::unaryOp(const MetaStack &variableMetas) {
RETURN_ERR_IF_NOT(variableMetas.size() == 1,
"Expected 1 input shape for operators.");
TensorOutput output;
output.shapeOrIntValues = variableMetas[0].shape<TensorShape>(),
output.dtype = variableMetas[0].dtype;
return output;
}
/**
* aten::add(Tensor self, Tensor or Scalar other, Scalar alpha=1) -> Tensor
* aten::pow(Tensor self, Tensor or Scalar other, Scalar alpha=1) -> Tensor
* variableMetas: 0: self, 1: other
*/
Expected<TensorOutput>
ShapeInferenceEngine::binaryOp(const MetaStack &variableMetas,
const torch::jit::Node *ptNode) {
if (variableMetas.size() != 2 && variableMetas.size() != 3) {