forked from openvinotoolkit/openvino
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_optimizer.cpp
More file actions
3647 lines (3097 loc) · 142 KB
/
graph_optimizer.cpp
File metadata and controls
3647 lines (3097 loc) · 142 KB
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) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "graph_optimizer.h"
#include <oneapi/dnnl/dnnl_common_types.h>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <limits>
#include <list>
#include <memory>
#include <numeric>
#include <optional>
#include <set>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "cpu/x64/cpu_isa_traits.hpp"
#include "cpu_types.h"
#include "dnnl_extension_utils.h"
#include "edge.h"
#include "itt.h"
#include "memory_desc/cpu_memory_desc_utils.h"
#include "node.h"
#include "nodes/bin_conv.h"
#include "nodes/common/cpu_convert.h"
#include "nodes/concat.h"
#include "nodes/conv.h"
#include "nodes/deconv.h"
#include "nodes/eltwise.h"
#include "nodes/fake_quantize.h"
#include "nodes/fullyconnected.h"
#include "nodes/input.h"
#include "nodes/interpolate.h"
#include "nodes/memory.hpp"
#include "nodes/memory_state_base.h"
#include "nodes/reorder.h"
#include "nodes/reshape.h"
#include "nodes/rnn.h"
#include "nodes/scaled_attn.h"
#include "nodes/transpose.h"
#include "onednn/dnnl.h"
#include "onednn/iml_type_mapper.h"
#include "openvino/core/except.hpp"
#include "openvino/core/type/element_type.hpp"
#include "openvino/itt.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "selective_build.h"
#include "utils/cpu_utils.hpp"
#include "utils/debug_capabilities.h"
#include "utils/general_utils.h"
// WA for xbyak.h
#ifdef _WIN32
# ifndef _WINSOCKAPI_
# define _WINSOCKAPI_
# endif
# ifndef _WINSOCK2API_
# define _WINSOCK2API_
# endif
#endif
using namespace dnnl;
using namespace ov::intel_cpu::node;
// Many GraphOptimizer passes are changing graphNodes collection while iterating which is not completely safe. So, it is
// impossible to use range based for loops.
// NOLINTBEGIN(modernize-loop-convert)
namespace ov::intel_cpu {
GraphOptimizer::GraphOptimizer() = default;
void GraphOptimizer::ApplyCommonGraphOptimizations(Graph& graph) {
// For conv with input zp, canBeExecutedInInt8() check has dependency on input zero point check.
// Also zero point node is the input of computing-intensive nodes. Most others fusing are the output of
// computing-intensive nodes. So Locate the FuseConvolutionAndZeroPoints() as the first optimization.
OV_ITT_SCOPE_CHAIN(FIRST_INFERENCE,
taskChain,
itt::domains::ov_intel_cpu_LT,
"ApplyCommonGraphOptimizations",
"FuseConvolutionAndZeroPoints");
FuseConvolutionAndZeroPoints(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseConvMatmulFCDeconvAndDQScales");
FuseConvMatmulFCDeconvAndDQScales(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseConvolutionAndBias");
FuseConvolutionMatMulDeconvAndBias(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseMultiplyAndAdd");
FuseMultiplyAndAdd(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "MergeConvertAndEltwise");
MergeConvertAndEltwise(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseFCAndConvertOnWeights");
FuseConvDeconvFCAndConvertOnWeights(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseFCAndTransposeOnWeights");
FuseFCAndTransposeOnWeights(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseDeconvolutionAndSimpleOperation");
FuseDeconvolutionAndSimpleOperation(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseClampAndFakeQuantize");
FuseClampAndFakeQuantize(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FusePerformedAsScaleShiftAndFakeQuantize");
FusePerformedAsScaleShiftAndFakeQuantize(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseConvolutionAndSimpleOperationThroughMaxPool");
FuseConvolutionAndSimpleOperationThroughMaxPool(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseConvolutionAndSimpleOperation");
FuseConvolutionAndSimpleOperation(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "RemoveDroppedEdges");
graph.SortTopologically();
graph.RemoveDroppedEdges();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FusePoolingAndFakeQuantize");
FusePoolingAndFakeQuantize(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "RemoveDroppedEdges");
graph.SortTopologically();
graph.RemoveDroppedEdges();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseConvolutionAndDWConvolution");
FuseConvolutionAndDWConvolution(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseConvolutionSumAndConvolutionSumActivation");
FuseConvolutionSumAndConvolutionSumActivation(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseConvolutionAndSimpleOperation");
FuseConvolutionAndSimpleOperation(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseFullyConnectedAndSimpleOperation");
FuseFullyConnectedAndSimpleOperation(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseMatMulAndSimpleOperation");
FuseMatMulAndSimpleOperation(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseMVNAndSimpleOperation");
FuseMVNAndSimpleOperation(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseInterpolateAndSimpleOperation");
FuseInterpolateAndSimpleOperation(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseNormalizeL2AndSimpleOperation");
FuseNormalizeL2AndSimpleOperation(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseReduceAndSimpleOperation");
FuseReduceAndSimpleOperation(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseGatherAndConvert");
FuseGatherAndConvert(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "FuseEltwiseAndSimple");
FuseEltwiseAndSimple(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "MergeEltwiseAndConvert");
MergeEltwiseAndConvert(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "reshapeRnnSeq");
reshapeRnnSeq(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "RemoveSameConvert");
RemoveSameConvert(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "RemoveMemoryInputConvert");
RemoveMemoryInputConvert(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "RemoveConvertMemoryOutput");
RemoveConvertMemoryOutput(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "MatchSdpaKvCache");
MatchSdpaKvCache(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "DropRedundantMemoryOutput");
DropRedundantMemoryOutput(graph);
graph.RemoveDroppedNodes();
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "RemoveDroppedEdges");
graph.RemoveDroppedEdges();
}
void GraphOptimizer::ApplyImplSpecificGraphOptimizations(Graph& graph) {
OV_ITT_SCOPE(FIRST_INFERENCE, itt::domains::ov_intel_cpu_LT, "GraphOptimizer::ApplyImplSpecificGraphOptimizations");
TailNodesPrecisionOptimize(graph);
graph.RemoveDroppedNodes();
DropDoubleReorders(graph);
graph.RemoveDroppedNodes();
MergeTransposeAndReorder(graph);
graph.RemoveDroppedNodes();
MergeReorderAndTranspose(graph);
graph.RemoveDroppedNodes();
graph.RemoveDroppedEdges();
}
void GraphOptimizer::FuseConvMatmulFCDeconvAndDQScales(Graph& graph) {
const auto& graphNodes = graph.GetNodes();
auto isDQScaleGraphPattern = [](const NodePtr& node) {
if (node->getType() != Type::Eltwise || node->getAlgorithm() != Algorithm::EltwiseMultiply) {
return false;
}
auto parentNode = node->getParentEdgeAt(0)->getParent();
auto scaleNode = node->getParentEdgeAt(1)->getParent();
if (none_of(parentNode->getType(), Type::Convolution, Type::MatMul, Type::Deconvolution)) {
return false;
}
if (!scaleNode->isConstant()) {
return false;
}
// Only Fusing scales for INT8 precision.
if (!parentNode->canBeExecutedInInt8()) {
return false;
}
return (parentNode->getParentEdges().size() == 2);
};
auto scaleDimsCheck = [](const NodePtr& node, const NodePtr& scales) {
const auto nodeOutDims = node->getOutputShapeAtPort(0).getDims();
const auto channelAxis = node->getFusingAxis();
OPENVINO_ASSERT(channelAxis >= 0 && channelAxis < static_cast<int>(nodeOutDims.size()),
"Incorrect channel axis for Conv/Deconv/MatMul node: ",
node->getName(),
", channel axis: ",
nodeOutDims.size());
auto OC = nodeOutDims[channelAxis];
if (Shape::UNDEFINED_DIM == OC) {
return false;
}
if (!node->getFusedWith().empty() || !scales->getFusedWith().empty()) {
return false;
}
const auto scalesDims = getNormalizedDimsBySize(scales->getOutputShapeAtPort(0).getDims(), nodeOutDims.size());
if (nodeOutDims.size() != scalesDims.size() || scalesDims.size() < 2) {
return false;
}
if (!dimsEqualStrong(scalesDims[channelAxis], nodeOutDims[channelAxis]) && scalesDims[channelAxis] != 1) {
return false;
}
for (size_t i = 0; i < scalesDims.size(); i++) {
if (scalesDims[i] != 1 && static_cast<int>(i) != channelAxis) {
return false;
}
}
return true;
};
auto initializeDeQuantizedScales = [](const NodePtr& node, const NodePtr& scales) {
auto* scalesConstant = dynamic_cast<node::Input*>(scales.get());
OPENVINO_ASSERT(scalesConstant, "Cannot cast to Input node");
auto scalesBlob = scalesConstant->getMemoryPtr();
OPENVINO_ASSERT(scalesBlob, "Cannot cast to TBlob internal scales blob");
const auto* scalesData = static_cast<const float*>(scalesBlob->getData());
OPENVINO_ASSERT(scalesData, "scalesBlob has not allocated buffer");
auto scalesDims = getNormalizedDimsBySize(scales->getOutputShapeAtPort(0).getDims(),
node->getOutputShapeAtPort(0).getDims().size());
auto scaleSize = std::accumulate(scalesDims.begin(), scalesDims.end(), 1, std::multiplies<>());
node->fuseDQScales(scalesData, scaleSize);
return true;
};
for (const auto& mul : graphNodes) {
if (!isDQScaleGraphPattern(mul)) {
continue;
}
CPU_GRAPH_OPTIMIZER_SCOPE(FuseConvMatmulFCDeconvAndDQScales);
auto node = mul->getParentEdgeAt(0)->getParent();
auto scales = mul->getParentEdgeAt(1)->getParent();
if (!scaleDimsCheck(node, scales)) {
continue;
}
if (initializeDeQuantizedScales(node, scales)) {
DEBUG_LOG("GraphOptimizer##FusingDQ: Node ##",
mul->getName(),
" optimized as DQ scales of Node ##",
node->getName());
node->addOriginalLayer(mul->getOriginalLayers());
auto p_edge = mul->getParentEdgeAt(1);
graph.RemoveEdge(p_edge);
graph.DropNode(mul);
}
}
}
void GraphOptimizer::FuseConvolutionMatMulDeconvAndBias(Graph& graph) {
const auto& graphNodes = graph.GetNodes();
auto isSuitableParentNode = [](const NodePtr& node) {
const auto deconv = std::dynamic_pointer_cast<Deconvolution>(node);
// bias should be the first child
if (!node->getFusedWith().empty()) {
return false;
}
// no other child other than bias-add
if (node->getChildEdges().size() != 1) {
return false;
}
if (!deconv) {
return (any_of(node->getType(), Type::Convolution, Type::MatMul) && node->getParentEdges().size() == 2);
}
return deconv->canFuseBias();
};
auto isSuitableChildNode = [&](const NodePtr& parentNode, const NodePtr& childNode) {
if (childNode->getAlgorithm() != Algorithm::EltwiseAdd || !childNode->getFusedWith().empty() ||
childNode->getParentEdges().size() != 2) {
return false;
}
auto biasPort = childNode->getParentEdgeAt(0)->getParent() == parentNode ? 1 : 0;
const auto biasNode = childNode->getParentEdgeAt(biasPort)->getParent();
if (biasNode->getType() != Type::Input || !biasNode->isConstant() || biasNode->getChildEdges().size() != 1) {
return false;
}
const auto parentOutDims = parentNode->getOutputShapeAtPort(0).getDims();
const auto biasDims =
getNormalizedDimsBySize(biasNode->getOutputShapeAtPort(0).getDims(), parentOutDims.size());
// TODO [NM]: Legacy ConvBias fusion transformation supports both per-tensor (via explicit broadcasing) and
// per-channel cases. Most of the real models contain per-channel bias, so we need to reavaluate the need to
// support per-tensor variant.
if (parentOutDims.size() != biasDims.size() || biasDims.size() < 2) {
return false;
}
const auto channelAxis = parentNode->getFusingAxis();
OPENVINO_ASSERT(channelAxis >= 0 && channelAxis < static_cast<int>(parentOutDims.size()),
"Incorrect channel axis for Conv/Deconv/MatMul node: ",
parentNode->getName(),
", output dims size: ",
parentOutDims.size());
if (!dimsEqualStrong(biasDims[channelAxis], parentOutDims[channelAxis])) {
return false;
}
for (size_t i = 0; i < biasDims.size(); i++) {
if (biasDims[i] != 1 && static_cast<int>(i) != channelAxis) {
return false;
}
}
return true;
};
for (size_t i = 0; i < graphNodes.size(); i++) {
auto parentNode = graphNodes[i];
if (!isSuitableParentNode(parentNode)) {
continue;
}
CPU_GRAPH_OPTIMIZER_SCOPE(FuseConvolutionMatMulDeconvAndBias_ParentNode);
auto childNode = parentNode->getChildEdgeAt(0)->getChild();
if (!isSuitableChildNode(parentNode, childNode)) {
continue;
}
CPU_GRAPH_OPTIMIZER_SCOPE(FuseConvolutionMatMulDeconvAndBias_ChildNode);
auto childs = childNode->childEdges;
auto parents = childNode->parentEdges;
const auto biasPort = childNode->getParentEdgeAt(0)->getParent() == parentNode ? 1 : 0;
for (const auto& i : parents) {
auto p_edge = i.lock();
if (!p_edge) {
continue;
}
auto parent = p_edge->getParent();
if (!parent) {
continue;
}
if (parent == parentNode) {
for (const auto& j : childs) {
if (!j.lock()) {
continue;
}
auto child = j.lock()->getChild();
if (!child) {
continue;
}
EdgePtr& remEdge = p_edge;
int inNum = 0;
if (remEdge) {
inNum = remEdge->getInputNum();
graph.RemoveEdge(remEdge);
}
remEdge = j.lock();
int outNum = 0;
if (remEdge) {
outNum = remEdge->getOutputNum();
graph.RemoveEdge(remEdge);
}
graph.CreateEdge(parent, child, inNum, outNum);
}
} else {
EdgePtr& remEdge = p_edge;
int inNum = 0;
if (remEdge) {
inNum = remEdge->getInputNum();
graph.RemoveEdge(remEdge);
}
auto& targetNode = parentNode;
const auto& biasNode = parent;
auto biasOutputShape = biasNode->getOutputShapeAtPort(0);
int outNum = targetNode->getParentEdges().size();
// ONEDNN Conv, Deconv, FC would need the bias to be flatten into 1D tensor.
// Usually the bias output shape would be normalized to align rank with Conv/Deconv/FC output.
// To avoid duplicate reshape WA code in nodes, here we flatten the shape.
// Most bias nodes are const Input and bias memory primitive has been initialized as const memory when
// constructing CPU Input node. Const memory is not allowed to be modified after initialized. It means
// we can't redefine const bias memory primitive. So let's insert a reshape node to flatten the bias
// shape into 1D and const folding node will be executed during the compiling stage.
const bool needReshape = (targetNode->getType() != Type::MatMul && biasOutputShape.getRank() != 1);
if (needReshape) {
// Bias -> Reshape -> Conv/Deconv/FC
const VectorDims flattenShape = {biasOutputShape.getElementsCount()};
// Construct Ngraph Reshape node and CPU Reshape node.
auto reshapeConstInput =
std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{1}, flattenShape);
auto reshapeDummyInput =
std::make_shared<ov::op::v0::Parameter>(biasNode->getOriginalOutputPrecisionAtPort(0),
biasOutputShape.toPartialShape());
const auto reshape =
std::make_shared<ov::op::v1::Reshape>(reshapeDummyInput, reshapeConstInput, false);
reshape->set_friendly_name(biasNode->getName() + "_flatten_reshape");
const auto cpuReshapeNode =
std::make_shared<ov::intel_cpu::node::Reshape>(reshape, graph.getGraphContext());
// Insert Reshape between bias node and Conv/Deconv/FC
graph.InsertNode(biasNode, targetNode, cpuReshapeNode, inNum, outNum, false);
// Insert the Reshape const input node and edge into CPU graph.
const auto cpuReshapeConstInput =
std::make_shared<node::Input>(reshapeConstInput, graph.getGraphContext());
graph.AddNode(cpuReshapeConstInput);
graph.CreateEdge(cpuReshapeConstInput, cpuReshapeNode, 0, 1);
DEBUG_LOG("GraphOptimizer##FusingBias:Flatten Bias node from shape ",
PartialShape{biasOutputShape.getDims()},
" to ",
PartialShape{flattenShape});
// Update bias output shape to be flatten shape.
biasOutputShape = Shape{flattenShape};
} else {
// Bias is connected as input edge.
graph.CreateEdge(biasNode, targetNode, inNum, outNum);
}
// Add the Bias inputshape into conv/FC/Deconv/Matmul.
targetNode->inputShapes.push_back(biasOutputShape);
}
}
DEBUG_LOG("GraphOptimizer##FusingBias:Node ##: ",
childNode->getName(),
" initialize as Bias of Node ##",
parentNode->getName());
parentNode->addOriginalLayer(childNode->getOriginalLayers());
parentNode->addOriginalInputPrecision(childNode->getOriginalInputPrecisionAtPort(biasPort));
graph.DropNode(childNode);
}
}
void GraphOptimizer::FuseDeconvolutionAndSimpleOperation(Graph& graph) {
const auto& graphNodes = graph.GetNodes();
auto isSuitableParentNode = [](const NodePtr& node) {
if (node->getType() != Type::Deconvolution || node->getChildEdges().size() != 1) {
return false;
}
const auto deconv = std::dynamic_pointer_cast<Deconvolution>(node);
OPENVINO_ASSERT(deconv, "Cannot cast to deconvolution node ", node->getName());
if (deconv->getAlgorithm() != Algorithm::DeconvolutionCommon) {
return true;
}
const auto& strides = deconv->getStride();
const auto& kernel = deconv->getWeightDims();
// WA oneDNN doesn't support fusing post ops after deconvolution with strides over kernel size
bool isSupportedParams = strides[strides.size() - 1] <= static_cast<dnnl_dim_t>(kernel[kernel.size() - 1]);
if (strides.size() > 1) {
isSupportedParams &= strides[strides.size() - 2] <= static_cast<dnnl_dim_t>(kernel[kernel.size() - 2]);
}
if (strides.size() > 2) {
isSupportedParams &= strides[strides.size() - 3] <= static_cast<dnnl_dim_t>(kernel[kernel.size() - 3]);
}
return isSupportedParams;
};
auto parent = graphNodes.begin();
while (parent != graphNodes.end()) {
auto parentNode = *parent;
if (!isSuitableParentNode(parentNode)) {
parent++;
continue;
}
CPU_GRAPH_OPTIMIZER_SCOPE(FuseDeconvolutionAndSimpleOperation_ParentNode);
auto childNode = parentNode->getChildEdgeAt(0)->getChild();
if (!parentNode->canFuse(childNode)) {
parent++;
continue;
}
CPU_GRAPH_OPTIMIZER_SCOPE(FuseDeconvolutionAndSimpleOperation_ChildNode);
childNode->fuseInto(parentNode);
auto parentEdges = childNode->parentEdges;
for (auto& parentEdge : parentEdges) {
auto p_edge = parentEdge.lock();
if (p_edge->getParent()->getType() == Type::Deconvolution) {
continue;
}
graph.RemoveEdge(p_edge);
}
graph.DropNode(childNode);
}
}
void GraphOptimizer::FuseMultiplyAndAdd(Graph& graph) {
const auto& graphNodes = graph.GetNodes();
auto isSuitableSecondInput = [](const NodePtr& node, VectorDims dataDims) {
if (node->getType() != Type::Input || !node->isConstant()) {
return false;
}
const auto secondInputDims = node->getOutputShapeAtPort(0).getStaticDims();
if (secondInputDims.size() != dataDims.size() || secondInputDims.size() < 2) {
return false;
}
auto getChannelAxis = [](const VectorDims& dims) {
auto channelAxis = -1;
for (size_t i = 0; i < dims.size(); i++) {
if (dims[i] != 1) {
if (channelAxis != -1) { // more than one axis is != 1
return -1;
}
channelAxis = i;
}
}
return channelAxis;
};
const auto channelAxis = getChannelAxis(secondInputDims);
if (channelAxis == -1) {
return false;
}
return secondInputDims[0] == 1 && dimsEqualWeak(secondInputDims[channelAxis], dataDims[channelAxis]);
};
auto isSuitableParentNode = [&](const NodePtr& node) {
if (node->getAlgorithm() != Algorithm::EltwiseMultiply || !node->getFusedWith().empty() ||
node->getParentEdges().size() != 2 || node->getChildEdges().size() != 1) {
return false;
}
return isSuitableSecondInput(node->getParentEdgeAt(1)->getParent(), node->getInputShapeAtPort(0).getDims());
};
auto isSuitableChildNode = [&](const NodePtr& parentNode, const NodePtr& childNode) {
if (childNode->getAlgorithm() != Algorithm::EltwiseAdd || !childNode->getFusedWith().empty() ||
childNode->getParentEdges().size() != 2) {
return false;
}
return isSuitableSecondInput(childNode->getParentEdgeAt(1)->getParent(),
childNode->getInputShapeAtPort(0).getDims()) &&
parentNode->canFuse(childNode);
};
auto parent = graphNodes.begin();
while (parent != graphNodes.end()) {
auto parentNode = *parent;
if (!isSuitableParentNode(parentNode)) {
parent++;
continue;
}
CPU_GRAPH_OPTIMIZER_SCOPE(FuseMultiplyAndAdd_ParentNode);
auto childNode = parentNode->getChildEdgeAt(0)->getChild();
if (!isSuitableChildNode(parentNode, childNode)) {
parent++;
continue;
}
CPU_GRAPH_OPTIMIZER_SCOPE(FuseMultiplyAndAdd_ChildNode);
auto childs = childNode->childEdges;
auto parents = childNode->parentEdges;
for (const auto& i : parents) {
auto p_edge = i.lock();
if (!p_edge) {
continue;
}
auto parent = p_edge->getParent();
if (!parent) {
continue;
}
if (parent == parentNode) {
for (const auto& j : childs) {
if (!j.lock()) {
continue;
}
auto child = j.lock()->getChild();
if (!child) {
continue;
}
EdgePtr& remEdge = p_edge;
int inNum = 0;
if (remEdge) {
inNum = remEdge->getInputNum();
graph.RemoveEdge(remEdge);
}
remEdge = j.lock();
int outNum = 0;
if (remEdge) {
outNum = remEdge->getOutputNum();
graph.RemoveEdge(remEdge);
}
graph.CreateEdge(parent, child, inNum, outNum);
}
} else {
EdgePtr& remEdge = p_edge;
int inNum = 0;
if (remEdge) {
inNum = remEdge->getInputNum();
graph.RemoveEdge(remEdge);
}
auto& parentEltwise = parentNode;
parentEltwise->inputShapes.push_back(parent->getOutputShapeAtPort(0));
graph.CreateEdge(parent, parentEltwise, inNum, parentEltwise->getParentEdges().size());
}
}
parentNode->addOriginalInputPrecision(childNode->getOriginalInputPrecisionAtPort(1));
parentNode->setAlgorithm(Algorithm::EltwiseMulAdd);
parentNode->setTypeStr("MulAdd");
parentNode->addOriginalLayer(childNode->getOriginalLayers());
graph.DropNode(childNode);
}
}
void GraphOptimizer::MergeEltwiseAndConvert(Graph& graph) {
// The pass is enabled on arm platforms only, however it might be usefull for other platforms as well
// It requires additional perf validation. Ticket: 163388
#if !defined(OPENVINO_ARCH_ARM64)
return;
#endif
const auto& graphNodes = graph.GetNodes();
auto parent = graphNodes.begin();
while (parent != graphNodes.end()) {
CPU_GRAPH_OPTIMIZER_SCOPE(MergeEltwiseAndConvert);
auto parentNode = *parent;
if (parentNode->getType() != Type::Eltwise) {
parent++;
continue;
}
const auto& childEdges = parentNode->getChildEdges();
if (childEdges.size() != 1) {
parent++;
continue;
}
const auto edge = childEdges[0].lock();
auto childNode = edge->getChild();
if (childNode->getType() != Type::Convert) {
parent++;
continue;
}
auto* const eltwise = dynamic_cast<ov::intel_cpu::node::Eltwise*>(parentNode.get());
if (!eltwise->canFuseConvert(childNode)) {
parent++;
continue;
}
// WA: Eltwise node uses precision of last fused node as output precision
auto fusedOps = parentNode->getFusedWith();
if (!fusedOps.empty()) {
fusedOps[fusedOps.size() - 1]->setOriginalOutputPrecisionAtPort(
0,
childNode->getOriginalOutputPrecisionAtPort(0));
}
parentNode->setOriginalOutputPrecisionAtPort(0, childNode->getOriginalOutputPrecisionAtPort(0));
parentNode->addOriginalLayer(childNode->getOriginalLayers());
graph.DropNode(childNode);
}
}
void GraphOptimizer::MergeConvertAndEltwise(Graph& graph) {
const auto& graphNodes = graph.GetNodes();
auto parent = graphNodes.begin();
while (parent != graphNodes.end()) {
CPU_GRAPH_OPTIMIZER_SCOPE(MergeConvertAndEltwise);
auto parentNode = *parent;
if (parentNode->getType() != Type::Convert) {
parent++;
continue;
}
const auto& childEdges = parentNode->getChildEdges();
if (childEdges.size() != 1) {
parent++;
continue;
}
const auto edge = childEdges[0].lock();
auto childNode = edge->getChild();
if (childNode->getType() != Type::Eltwise) {
parent++;
continue;
}
auto* const eltwise = dynamic_cast<ov::intel_cpu::node::Eltwise*>(childNode.get());
if (!eltwise->canFuseParent(parentNode)) {
parent++;
continue;
}
const auto parents = parentNode->parentEdges;
for (const auto& i : parents) {
auto p_edge = i.lock();
if (!p_edge) {
continue;
}
auto parent = p_edge->getParent();
if (!parent) {
continue;
}
if (!parentNode->childEdges[0].lock()) {
continue;
}
auto child = parentNode->childEdges[0].lock()->getChild();
if (!child) {
continue;
}
EdgePtr& remEdge = p_edge;
int inNum = 0;
if (remEdge) {
inNum = remEdge->getInputNum();
graph.RemoveEdge(remEdge);
}
remEdge = parentNode->childEdges[0].lock();
int outNum = 0;
if (remEdge) {
outNum = remEdge->getOutputNum();
graph.RemoveEdge(remEdge);
}
graph.CreateEdge(parent, child, inNum, outNum);
}
childNode->setOriginalInputPrecisionAtPort(0, parentNode->getOriginalInputPrecisionAtPort(0));
childNode->addOriginalLayer(parentNode->getOriginalLayers());
graph.DropNode(parentNode);
}
}
void GraphOptimizer::FuseConvDeconvFCAndConvertOnWeights(Graph& graph) {
#if defined(OV_CPU_WITH_SHL)
return;
#endif
// This optimization fuses Convert (fp16 -> bf16/fp32) on weights directly to FC input to allow precision conversion
// handling based on internal logic (e.g. fuse conversion with weights reordering)
auto isSuitableTranspose = [](const NodePtr& node) {
return node->getType() == Type::Transpose && node->getChildEdges().size() == 1 && node->isConstant();
};
auto isSuitableConvert = [&](const NodePtr& node) {
return node->getType() == Type::Convert && node->isConstant() &&
any_of(node->getOriginalInputPrecisionAtPort(0), ov::element::f16, ov::element::bf16) &&
any_of(node->getOriginalOutputPrecisionAtPort(0), ov::element::f32, ov::element::bf16);
};
const auto& graphNodes = graph.GetNodes();
for (const auto& fullyConnected : graphNodes) {
if (none_of(fullyConnected->getType(), Type::FullyConnected, Type::Convolution, Type::Deconvolution)) {
continue;
}
NodePtr transpose = nullptr;
auto parent = fullyConnected->getParentEdgeAt(1)->getParent();
if (parent->getType() == Type::Transpose) {
if (!isSuitableTranspose(parent)) {
continue;
}
transpose = parent;
parent = transpose->getParentEdgeAt(0)->getParent();
}
const auto convert = std::move(parent);
if (!isSuitableConvert(convert)) {
continue;
}
const auto weights = convert->getParentEdgeAt(0)->getParent();
const auto weights_out_edge = weights->getChildEdges()[0].lock();
const auto fc_weights_path_edge =
transpose ? transpose->getParentEdgeAt(0) : fullyConnected->getParentEdgeAt(1);
const auto inNum = weights_out_edge->getInputNum();
const auto outNum = fc_weights_path_edge->getOutputNum();
const auto originalPrecision = convert->getOriginalInputPrecisionAtPort(0);
fullyConnected->setOriginalInputPrecisionAtPort(1, originalPrecision);
if (transpose) {
transpose->setOriginalInputPrecisionAtPort(0, originalPrecision);
transpose->setOriginalOutputPrecisionAtPort(0, originalPrecision);
}
graph.RemoveEdge(fc_weights_path_edge);
graph.CreateEdge(weights, transpose ? transpose : fullyConnected, inNum, outNum);
if (convert->getChildEdges().empty()) {
graph.DropNode(convert);
}
}
}
void GraphOptimizer::FuseFCAndTransposeOnWeights(Graph& graph) {
#if defined(OV_CPU_WITH_SHL)
return;
#endif
// This optimization allows us to avoid transposing the weights in Transpose node and do it directly along with
// reordering in FC node
const auto& graphNodes = graph.GetNodes();
auto isSuitablePattern = [](const NodePtr& parent) {
bool res = parent->getType() == Type::Transpose && parent->getChildEdges().size() == 1 &&
parent->getChildEdgeAt(0)->getChild()->getType() == Type::FullyConnected && parent->isConstant();
return res;
};
for (const auto& parent : graphNodes) {
if (isSuitablePattern(parent)) {
CPU_GRAPH_OPTIMIZER_SCOPE(FuseFCAndTransposeOnWeights);
auto fcNode = std::dynamic_pointer_cast<FullyConnected>(parent->getChildEdgeAt(0)->getChild());
fcNode->keepWeightsNonTransposed(true);
auto transposeNode = std::dynamic_pointer_cast<Transpose>(parent);
transposeNode->setOptimized(true);
}
}
}
void GraphOptimizer::FuseConvolutionAndZeroPoints(Graph& graph) {
const auto& graphNodes = graph.GetNodes();
// zero points fusing is skipped on ARM platforms because oneDNN is not involved into int8 convolution inference
#if defined(OPENVINO_ARCH_ARM) || defined(OPENVINO_ARCH_ARM64)
return;
#endif
auto isSuitableConvNode = [](const NodePtr& node) {
bool retVal = false;
if (node->getType() == Type::Convolution) {
if (auto convNode = std::dynamic_pointer_cast<Convolution>(node)) {
auto rank = convNode->getInputShapeAtPort(0).getRank();
// int8 depthwise convolution does not support fusing zero points in 3D case
if (implication(convNode->isDepthWise(), rank < 5)) {
retVal = true;
}
}
}
return retVal;
};
auto initializeInputZeroPoints = [](const NodePtr& node, const NodePtr& parent0, const NodePtr& parent1) {
auto* convNode = dynamic_cast<Convolution*>(node.get());
OPENVINO_ASSERT(convNode, "Cannot get convolution node ", node->getName());
auto IC = node->getInputShapeAtPort(0).getDims()[1];
auto OC = node->getOutputShapeAtPort(0).getDims()[1];
if (any_of(Shape::UNDEFINED_DIM, IC, OC)) {
return false;
}
if (parent0->getType() != Type::Eltwise) {
return false;
}
if (!parent0->getFusedWith().empty() || !parent1->getFusedWith().empty()) {
return false;
}
// The plug-in doesn't support FP32 convolution with input/weights zero points.
// In case weights are in FP32 (or we have zero points on weights which are not supported by INT8 convolution)
// we cannot use INT8 implementation so we have to disable input zero points fusing as well.
if (parent1->getType() != Type::Input || !parent1->isConstant() ||
parent1->getOriginalOutputPrecisionAtPort(0) != ov::element::i8) {
return false;
}
if (parent0->getAlgorithm() != Algorithm::EltwiseSubtract) {
return false;
}
if (parent0->getParentEdges().size() != 2) {
return false;
}
auto subtractArg1 = parent0->getParentEdgeAt(1)->getParent();
if (subtractArg1->getType() != Type::Input || !subtractArg1->isConstant()) {
return false;
}
if (subtractArg1->getOriginalOutputPrecisionAtPort(0) != ov::element::u8) {
return false;
}
if (parent0->getInputShapeAtPort(1).getRank() < 2) {
return false;
}
auto zpDims = parent0->getInputShapeAtPort(1).getDims();
if (zpDims[0] != 1 || !dimsEqualStrong(zpDims[1], IC)) {
return false;
}
for (size_t i = 2; i < zpDims.size(); i++) {
if (zpDims[i] != 1) {
return false;
}
}
const auto& parentEdge = parent0->getParentEdgeAt(0);
const auto& subtractArg0 = parentEdge->getParent();