/
GraphOptimizer.cpp
3008 lines (2640 loc) · 103 KB
/
GraphOptimizer.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) 2017-present, Facebook, Inc.
*
* 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 "glow/Optimizer/GraphOptimizer/GraphOptimizer.h"
#include "glow/Backend/Backend.h"
#include "glow/Converter/TypeAToTypeBFunctionConverter.h"
#include "glow/Graph/Graph.h"
#include "glow/Graph/Log.h"
#include "glow/Graph/Node.h"
#include "glow/Graph/Nodes.h"
#include "glow/Graph/PlaceholderBindings.h"
#include "glow/Graph/Utils.h"
#include "glow/Optimizer/GraphOptimizer/FunctionPasses.h"
#include "glow/Quantization/Base/Base.h"
#include "glow/Quantization/Quantization.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <vector>
llvm::cl::OptionCategory graphOptCat("Graph Optimizations Options");
llvm::cl::opt<unsigned> constDedupSizeOpt(
"const_dedup_size",
llvm::cl::desc(
"Max number of elements allowed for deduplicating Constants"),
llvm::cl::Optional, llvm::cl::init(256), llvm::cl::cat(graphOptCat));
using namespace glow;
using llvm::cast;
using llvm::dyn_cast;
using llvm::isa;
static bool shouldDeleteNode(Node *N) {
// In general, nodes who have side effects are retained.
if (N->hasSideEffects()) {
return false;
}
// Don't delete nodes that have users.
if (N->hasUsers()) {
return false;
}
return true;
}
/// Helper that \returns whether all sibling Functions of \p F (other Functions
/// inside its Module) are Loaded.
static bool shouldDeleteConstants(Function *F) {
Module *mod = F->getParent();
for (auto *MF : mod->getFunctions()) {
if (MF->getState() < FunctionState::FuncLoaded) {
return false;
}
}
return true;
}
bool DCE::run(Function *F) {
LOG_SCOPE(F->getLogContext(), getName());
auto &nodes = F->getNodes();
auto &consts = F->getParent()->getConstants();
std::vector<ConstList::iterator> erasedConsts{};
std::vector<NodesList::iterator> erasedNodes{};
bool changed = false;
// Remove unused nodes.
while (true) {
bool changedLocally = false;
for (auto it = nodes.begin(), e = nodes.end(); it != e;) {
if (!shouldDeleteNode(&*it)) {
++it;
continue;
}
erasedNodes.push_back(it);
++it;
changedLocally = true;
changed = true;
}
while (!erasedNodes.empty()) {
auto it = erasedNodes.back();
F->eraseNode(it);
erasedNodes.pop_back();
}
if (!changedLocally) {
break;
}
}
if (!shouldDeleteConstants(F)) {
return changed;
}
// Delete unused Constants.
for (auto it = consts.begin(), e = consts.end(); it != e;) {
if (!shouldDeleteNode(*it)) {
++it;
continue;
}
erasedConsts.push_back(it);
++it;
}
while (!erasedConsts.empty()) {
auto it = erasedConsts.back();
F->getParent()->eraseConstant(it);
erasedConsts.pop_back();
}
return changed;
}
/// \returns true if the \p shuffle corresponds to an identity operation, false
/// otherwise.
static bool isIdentityShuffle(llvm::ArrayRef<unsigned> shuffle) {
for (size_t i = 0, e = shuffle.size(); i < e; i++) {
if (shuffle[i] != i) {
return false;
}
}
return true;
}
/// \returns True if the node \p N always evaluates to \p val.
bool isSplatOfVal(Node *N, float val) {
SplatNode *Z = dyn_cast<SplatNode>(N);
if (!Z) {
return false;
}
return (Z->getValue() == val);
}
/// \returns True if the node returns a constant value.
bool isConstant(Node *N) { return isa<SplatNode>(N); }
/// \returns the new simplified node or the original node.
static Node *simplifyNode(Node *node, Function *F) {
// Simplify commutative nodes by moving the constant operator to the right-hand
// side.
// Example: C + X => X + C
#define COMMUTE_CONST_TO_RHS(NodeKind) \
if (auto *NN = dyn_cast<NodeKind##Node>(node)) \
if (isConstant(NN->getLHS()) && !isConstant(NN->getRHS())) { \
return F->create##NodeKind(NN->getName(), NN->getResult().getType(), \
NN->getRHS(), NN->getLHS()); \
}
COMMUTE_CONST_TO_RHS(Add)
COMMUTE_CONST_TO_RHS(Mul)
COMMUTE_CONST_TO_RHS(Max)
COMMUTE_CONST_TO_RHS(Min)
#undef COMMUTE_CONST_TO_RHS
if (auto *AN = dyn_cast<AddNode>(node)) {
// X + 0 => X
if (isSplatOfVal(AN->getRHS(), 0)) {
return AN->getLHS();
}
}
if (auto *MN = dyn_cast<MulNode>(node)) {
// X * 0 => 0
if (isSplatOfVal(MN->getRHS(), 0)) {
return MN->getRHS();
}
// X * 1 => X
if (isSplatOfVal(MN->getRHS(), 1)) {
return MN->getLHS();
}
}
if (auto *DN = dyn_cast<DivNode>(node)) {
// 0 / X => 0
if (isSplatOfVal(DN->getLHS(), 0)) {
return DN->getLHS();
}
// X / 1 => X
if (isSplatOfVal(DN->getRHS(), 1)) {
return DN->getLHS();
}
}
// X - 0 => X
if (auto *SN = dyn_cast<SubNode>(node)) {
if (isSplatOfVal(SN->getRHS(), 0)) {
return SN->getLHS();
}
}
return node;
}
/// Sink Transpose below ChannelShuffle node.
static bool sinkTranposeBelowChannelShuffle(Function *F,
ChannelShuffleNode *CS) {
auto *TR = dyn_cast<TransposeNode>(CS->getInput());
if (!TR) {
return false;
}
// Create a new ChannelShuffle with kernel parameter transposed by the
// sinking TR's shuffle because that Transpose will now be moved below this
// ChannelShuffle operator.
auto *newCS =
F->createChannelShuffle(CS->getName(), TR->getInput(), CS->getGroup(),
TR->getShuffle()[CS->getKernel()]);
// Create a copy of sinkingTR and insert after newChannelShuffle.
auto *newTR = F->createTranspose(TR->getName(), newCS, TR->getShuffle());
CS->getResult().replaceAllUsesOfWith(newTR);
return true;
}
/// Code Sinking.
bool SinkCode::run(Function *F) {
LOG_SCOPE(F->getLogContext(), getName());
bool changed = false;
auto &nodes = F->getNodes();
// For each node:
for (auto &N : nodes) {
auto *node = &N;
// Sink Transpose below batch normalization nodes:
if (auto *BN = dyn_cast<BatchNormalizationNode>(node)) {
auto *TR = dyn_cast<TransposeNode>(BN->getInput());
if (!TR) {
continue;
}
// Figure out where we transposed the channel index for batch
// normalization.
unsigned_t idx = BN->getChannelIdx();
unsigned_t newChannelIdx = TR->getShuffle()[idx];
auto *NewBN = F->createBatchNormalization(
BN->getName(), TR->getInput(), BN->getBias(), BN->getScale(),
BN->getMean(), BN->getVar(), newChannelIdx, BN->getEpsilon(),
BN->getMomentum());
NewBN->setPredicate(node->getPredicate());
auto *newTR = F->createTranspose(TR->getName(), NewBN, TR->getShuffle());
newTR->setPredicate(node->getPredicate());
BN->getResult().replaceAllUsesOfWith(newTR);
changed = true;
continue;
}
// Sink Transpose below batch RELU nodes.
if (auto *RL = dyn_cast<ReluNode>(node)) {
auto *TR = dyn_cast<TransposeNode>(RL->getInput());
if (!TR) {
continue;
}
// Keep the same quantization parameters for ReLU output, but
// change the shape to appropriate value.
auto reluOutTy = F->getParent()->uniqueTypeWithNewShape(
RL->getResult().getType(), TR->getInput().dims());
auto *NRL = F->createRELU(RL->getName(), TR->getInput(), reluOutTy);
NRL->setPredicate(node->getPredicate());
auto *newTR = F->createTranspose(TR->getName(), NRL, TR->getShuffle());
newTR->setPredicate(node->getPredicate());
RL->getResult().replaceAllUsesOfWith(newTR);
changed = true;
continue;
}
// Sink Transpose below Sigmoid nodes.
if (auto *SI = dyn_cast<SigmoidNode>(node)) {
auto *TR = dyn_cast<TransposeNode>(SI->getInput());
if (!TR) {
continue;
}
auto *NSI = F->createSigmoid(SI->getName(), TR->getInput());
NSI->setPredicate(node->getPredicate());
auto *newTR = F->createTranspose(TR->getName(), NSI, TR->getShuffle());
newTR->setPredicate(node->getPredicate());
SI->getResult().replaceAllUsesOfWith(newTR);
changed = true;
continue;
}
// Sink Transpose below Pad nodes.
if (auto *padNode = dyn_cast<PadNode>(node)) {
auto *transposeNode = dyn_cast<TransposeNode>(padNode->getInput());
if (!transposeNode) {
continue;
}
// The transpose shuffle specifies the source dimension.
// When sinking Transpose below Pad, shuffle describes the target
// dimension.
auto shuffle = transposeNode->getShuffle();
// Shuffle the Pad output type and the padding attribute.
auto outPadType = padNode->getResult().getType();
auto outPadShape = outPadType->dims();
auto pads = padNode->getPads();
size_t numDims = outPadShape.size();
std::vector<size_t> newOutPadShape(numDims);
std::vector<int> newPads(2 * numDims);
for (size_t i = 0; i < outPadShape.size(); i++) {
newOutPadShape[shuffle[i]] = outPadShape[i];
newPads[shuffle[i]] = pads[i];
newPads[shuffle[i] + numDims] = pads[i + numDims];
}
// New pad
auto newOutPadType =
F->getParent()->uniqueTypeWithNewShape(outPadType, newOutPadShape);
auto *NewPadNode = F->createPad(
padNode->getName(), transposeNode->getInput(), newOutPadType,
padNode->getMode(), newPads, padNode->getValue());
NewPadNode->setPredicate(node->getPredicate());
auto *newTransposeNode =
F->createTranspose(transposeNode->getName(), NewPadNode, shuffle);
newTransposeNode->setPredicate(node->getPredicate());
padNode->getResult().replaceAllUsesOfWith(newTransposeNode);
changed = true;
continue;
}
// Sink Transpose below Tanh nodes.
if (auto *TN = dyn_cast<TanhNode>(node)) {
auto *TR = dyn_cast<TransposeNode>(TN->getInput());
if (!TR) {
continue;
}
auto *NTN = F->createTanh(TN->getName(), TR->getInput());
NTN->setPredicate(node->getPredicate());
auto *newTR = F->createTranspose(TR->getName(), NTN, TR->getShuffle());
newTR->setPredicate(node->getPredicate());
TN->getResult().replaceAllUsesOfWith(newTR);
changed = true;
continue;
}
// Remove 'identity' transpose operations.
if (auto *TR = dyn_cast<TransposeNode>(node)) {
auto mask = TR->getShuffle();
if (isIdentityShuffle(mask)) {
TR->getResult().replaceAllUsesOfWith(TR->getInput());
changed = true;
continue;
}
}
// Merge consecutive Transpose operations.
if (auto *TR1 = dyn_cast<TransposeNode>(node)) {
auto *TR2 = dyn_cast<TransposeNode>(TR1->getInput());
if (!TR2) {
continue;
}
auto mask1 = TR1->getShuffle();
auto mask2 = TR2->getShuffle();
assert(mask1.size() == mask2.size() && "Invalid mask size");
llvm::SmallVector<unsigned_t, max_tensor_dimensions> newMask;
newMask.resize(mask2.size());
for (size_t i = 0, end = mask2.size(); i < end; i++) {
newMask[i] = mask2[mask1[i]];
}
auto *newTR = F->createTranspose("tranpose", TR2->getInput(), newMask);
TR1->getResult().replaceAllUsesOfWith(newTR->getResult());
changed = true;
continue;
}
if (auto *CS = dyn_cast<ChannelShuffleNode>(node)) {
// Sink Transpose below ChannelShuffle.
if (sinkTranposeBelowChannelShuffle(F, CS)) {
changed = true;
continue;
}
}
// Sink Transpose below Arithmetic nodes.
if (node->isArithmetic()) {
TransposeNode *LTR =
dyn_cast<TransposeNode>(node->getNthInput(ArithmeticNode::LHSIdx));
TransposeNode *RTR =
dyn_cast<TransposeNode>(node->getNthInput(ArithmeticNode::RHSIdx));
if (!LTR || !RTR) {
// If one of the sides is a splat, it can be seen as
// transpose (splat').
if (isa<SplatNode>(node->getNthInput(ArithmeticNode::LHSIdx)) && RTR) {
// Build splat' for LHS.
auto *SN =
dyn_cast<SplatNode>(node->getNthInput(ArithmeticNode::LHSIdx));
auto *NS = F->createSplat("splat", RTR->getInput().getType(),
SN->getValue());
LTR = F->createTranspose("transpose", NS, RTR->getShuffle());
changed = true;
} else if (isa<SplatNode>(node->getNthInput(ArithmeticNode::RHSIdx)) &&
LTR) {
// Build splat' for RHS.
auto *SN =
dyn_cast<SplatNode>(node->getNthInput(ArithmeticNode::RHSIdx));
auto *NS = F->createSplat("splat", LTR->getInput().getType(),
SN->getValue());
RTR = F->createTranspose("transpose", NS, LTR->getShuffle());
changed = true;
} else {
continue;
}
}
// The masks of the transposes on both sizes must match.
if (LTR->getShuffle() != RTR->getShuffle()) {
continue;
}
Node *newAN = nullptr;
#define ARITHMETIC_CASE(NODE_NAME_) \
case glow::Kinded::Kind::NODE_NAME_##NodeKind: \
newAN = \
F->create##NODE_NAME_(node->getName(), \
F->getParent()->uniqueTypeWithNewShape( \
node->getType(ArithmeticNode::ResultIdx), \
LTR->getInput().getType()->dims()), \
LTR->getInput(), RTR->getInput()); \
break;
#define BOOLEAN_OP_CASE(NODE_NAME_) \
case glow::Kinded::Kind::NODE_NAME_##NodeKind: \
newAN = F->create##NODE_NAME_(node->getName(), LTR->getInput(), \
RTR->getInput()); \
break;
switch (node->getKind()) {
ARITHMETIC_CASE(Add);
ARITHMETIC_CASE(Mul);
ARITHMETIC_CASE(Sub);
ARITHMETIC_CASE(Div);
ARITHMETIC_CASE(Max);
ARITHMETIC_CASE(Min);
BOOLEAN_OP_CASE(CmpLTE);
BOOLEAN_OP_CASE(CmpEQ);
default:
llvm_unreachable("Unhandled node");
}
#undef BOOLEAN_OP_CASE
#undef ARITHMETIC_CASE
newAN->setPredicate(node->getPredicate());
changed = true;
auto *newTR =
F->createTranspose(LTR->getName(), newAN, LTR->getShuffle());
newTR->setPredicate(node->getPredicate());
node->getNthResult(ArithmeticNode::ResultIdx).replaceAllUsesOfWith(newTR);
}
// Sink Transpose below RescaleQuantized.
// Potentially exposes opportunity to be combined up with Convolution.
// If it doesn't work out it will be re-sinked later.
if (auto *RQ = dyn_cast<RescaleQuantizedNode>(node)) {
auto *TR = dyn_cast<TransposeNode>(RQ->getInput());
if (!TR) {
continue;
}
auto newRQType = F->getParent()->uniqueTypeWithNewShape(
RQ->getResult().getType(), TR->getInput().getType()->dims());
auto *newRQ =
F->createRescaleQuantized(RQ->getName(), TR->getInput(), newRQType);
auto *newTR = F->createTranspose(TR->getName(), newRQ, TR->getShuffle());
RQ->getResult().replaceAllUsesOfWith(newTR);
changed = true;
}
// Sink RELU below batch concat nodes.
if (auto *CN = dyn_cast<ConcatNode>(node)) {
llvm::SmallVector<NodeValue, 6> CNInputs;
for (auto &input : CN->getInputs()) {
auto *inputRL = dyn_cast<ReluNode>(input);
if (!inputRL) {
break;
}
CNInputs.push_back(inputRL->getInput());
}
if (CNInputs.size() == CN->getNumInputs()) {
auto *newCN = F->createConcat(CN->getName(), CNInputs, CN->getDim());
newCN->setPredicate(node->getPredicate());
auto name = CN->getNthInput(0).getNode()->getName();
auto *newRL = F->createRELU(name, newCN, CN->getResult().getType());
newRL->setPredicate(node->getPredicate());
CN->getResult().replaceAllUsesOfWith(newRL);
changed = true;
}
}
// Sink Transpose below concat nodes.
if (auto *CN = dyn_cast<ConcatNode>(node)) {
llvm::SmallVector<NodeValue, 6> transVector;
auto inputIter = CN->getInputs().begin();
auto *firstInput = dyn_cast<TransposeNode>(*inputIter);
if (!firstInput) {
continue;
}
transVector.push_back(firstInput->getInput());
auto shuffle = firstInput->getShuffle();
// If the shuffle masks don't agree or not all inputs are Transpose then
// bail out.
for (++inputIter; inputIter != CN->getInputs().end(); ++inputIter) {
auto *tTR = dyn_cast<TransposeNode>(*inputIter);
if (!tTR || tTR->getShuffle() != shuffle) {
break;
}
transVector.push_back(tTR->getInput());
}
if (transVector.size() != CN->getNumInputs()) {
continue;
}
// Figure out where we transposed the channel index for batch
// normalization.
unsigned_t idx = CN->getDim();
unsigned_t newChannelIdx = shuffle[idx];
auto *newCN = F->createConcat(CN->getName(), transVector, newChannelIdx);
newCN->setPredicate(node->getPredicate());
auto *newTR = F->createTranspose(firstInput->getName(), newCN,
firstInput->getShuffle());
newTR->setPredicate(node->getPredicate());
CN->getResult().replaceAllUsesOfWith(newTR);
changed = true;
}
} // For all nodes in the graph.
return changed;
}
/// \returns True if node A may depend on the result of B. The relationship
/// between the nodes does not have to be direct. For example, A can depend on
/// X which depends on B. In that case the method needs to return True.
/// Check the use-def dependency up to a depth of \p depth.
static bool mayDepend(Node *A, Node *B, unsigned depth = 6) {
// We define the identify as a dependency.
if (A == B) {
return true;
}
// A does not depend on anything.
if (A->getNumInputs() == 0) {
return false;
}
// B has no users. Nothing can depend on it.
if (B->getNumResults() == 0) {
return false;
}
// We can't continue the search. Assume that the nodes depend on one another.
if (depth == 0) {
return true;
}
// Check all inputs of A. None of them may depend on B.
for (int i = 0, e = A->getNumInputs(); i < e; i++) {
auto *input = A->getNthInput(i).getNode();
// The inputs of A must not depend on B.
if (mayDepend(input, B, depth - 1)) {
return true;
}
}
// We checked all inputs of A and none of them depend on B.
return false;
}
/// \returns True if the node \p N depends on any of the values in \p list, or
/// if any of the values in list depend on \p N.
static bool mayDependOnAny(llvm::ArrayRef<NodeValue> list, Node *N) {
for (auto &ll : list) {
if (mayDepend(ll.getNode(), N) || mayDepend(N, ll.getNode())) {
return true;
}
}
return false;
}
// Merge several two or more multiple matrix multiplications into a single
// large matmul. The large matmul is more likely to utilize the hardware. The
// result of the big matmul is the concatenated results.
//
// ____ _________ _________
// ---- | | | | M| A * C |
// M| A | T| B | * K| C | = |---------|
// ---- , | | | | T| B * C |
// K ---- --------- ---------
// K R R
bool MergeMatMul::run(Function *F) {
LOG_SCOPE(F->getLogContext(), getName());
bool changed = false;
auto &nodes = F->getNodes();
// These two maps record the list of matrix multipliers that use each node
// value either as a right-hand-side user or a left-hand-user.
llvm::DenseMap<Node *, std::vector<MatMulNode *>> rightMatrixUsers;
llvm::DenseMap<Node *, std::vector<MatMulNode *>> leftMatrixUsers;
// Collect the list of nodes that are used by the matrix multiplier.
for (auto &node : nodes) {
if (auto *MM = dyn_cast<MatMulNode>(&node)) {
// Do not try to merge quantized matrix multiplications because their
// quantized parameters may not match. Until we implement the logic to
// match the scale and offset just avoid the optimization.
if (MM->getResult().getType()->isQuantizedType()) {
continue;
}
rightMatrixUsers[MM->getRHS().getNode()].push_back(MM);
leftMatrixUsers[MM->getLHS().getNode()].push_back(MM);
}
}
// Merge RHS matrices.
for (auto &it : rightMatrixUsers) {
auto &MMs = it.second;
// Collects the LHS values to merge.
std::vector<NodeValue> LHS;
// For each matmul that depends on the rhs matrix.
for (auto &MM : MMs) {
auto L = MM->getLHS();
// The operands to the matrix multiplier should not depend on one another
// or else we won't be able to get rid of the original matrix
// multiplication.
if (mayDependOnAny(LHS, L.getNode())) {
continue;
}
LHS.push_back(L);
}
// We need to have at least two matrices to merge.
if (LHS.size() < 2) {
continue;
}
// Merge the matmul:
auto *CC = F->createConcat("mergeLHS", LHS, 0);
auto *MM = F->createMatMul("bigMatMul", CC, it.first);
size_t R = MM->getResult().dims()[1];
size_t start = 0;
for (auto *origMM : MMs) {
size_t H = origMM->getResult().dims()[0];
auto *ex = F->createSlice("extract", MM, {start, 0}, {start + H, R});
start += H;
origMM->getResult().replaceAllUsesOfWith(ex);
changed = true;
}
}
return changed;
}
bool MergePadIntoConvolution::run(Function *F) {
LOG_SCOPE(F->getLogContext(), getName());
bool changed = false;
for (auto &node : F->getNodes()) {
auto *CN = dyn_cast<ConvolutionNode>(&node);
if (!CN) {
continue;
}
auto *PN = dyn_cast<PadNode>(CN->getInput());
if (!PN) {
continue;
}
// Convolution only supports padding with 0 constant
if ((PN->getMode() != PaddingMode::CONSTANT) || (PN->getValue() != 0.f)) {
continue;
}
// The convolution needs to be the unique user
if (!PN->hasOneUse()) {
continue;
}
// Compute the new padding.
// Note: - convolution only supports positive padding
// - the convolution takes NHWC input tensors.
bool canMerge = true;
auto padPads = PN->getPads();
auto convPads = CN->getPads();
// For now, there is a different interpretation of the ONNX spec for
// Pad and Convolution. The 'pads' array won't have the same size because
// only spatial dimensions are specified for the convolution while all
// dimensions are specified for Pad.
// The merge can apply only if no padding is requested for non spatial
// dimensions.
if ((padPads[0] != 0) || (padPads[3] != 0) || (padPads[4] != 0) ||
(padPads[7] != 0)) {
continue;
}
// Compute new spatial padding.
const int H_INDEX = 1;
std::vector<unsigned_t> newConvPads(4);
auto numDims = PN->getResult().dims().size();
for (size_t i = 0; i < 2; i++) {
// Two pad integers per dimension (begin and end padding).
for (size_t j = 0; j < 2; j++) {
int newConvPadSigned =
padPads[(i + H_INDEX) + j * numDims] + int(convPads[i + j * 2]);
if (newConvPadSigned < 0) {
canMerge = false;
break;
}
newConvPads[i + j * 2] = unsigned_t(newConvPadSigned);
}
}
if (!canMerge) {
continue;
}
// New Convolution
auto *newCN = F->createConv(CN->getName(), PN->getInput(), CN->getFilter(),
CN->getBias(), CN->getResult().getType(),
CN->getKernels(), CN->getStrides(), newConvPads,
CN->getGroup(), CN->getDilation());
CN->getResult().replaceAllUsesOfWith(newCN);
changed = true;
}
return changed;
}
/// Merge Transpose into MatMul or FC.
/// MatMul/FC(Reshape(Transpose(X)), Weights) ->
/// -> MatMul/FC(Reshape(X), reordered Weights)
/// Common sequence while using NCHW as input layout, because GLOW convolution
/// layout is NHWC:
/// Transpose([N, H, W, C]) -> [N, C, H, W]
/// Reshape([N, C, H, W]) -> [N, C * H * W]
/// MatMul/FC([N, C * H * W], [C * H * W, K]) -> [N, K]
bool MergeTransposeIntoMatMulOrFC::run(Function *F) {
LOG_SCOPE(F->getLogContext(), getName());
bool changed = false;
for (auto &node : F->getNodes()) {
auto *MMN = dyn_cast<MatMulNode>(&node);
auto *FCN = dyn_cast<FullyConnectedNode>(&node);
Constant *W;
ReshapeNode *RN;
// Node is either MatMul or FC.
if (MMN) {
W = dyn_cast<Constant>(MMN->getRHS());
RN = dyn_cast<ReshapeNode>(MMN->getLHS());
} else if (FCN) {
W = dyn_cast<Constant>(FCN->getWeights());
RN = dyn_cast<ReshapeNode>(FCN->getInput());
} else {
continue;
}
// Weights node (or MatMul RHS) is constant.
if (!W) {
continue;
}
// Linearizing Reshape precedes MatMul/FC.
// The first dimension must be kept unchanged, the others are linearized.
if (!RN || !RN->hasOneUse() ||
RN->getInput().dims()[0] != RN->getDims()[0]) {
continue;
}
// Transpose precedes Reshape.
// The first dimension must be kept unchanged, the others can be shuffled
// in any way.
auto *TN = dyn_cast<TransposeNode>(RN->getInput());
if (!TN || !TN->hasOneUse() || TN->getShuffle()[0] != 0) {
continue;
}
// MatMul/FC weights tensor is 2D. De-linearize the first dimension
// according to Transpose output layout (original shape) and input layout
// (reordered shape). Then we can do weights reordering by simply
// transposing the tensor from original shape to reordered shape.
//
// Example for [N, H, W, C] -> [N, C, H, W] transpose (common case):
// De-linearized original shape: [C * H * W, K] -> [C, H, W, K]
// De-linearized reordered shape: [C * H * W, K] -> [H, W, C, K]
// Reorder weights by transposing them: [C, H, W, K] -> [H, W, C, K]
ShapeVector shape, newShape;
llvm::SmallVector<unsigned_t, max_tensor_dimensions> shuffle;
shuffle.resize(TN->getShuffle().size() - 1);
for (size_t i = 1; i < TN->getShuffle().size(); i++) {
shape.push_back(TN->getResult().getType()->dims()[i]);
newShape.push_back(TN->getInput().getType()->dims()[i]);
shuffle[TN->getShuffle()[i] - 1] = i - 1;
}
shape.push_back(W->dims()[1]);
newShape.push_back(W->dims()[1]);
shuffle.push_back(TN->getShuffle().size() - 1);
auto reshapedWTy =
F->getParent()->uniqueTypeWithNewShape(W->getType(), shape);
auto reshapedNewWTy =
F->getParent()->uniqueTypeWithNewShape(W->getType(), newShape);
// New reordered weights.
auto *newW = F->getParent()->createConstant(W->getType(), W->getName());
Tensor reshapedSrc(W->getPayload().getUnsafePtr(), reshapedWTy);
Tensor reshapedDst(newW->getPayload().getUnsafePtr(), reshapedNewWTy);
reshapedSrc.transpose(&reshapedDst, shuffle);
// New Reshape and MatMul/FC.
auto *newRN =
F->createReshape(RN->getName(), TN->getInput(), RN->getDims());
if (MMN) {
auto *newMMN = F->createMatMul(MMN->getName(), MMN->getResult().getType(),
newRN, newW);
MMN->getResult().replaceAllUsesOfWith(newMMN);
} else if (FCN) {
auto *newFCN =
F->createFullyConnected(FCN->getName(), newRN, newW, FCN->getBias(),
FCN->getResult().getType());
FCN->getResult().replaceAllUsesOfWith(newFCN);
} else {
llvm_unreachable("Unexpected node kind");
}
changed = true;
}
return changed;
}
/// \returns True if the two slices \p A and \p B access consecutive spacial
/// regions on the \p dim dimension. For example Slice(0..10) Slice(10..50)
/// are consecutive but Slice(0..10) Slice(20..30) are not.
static bool areSlicesConsecutive(SliceNode *A, SliceNode *B, unsigned_t dim) {
// The slices must extract from the same input.
if (A->getInput().getNode() != B->getInput().getNode()) {
return false;
}
// The result element type must be identical.
if (A->getResult().getType()->getElementType() !=
B->getResult().getType()->getElementType()) {
return false;
}
auto aStart = A->getStart();
auto bStart = B->getStart();
assert(aStart.size() > dim && "Invalid dimension");
for (size_t i = 0, e = aStart.size(); i < e; i++) {
if (i == dim) {
auto resSize = A->getResult().dims();
// This is the stride (the delta between the two slices on the requested
// dimension).
auto delta = bStart[i] - aStart[i];
// The distance between the two slices must be identical to the size of
// the result.
if (resSize[dim] != delta) {
return false;
}
continue;
}
// The non-consecutive dimensions must be identical.
if (aStart[i] != bStart[i]) {
return false;
}
}
return true;
}
bool ConvertBroadcastedBatchMatMul::run(Function *F) {
LOG_SCOPE(F->getLogContext(), getName());
bool changed = false;
for (auto &node : F->getNodes()) {
BatchMatMulNode *BMMN = dyn_cast<BatchMatMulNode>(&node);
if (!BMMN) {
continue;
}
NodeValue LHS = BMMN->getLHS();
NodeValue RHS = BMMN->getRHS();
// If RHS is a Tile along axis 0 and the input's dims()[0] == 1, then the
// RHS is fully broadcasted and we can perform the optimization.
TileNode *TN = dyn_cast<TileNode>(RHS);
if (!TN || TN->getAxis() != 0 || TN->getInput().dims()[0] != 1) {
continue;
}
// Can now convert the broadcasted BatchMatMul to a MatMul.
// LHS = {numBatches, N, M}
// RHS = {M, P}
// Multiply each LHS matrix {N, M} by RHS {M, P} to get final matrix
// {numBatches, N, P}
const size_t numBatches = LHS.dims()[0];
const size_t N = LHS.dims()[1];
const size_t M = LHS.dims()[2];
const size_t P = RHS.dims()[2];
auto name = BMMN->getName();
// Reshape the LHS to be a two-dimensional matrix, where each batch is
// essentially concatenated onto itself in the 0th dimension.
ReshapeNode *reshapeLHS =
F->createReshape(name.str() + ".reshapeLHS", LHS, {numBatches * N, M});
// Squeeze out the first dimension of the original Tile's input.
ReshapeNode *squeezedRHS =
F->createSqueeze(name.str() + ".squeezedRHS", TN->getInput(), {0});
// Perform a normal matmul, implementing the batch matmul.
MatMulNode *MMN = F->createMatMul(name, reshapeLHS, squeezedRHS);
assert(MMN->getResult().dims()[0] == (numBatches * N) &&
"Incorrect resulting dimension for batch matmul");
assert(MMN->getResult().dims()[1] == P &&
"Incorrect resulting dimension for batch matmul");
// Reshape the result back to the expected batch output shape, with the
// first dimension the number of batches.
ReshapeNode *finalReshape = F->createReshape(name.str() + ".reshapeResult",
MMN, {numBatches, N, P});
BMMN->getResult().replaceAllUsesOfWith(finalReshape);
changed = true;
}
return changed;
}
/// Find a sequence of slices in \p input that span the whole input.
/// \returns True if a group of slices that span the whole input was found.
/// The order of the slices is recorded in \p order.
static bool findSlicesThatSpanInput(llvm::ArrayRef<SliceNode *> input,
unsigned_t dimension,
std::vector<SliceNode *> &order) {
// This is the 'last' slice to be found in the sequence of slices.
SliceNode *lastSlice = nullptr;
// Find the 'first' slice in the sequence.
for (SliceNode *SN : input) {
auto start = SN->getStart();
// Invalid dimension.
if (start.size() <= dimension) {
return false;
}
// Check if this slice extract the first element.
if (start[dimension] == 0) {
// We found the first element.
lastSlice = SN;
order.push_back(lastSlice);
break;
}