-
Notifications
You must be signed in to change notification settings - Fork 699
/
Copy pathGraphOptimizer.cpp
7884 lines (7033 loc) · 286 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) 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 "glow/Optimizer/GraphOptimizer/GraphOptimizer.h"
#include <folly/String.h>
#include "glow/Backend/Backend.h"
#include "glow/Converter/Float16Converter.h"
#include "glow/Converter/FusedRowwiseConverter.h"
#include "glow/Converter/TypeAToTypeBFunctionConverter.h"
#include "glow/Flags/Flags.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/TensorLayout.h"
#include "glow/Graph/Utils.h"
#include "glow/Graph/VerifierHelper.h"
#include "glow/Optimizer/GraphOptimizer/FunctionPassPipeline.h"
#include "glow/Optimizer/GraphOptimizer/FunctionPasses.h"
#include "glow/Optimizer/Lower/Lower.h"
#include "glow/PassManager/PassManager.h"
#include "glow/Quantization/Base/Base.h"
#include "glow/Quantization/Quantization.h"
#include "glow/Runtime/RuntimeTypes.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include <algorithm>
#include <numeric>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// Utility macro to continue loop if given condition is not met.
// This is intended to improve code readability and size.
#define CONTINUE_IF_NOT(cond) \
if (!(cond)) { \
continue; \
}
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. "
"A value equal to 0 means no limit. Default is 0."),
llvm::cl::Optional, llvm::cl::init(0), 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;
}
// Don't delete fused nodes.
if (N->isFused()) {
return false;
}
return true;
}
ConstantModificationPreventer::ConstantModificationPreventer(
Module &mod, CompilationContext &cctx)
: ScopeGuard([&]() {
// Ensure we cleanup Placeholder-Constant swap if necessary.
auto &PHs = mod_.getPlaceholders();
for (auto &pair : tmpPHToConstMap_) {
Placeholder *tmpPH = pair.first;
Constant *C = pair.second;
tmpPH->getOutput().replaceAllUsesOfWith(C->getOutput());
mod_.erasePlaceholder(std::find(PHs.begin(), PHs.end(), tmpPH));
}
cctx_.optimizationOpts.enableConstantFolding =
origEnableConstantFolding_;
}),
mod_(mod), cctx_(cctx),
origEnableConstantFolding_(cctx.optimizationOpts.enableConstantFolding) {
// By default dismiss until explicitly activated.
dismissed_ = true;
}
void ConstantModificationPreventer::activate() {
dismissed_ = false;
// Prevent Constant modification by temporarily replacing them with PHs.
for (Constant *C : mod_.getConstants()) {
// Note: These temp Placeholders are more like static Placeholders, but we
// don't want to set them as static here because optimizations may kick in
// to modify the type of the static Placeholder (see
// cctx.optimizationOpts.foldStaticPlaceholderConversions).
Placeholder *tmpPH = mod_.createPlaceholder(
C->getType(), C->getName().str() + "_SWAP_CONST_FOLD",
/* isTrainable */ false, C->getLayout());
tmpPHToConstMap_[tmpPH] = C;
cctx_.optimizationOpts.tempPHsForConstants.insert(tmpPH);
C->getOutput().replaceAllUsesOfWith(tmpPH->getOutput());
}
// Disable constant folding temporarily; restored later by the scope guard.
cctx_.optimizationOpts.enableConstantFolding = false;
}
/// Helper that \returns true if all functions in \p mod are loaded.
static bool areAllFunctionsLoaded(Module *mod) {
for (auto *MF : mod->getFunctions()) {
if (MF->getState() < FunctionState::FuncLoaded) {
return false;
}
}
return true;
}
/// Helper that \returns the shuffle that inverts \p shuffle. For example, if
/// \p shuffle is {3, 0, 1, 2}, then this function returns {1, 2, 3, 0}.
static llvm::SmallVector<unsigned_t, max_tensor_dimensions>
invertShuffle(llvm::ArrayRef<unsigned_t> shuffle) {
llvm::SmallVector<unsigned_t, max_tensor_dimensions> invertedShuffle;
invertedShuffle.resize(shuffle.size());
for (size_t i = 0; i < shuffle.size(); ++i) {
invertedShuffle[shuffle[i]] = i;
}
return invertedShuffle;
}
/// Add a TranposeNode after \p C in \p F that has the same shuffle as \p TR.
/// This funcion assumes that the type of \p C and the output type of \p TR are
/// the same. \returns the newly added TransposeNode.
static TransposeNode *insertMatchingTransposeAfterConstant(Function *F,
Constant *C,
TransposeNode *TR) {
const auto *CT = C->getOutput().getType();
const auto *TRT = TR->getResult().getType();
DCHECK(CT->isEqual(*TRT, /* allowDifferentShape */ false,
/* allowDifferentStride */ false,
/* allowDifferentScaleOffset */ true));
auto &T = C->getPayload();
// In order for a new Transpose node with the same shuffle as TR to be created
// at the output of the Constant, a new Constant with the same dimension as
// the input of TR should be created. Note that the original scale and offset
// should be kept for quantized types.
auto newConstTy =
F->getParent()->uniqueTypeWithNewShape(CT, TR->getInput().dims());
auto *NC = F->getParent()->createConstant(newConstTy,
C->getName().str() + ".transposed");
// The payload of the original Constant C has the same type as the
// output of TR. In order to preserve correctness, this payload must
// be transposed using the inverse of the shuffle of TR and stored
// into the payload of the new Constant.
//
// Another way to think of this is that we are inserting two
// Transposes that are inverses of each other back to back after the original
// Constant. The shuffle of the second Transpose must match that of TR.
// In order to preserve correctness, the shuffle
// of the first Transpose must be the inverse of that shuffle of the
// second Transpose. The statement below statically computes this
// first Transpose.
T.transpose(&NC->getPayloadMutable(), invertShuffle(TR->getShuffle()));
// Create Transpose on the LHS that has the same shuffle as TR.
return F->createTranspose("transpose", NC, TR->getShuffle());
}
bool EmptyPass::run(Function *F, const CompilationContext &cctx) {
return false;
}
bool DCE::run(Function *F, const CompilationContext &cctx) {
LOG_SCOPE(F->getLogContext(), getName());
auto &nodes = F->getNodes();
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;
}
}
// Don't remove unused Constants since many may be temporarily unused during
// optimizations.
if (cctx.optimizationOpts.delayAndRecordConstantModification) {
return changed;
}
if (!areAllFunctionsLoaded(F->getParent())) {
return changed;
}
// Delete unused Constants.
deleteUnusedConstants(*F->getParent());
return changed;
}
void glow::deleteUnusedConstants(Module &mod) {
auto &consts = mod.getConstants();
std::vector<ConstList::iterator> erasedConsts{};
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();
mod.eraseConstant(it);
erasedConsts.pop_back();
}
}
/// \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 NodeValue or the original node's first result.
static NodeValue 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(),
TR->getLayout());
CS->getResult().replaceAllUsesOfWith(newTR);
return true;
}
/// Given \p CN from \p F, determines if all inputs are ConvertTo that use the
/// same scale/offset/kind, and if so creates and \returns a new concat with all
/// inputs as the inputs from the ConvertTo inputs. Otherwise \returns nullptr.
static ConcatNode *setupConvertToSinkBelowConcat(Function *F, ConcatNode *CN) {
// Check if all inputs are ConvertTo.
std::vector<ConvertToNode *> inputNodes;
inputNodes.reserve(CN->getInputs().size());
for (auto &concatInput : CN->getInputs()) {
auto *CT = dyn_cast<ConvertToNode>(concatInput);
if (!CT) {
return nullptr;
}
inputNodes.push_back(CT);
}
// Gather all inputs of the nodes in inputNodes here.
std::vector<NodeValue> newInputs;
newInputs.reserve(inputNodes.size());
newInputs.push_back(inputNodes[0]->getInput());
// Get the CN's first input's result and input types to check against all
// other CN inputs.
const TypeRef firstResultTy = inputNodes[0]->getResult().getType();
const TypeRef firstInputTy = inputNodes[0]->getInput().getType();
// Check that all inputs have the same output and input element type.
for (size_t i = 1, e = inputNodes.size(); i < e; i++) {
const TypeRef currResultTy = inputNodes[i]->getResult().getType();
const TypeRef currInputTy = inputNodes[i]->getInput().getType();
if (currResultTy->getElementType() != firstResultTy->getElementType()) {
return nullptr;
}
if (firstResultTy->isQuantizedType()) {
if (currResultTy->getScale() != firstResultTy->getScale() ||
currResultTy->getOffset() != firstResultTy->getOffset()) {
return nullptr;
}
}
if (currInputTy->getElementType() != firstInputTy->getElementType()) {
return nullptr;
}
if (firstInputTy->isQuantizedType()) {
if (currInputTy->getScale() != firstInputTy->getScale() ||
currInputTy->getOffset() != firstInputTy->getOffset()) {
return nullptr;
}
}
newInputs.push_back(inputNodes[i]->getInput());
}
// Create and return a new ConcatNode with newInputs.
return F->createConcat(CN->getName(), newInputs, CN->getDim());
}
/// Given \p CN from \p F, determines if all inputs are either Quantize or
/// Dequantize (depending on \p QuantNodeClass) that use the same
/// scale/offset/kind, and if so creates and \returns a new concat with all
/// inputs as the inputs from the Quantize or Dequantize inputs. Otherwise
/// \returns nullptr.
template <class QuantNodeClass>
static ConcatNode *setupQuantDequantSinkBelowConcat(Function *F,
ConcatNode *CN) {
constexpr bool isQuant = std::is_same<QuantizeNode, QuantNodeClass>::value;
constexpr bool isDeq = std::is_same<DequantizeNode, QuantNodeClass>::value;
static_assert(isQuant || isDeq, "setupQuantDequantSinkBelowConcat() only "
"supports Quantize/Dequantize nodes.");
// Check if all inputs are Quantize with the same input
// scale/offset/ElemKind.
std::vector<QuantNodeClass *> qNodes;
qNodes.reserve(CN->getInputs().size());
for (auto &concatInput : CN->getInputs()) {
QuantNodeClass *Q = dyn_cast<QuantNodeClass>(concatInput);
if (!Q) {
return nullptr;
}
qNodes.push_back(Q);
}
// Gather all inputs of the nodes in qNodes here.
std::vector<NodeValue> newInputs;
newInputs.reserve(qNodes.size());
newInputs.push_back(qNodes[0]->getInput());
// Check the CN's first input's type to check against all other inputs. Use
// the output of Quantize or input of Dequantize.
const TypeRef firstTy = isQuant ? qNodes[0]->getResult().getType()
: qNodes[0]->getInput().getType();
// Check that all inputs have the same scale/offset/type.
for (size_t i = 1, e = qNodes.size(); i < e; i++) {
const TypeRef currTy = isQuant ? qNodes[i]->getResult().getType()
: qNodes[i]->getInput().getType();
if (currTy->getScale() != firstTy->getScale() ||
currTy->getOffset() != firstTy->getOffset() ||
currTy->getElementType() != firstTy->getElementType()) {
return nullptr;
}
newInputs.push_back(qNodes[i]->getInput());
}
// Create and return a new ConcatNode with newInputs.
return F->createConcat(CN->getName(), newInputs, CN->getDim());
}
/// Given \p CN from \p F, determines if all inputs are Tanh
/// and if so creates and \returns a new concat with all
/// inputs as the inputs from the Tanh inputs. Otherwise
/// \returns nullptr.
static ConcatNode *setupTanhSinkBelowConcat(Function *F, ConcatNode *CN) {
// Check if all inputs are Tanh
std::vector<TanhNode *> tanhNodes;
tanhNodes.reserve(CN->getInputs().size());
for (auto &concatInput : CN->getInputs()) {
TanhNode *T = dyn_cast<TanhNode>(concatInput);
if (!T) {
return nullptr;
}
tanhNodes.push_back(T);
}
// Gather all inputs of the nodes in tanhNodes.
std::vector<NodeValue> newInputs;
newInputs.reserve(tanhNodes.size());
for (size_t i = 0, e = tanhNodes.size(); i < e; i++) {
newInputs.emplace_back(tanhNodes[i]->getInput());
}
// Create and return a new ConcatNode with newInputs.
return F->createConcat(CN->getName(), newInputs, CN->getDim());
}
bool SinkConversions::run(Function *F, const CompilationContext &cctx) {
LOG_SCOPE(F->getLogContext(), getName());
bool changed = false;
auto &nodes = F->getNodes();
// For each node:
for (auto &N : nodes) {
ConcatNode *CN = dyn_cast<ConcatNode>(&N);
if (!CN) {
continue;
}
const Node *firstNode = CN->getInputs().front().getNode();
// Sink Dequantize below Concat nodes.
if (firstNode->getKind() == Kinded::Kind::DequantizeNodeKind) {
ConcatNode *newCN =
setupQuantDequantSinkBelowConcat<DequantizeNode>(F, CN);
if (!newCN) {
continue;
}
DequantizeNode *newDequantize =
F->createDequantize(CN->getName().str() + "_dequantize", newCN,
CN->getResult().getType());
CN->getResult().replaceAllUsesOfWith(newDequantize->getResult());
changed = true;
continue;
}
// Sink Quantize below Concat nodes.
if (firstNode->getKind() == Kinded::Kind::QuantizeNodeKind) {
ConcatNode *newCN = setupQuantDequantSinkBelowConcat<QuantizeNode>(F, CN);
if (!newCN) {
continue;
}
const TypeRef QTy =
llvm::cast<QuantizeNode>(firstNode)->getResult().getType();
const TypeRef concatQTy = F->getParent()->uniqueType(
QTy->getElementType(), newCN->getResult().dims(), QTy->getScale(),
QTy->getOffset());
QuantizeNode *newQuantize = F->createQuantize(
CN->getName().str() + "_quantize", newCN, concatQTy);
CN->getResult().replaceAllUsesOfWith(newQuantize->getResult());
changed = true;
continue;
}
// Sink ConvertTo below Concat nodes.
if (firstNode->getKind() == Kinded::Kind::ConvertToNodeKind) {
ConcatNode *newCN = setupConvertToSinkBelowConcat(F, CN);
if (!newCN) {
continue;
}
auto *newConvertTo =
F->createConvertTo(CN->getName().str() + "_convert_to", newCN,
CN->getResult().getType());
CN->getResult().replaceAllUsesOfWith(newConvertTo->getResult());
changed = true;
continue;
}
// Sink Tanh below Concat nodes.
if (cctx.optimizationOpts.sinkTanhBelowConcat) {
if (firstNode->getKind() == Kinded::Kind::TanhNodeKind) {
ConcatNode *newCN = setupTanhSinkBelowConcat(F, CN);
if (!newCN) {
continue;
}
const TypeRef TTy =
llvm::cast<TanhNode>(firstNode)->getResult().getType();
const TypeRef concatTy = F->getParent()->uniqueType(
TTy->getElementType(), newCN->getResult().dims());
TanhNode *newTanh =
F->createTanh(CN->getName().str() + "_tanh", concatTy, newCN);
CN->getResult().replaceAllUsesOfWith(newTanh->getResult());
changed = true;
continue;
}
}
}
return changed;
}
/// Sink Quantize(Concat(...)) -> Concat(Quantize(...)). This allows for
/// concatenating less data, and if there are some inputs that are already
/// quantized and are being dequantized just for the concat then we can skip
/// this conversion.
bool SinkConcatBelowQuantize::run(Function *F, const CompilationContext &cctx) {
LOG_SCOPE(F->getLogContext(), getName());
bool changed = false;
auto &nodes = F->getNodes();
// For each node:
for (auto &N : nodes) {
QuantizeNode *QN = dyn_cast<QuantizeNode>(&N);
if (!QN) {
continue;
}
ConcatNode *CN = dyn_cast<ConcatNode>(QN->getInput());
if (!CN || CN->getNumUsers() > 1) {
continue;
}
// For all inputs to the current CN, add quantize nodes to them all using
// the same scale/offset as QN and put the quantize nodes in newQuantInputs.
std::vector<NodeValue> newQuantInputs;
for (const NodeValue &inCN : CN->getInputs()) {
TypeRef newOutTy = F->getParent()->uniqueTypeWithNewShape(
QN->getResult().getType(), inCN.dims());
QuantizeNode *quantInCN = F->createQuantize(
inCN.getNode()->getName().str() + "_quant", inCN, newOutTy);
newQuantInputs.push_back(quantInCN);
}
// Create a new CN with the quantized inputs and replace QN with it.
ConcatNode *newCN =
F->createConcat(CN->getName(), newQuantInputs, CN->getDim());
QN->getResult().replaceAllUsesOfWith(newCN->getResult());
changed = true;
}
return changed;
}
/// If \p N is a TransposeNode with all of the same node kind of users, then
/// \returns that TransposeNode, else \returns nullptr. For example, if \p N is
/// a TransposeNode with two QuantizeNode users, this will return the
/// TransposeNode, but if it had one QuantizeNode and one MatMul node then it
/// will return nullptr.
static TransposeNode *getTransposeNodeWithAllSameUserKind(Node *N) {
auto *TN = dyn_cast<TransposeNode>(N);
if (!TN) {
return nullptr;
}
if (TN->getNumUsers() <= 1) {
return TN;
}
auto firstKind = N->getUsers().front().getUser()->getKind();
for (auto &U : N->getUsers()) {
if (U.getUser()->getKind() != firstKind) {
return nullptr;
}
}
return TN;
}
/// Code Sinking.
bool SinkCode::run(Function *F, const CompilationContext &cctx) {
LOG_SCOPE(F->getLogContext(), getName());
bool changed = false;
auto &nodes = F->getNodes();
// For each node:
for (auto &N : nodes) {
auto *node = &N;
// Sink Reshape/Transpose below BatchNormalization.
if (auto *BN = dyn_cast<BatchNormalizationNode>(node)) {
// Sink Reshape below BatchNormalization.
if (auto *RS = dyn_cast<ReshapeNode>(BN->getInput())) {
auto inDims = RS->getInput().dims();
auto outDims = RS->getResult().dims();
unsigned_t newChannelIdx;
// Skip sinking if: 1) the input was less than 3 dimensions,
// because we need spatial dimensions in addition to batch
// and channel or 2) if it is 3D data because the reshapes
// are deliberately introduced to phrase 3D BatchNormalization
// as a 2D one.
if (RS->getInput().dims().size() < 3 ||
RS->getInput().dims().size() == 5) {
continue;
}
// Reshape should not change the BatchNorm ChannelIdx dimensions.
// Only NH[W]C and NCH[W] are allowed.
if (BN->getChannelIdx() == outDims.size() - 1) {
if (inDims[inDims.size() - 1] != outDims[outDims.size() - 1]) {
continue;
}
newChannelIdx = inDims.size() - 1;
} else if (BN->getChannelIdx() == 1) {
// Note: index '1' maps to C in NCH[W] layout.
if (inDims[1] != outDims[1]) {
continue;
}
newChannelIdx = 1;
} else {
continue;
}
// Reshape should not change the batch dimension.
if (inDims[0] != outDims[0]) {
continue;
}
auto bnOutTy = F->getParent()->uniqueTypeWithNewShape(
BN->getResult().getType(), RS->getInput().getType());
auto rsInputType = RS->getInput().getType();
glow::TypeRef outTy = F->getParent()->uniqueTypeWithNewShape(
bnOutTy, rsInputType->dims());
auto *newBN = F->createBatchNormalization(
BN->getName(), outTy, RS->getInput(), BN->getBias(), BN->getScale(),
BN->getMean(), BN->getVar(), newChannelIdx, BN->getEpsilon(),
BN->getMomentum());
auto *newRS = F->createReshape(RS->getName(), newBN,
RS->getResult().dims(), RS->getLayout());
BN->getResult().replaceAllUsesOfWith(newRS);
changed = true;
continue;
}
// Sink Transpose below batch normalization nodes:
if (auto *TR = dyn_cast<TransposeNode>(BN->getInput())) {
// Figure out where we transposed the channel index for batch
// normalization.
unsigned_t idx = BN->getChannelIdx();
unsigned_t newChannelIdx = TR->getShuffle()[idx];
auto bnOutTy = BN->getResult().getType();
auto trInputType = TR->getInput().getType();
glow::TypeRef outTy = F->getParent()->uniqueTypeWithNewShape(
bnOutTy, trInputType->dims());
auto *NewBN = F->createBatchNormalization(
BN->getName(), outTy, 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(),
TR->getLayout());
newTR->setPredicate(node->getPredicate());
BN->getResult().replaceAllUsesOfWith(newTR);
changed = true;
continue;
}
}
if (auto *RL = dyn_cast<ReluNode>(node)) {
// Sink Transpose below batch RELU nodes.
if (auto *TR = dyn_cast<TransposeNode>(RL->getInput())) {
// 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().getType());
auto *NRL = F->createRELU(RL->getName(), TR->getInput(), reluOutTy);
NRL->setPredicate(node->getPredicate());
auto *newTR = F->createTranspose(TR->getName(), NRL, TR->getShuffle(),
TR->getLayout());
newTR->setPredicate(node->getPredicate());
RL->getResult().replaceAllUsesOfWith(newTR);
changed = true;
continue;
}
// Sink Clip below RELU nodes.
if (ClipNode *CN = dyn_cast<ClipNode>(RL->getInput())) {
assert(!RL->getResult().getType()->isQuantizedType() &&
"Relu(Clip) means Relu should not be quantized.");
ReluNode *newRL = F->createRELU(RL->getName(), CN->getInput());
ClipNode *newCN =
F->createClip(CN->getName(), newRL->getResult(),
std::max(CN->getMin(), 0.0f), CN->getMax());
RL->getResult().replaceAllUsesOfWith(newCN);
changed = true;
continue;
}
}
// Sink Transpose below Clip nodes.
if (auto *CL = dyn_cast<ClipNode>(node)) {
auto *TR = dyn_cast<TransposeNode>(CL->getInput());
if (!TR) {
continue;
}
// Keep the same quantization parameters for Clip output, but
// change the shape to appropriate value.
auto clipOutTy = F->getParent()->uniqueTypeWithNewShape(
CL->getResult().getType(), TR->getInput().getType());
auto *NCL = F->createClip(CL->getName(), TR->getInput(), clipOutTy,
CL->getMin(), CL->getMax());
NCL->setPredicate(node->getPredicate());
auto *newTR = F->createTranspose(TR->getName(), NCL, TR->getShuffle());
newTR->setPredicate(node->getPredicate());
CL->getResult().replaceAllUsesOfWith(newTR);
changed = true;
continue;
}
// Sink Transpose below LeakyRelu nodes.
if (auto *LR = dyn_cast<LeakyReluNode>(node)) {
auto *TR = dyn_cast<TransposeNode>(LR->getInput());
if (!TR) {
continue;
}
auto newLROutTy = F->getParent()->uniqueTypeWithNewShape(
LR->getResult().getType(), TR->getInput().getType());
auto *newLR = F->createLeakyRELU(LR->getName(), newLROutTy,
TR->getInput(), LR->getAlpha());
newLR->setPredicate(node->getPredicate());
auto *newTR = F->createTranspose(TR->getName(), newLR, TR->getShuffle());
newTR->setPredicate(node->getPredicate());
LR->getResult().replaceAllUsesOfWith(newTR);
changed = true;
continue;
}
// Sink Transpose below PRelu with Splat.
if (auto *PN = dyn_cast<PReluNode>(node)) {
auto *TR = dyn_cast<TransposeNode>(PN->getInput());
if (!TR) {
continue;
}
auto *SN = dyn_cast<SplatNode>(PN->getSlope());
if (!SN) {
continue;
}
auto newSNOutTy = F->getParent()->uniqueTypeWithNewShape(
SN->getResult().getType(), TR->getInput().getType());
auto newPNOutTy = F->getParent()->uniqueTypeWithNewShape(
PN->getResult().getType(), TR->getInput().getType());
auto *newSN = F->createSplat(SN->getName(), newSNOutTy, SN->getValue());
auto *newPN =
F->createPRELU(PN->getName(), TR->getInput(), newSN, newPNOutTy);
auto *newTR = F->createTranspose(TR->getName(), newPN, TR->getShuffle());
newPN->setPredicate(node->getPredicate());
newTR->setPredicate(node->getPredicate());
PN->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(),
TR->getLayout());
newTR->setPredicate(node->getPredicate());
SI->getResult().replaceAllUsesOfWith(newTR);
changed = true;
continue;
}
// Sink Transpose below Tile nodes.
if (auto *TN = dyn_cast<TileNode>(node)) {
auto *TR = dyn_cast<TransposeNode>(TN->getInput());
if (!TR) {
continue;
}
auto *newTN = F->createTile(TN->getName(), TR->getInput(), TN->getCount(),
TR->getShuffle()[TN->getAxis()]);
newTN->setPredicate(node->getPredicate());
auto *newTR = F->createTranspose(TR->getName(), newTN, TR->getShuffle(),
TR->getLayout());
newTR->setPredicate(node->getPredicate());
TN->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<dim_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(),
TR->getLayout());
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'). Similarly, if one of the sides is a Constant,
// it can be seen as tranpose (Constant').
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(),
RTR->getLayout());